diff --git a/api/prisma/migrations/20260912125344_add_plan_gym_and_week_alias/migration.sql b/api/prisma/migrations/20260912125344_add_plan_gym_and_week_alias/migration.sql new file mode 100644 index 0000000..9dc61d7 --- /dev/null +++ b/api/prisma/migrations/20260912125344_add_plan_gym_and_week_alias/migration.sql @@ -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; diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma index 7b96c2a..b2f7ee5 100644 --- a/api/prisma/schema.prisma +++ b/api/prisma/schema.prisma @@ -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]) } diff --git a/api/src/routes/plans-schemas.ts b/api/src/routes/plans-schemas.ts index 97265da..510dedd 100644 --- a/api/src/routes/plans-schemas.ts +++ b/api/src/routes/plans-schemas.ts @@ -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'), }); diff --git a/api/src/routes/trainer.ts b/api/src/routes/trainer.ts index 261e3d1..1fec0e8 100644 --- a/api/src/routes/trainer.ts +++ b/api/src/routes/trainer.ts @@ -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 } */ diff --git a/api/src/services/plans.ts b/api/src/services/plans.ts index 0c18a04..f194cc3 100644 --- a/api/src/services/plans.ts +++ b/api/src/services/plans.ts @@ -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 }; diff --git a/api/src/swagger.ts b/api/src/swagger.ts index d31df10..cc794f3 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -364,7 +364,10 @@ export const openapi: Record = { 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 = { 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 = { 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 = { 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 = { }, 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 = { 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 = { 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 = { '/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 = { 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)', + }, ], }, }, diff --git a/api/test/integration/plans.test.ts b/api/test/integration/plans.test.ts index dae8339..150df05 100644 --- a/api/test/integration/plans.test.ts +++ b/api/test/integration/plans.test.ts @@ -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'); + }); }); diff --git a/api/test/unit/services-plans.test.ts b/api/test/unit/services-plans.test.ts index 52514af..73fecc9 100644 --- a/api/test/unit/services-plans.test.ts +++ b/api/test/unit/services-plans.test.ts @@ -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 } } } }, }, }); diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index 2cc347c..9f1d0d5 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -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) { 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, +) { 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) { diff --git a/app/src/api/types.ts b/app/src/api/types.ts index c928580..15d1a78 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -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; } diff --git a/app/src/components/plans/PlanWeeks.tsx b/app/src/components/plans/PlanWeeks.tsx index e64466b..13ef376 100644 --- a/app/src/components/plans/PlanWeeks.tsx +++ b/app/src/components/plans/PlanWeeks.tsx @@ -31,10 +31,15 @@ export function PlanDayRow({ actions?: ReactNode; }) { return ( -
+
-
diff --git a/app/src/pages/plans/PlanDetail.tsx b/app/src/pages/plans/PlanDetail.tsx index eb76a62..d0cfaf6 100644 --- a/app/src/pages/plans/PlanDetail.tsx +++ b/app/src/pages/plans/PlanDetail.tsx @@ -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() { {doneDays}/{allDays.length} dni - {plan.startDate && start: {fmtDate(plan.startDate)}} + {plan.gym && {plan.gym.name}} + {plan.startDate && ( + start: {fmtDate(plan.startDate)} + )} {creatorName && utworzył: {creatorName}}
{allDays.length > 0 && ( @@ -142,7 +162,9 @@ export default function PlanDetail() { style={{ width: `${planPercent}%` }} />
- {planPercent}% + + {planPercent}% +
)} {plan.status === 'DRAFT' && ( @@ -156,8 +178,8 @@ export default function PlanDetail() {

) : (

- 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.

)} diff --git a/app/src/pages/plans/PlanEditor.tsx b/app/src/pages/plans/PlanEditor.tsx index b221135..10309bf 100644 --- a/app/src/pages/plans/PlanEditor.tsx +++ b/app/src/pages/plans/PlanEditor.tsx @@ -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 ( +
+ {WIZARD_STEPS.map((s, i) => { + const done = step > s.n; + const active = step === s.n; + return ( +
+ {i > 0 &&
+ ); + })} +
+ ); +} + 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 ; } + // 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 ( <> -
+
+
- 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 */} -
- ({ - id: String(wi), - label: ( - - T.{wi + 1} - Tydzień {wi + 1} - - ), - }))} - active={String(activeWi)} - onChange={(id) => setActiveWeek(parseInt(id, 10))} + {step === 1 && ( + setTitleTouched(true)} + titleError={titleError} + weeksCount={editor.weeksCount} + onWeeksCountChange={editor.setWeeksCount} + startDate={editor.startDate} + onStartDateChange={editor.setStartDate} + startWeekError={startWeekError} + showStartWeek={!isEdit} /> -
+ )} -
- 0} - onCopyPrev={() => editor.copyPrevWeek(activeWi)} - canClear={weekDays.length > 0 || !week.detached} - onClear={() => setClearWeekIdx(activeWi)} - > - 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 */} + + + {gymOptions.length > 0 ? ( + + ) : ( +

+ {isTraineeMode ? ( + 'Podopieczny nie należy do żadnej siłowni.' + ) : ( + <> + Nie należysz do żadnej siłowni.{' '} + + Zarządzaj siłowniami + + + )} +

+ )} +
+
- {weekDays.length === 0 && ( - + ({ + id: String(wi), + label: ( + + T.{wi + 1} + Tydzień {wi + 1} + + ), + }))} + active={String(activeWi)} + onChange={(id) => setActiveWeek(parseInt(id, 10))} /> - )} +
- {weekDays.length > 0 && ( -
- {weekDays.map((d, di) => ( - { - 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) +
+ 0} + onCopyPrev={() => editor.copyPrevWeek(activeWi)} + canClear={weekDays.length > 0 || !week.detached} + onClear={() => setClearWeekIdx(activeWi)} + alias={week.customName} + onAliasChange={(v) => editor.setWeekAlias(activeWi, v)} + > + 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 && ( + 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); - }} /> - ))} -
- )} - -
+ )} + + {weekDays.length > 0 && ( +
+ {weekDays.map((d, di) => ( + { + 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); + }} + /> + ))} +
+ )} + +
+ + )} + + {step === 3 && ( + + )} {/* sticky stopka; na mobile pod stałym dolnym paskiem topmenu (+ safe-area) */}
{error && {error}} -
- {dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '} - {setCountLabel(totals.sets)} - {totals.emptyWeeks > 0 && ( - · {weekCountLabel(totals.emptyWeeks)} bez ćwiczeń - )} +
+
+ {dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '} + {setCountLabel(totals.sets)} + {totals.emptyWeeks > 0 && ( + · {weekCountLabel(totals.emptyWeeks)} bez ćwiczeń + )} +
+
+ {step > 1 && ( + + )} + {step < 3 ? ( + + ) : ( + + )} +
diff --git a/app/src/pages/plans/plan-editor/PlanSummary.tsx b/app/src/pages/plans/plan-editor/PlanSummary.tsx new file mode 100644 index 0000000..7695df5 --- /dev/null +++ b/app/src/pages/plans/plan-editor/PlanSummary.tsx @@ -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 ( + +

{title || 'Bez tytułu'}

+
+ + + {gymName ?? 'bez siłowni'} + + {startDate ? `start: ${fmtDate(startDate)}` : 'szkic — bez startu'} +
+ +
+ {rows.map((r) => ( +
+
+

{r.alias || `Tydzień ${r.i + 1}`}

+ {r.exercises === 0 && bez ćwiczeń} + + {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)} + +
+
+ ))} +
+ +
+ Łącznie: {dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '} + {setCountLabel(totals.sets)} + {totals.empty > 0 && ( + · {weekCountLabel(totals.empty)} bez ćwiczeń + )} +
+
+ ); +} diff --git a/app/src/pages/plans/plan-editor/WeekPanel.tsx b/app/src/pages/plans/plan-editor/WeekPanel.tsx index 584ab36..f1ac3c9 100644 --- a/app/src/pages/plans/plan-editor/WeekPanel.tsx +++ b/app/src/pages/plans/plan-editor/WeekPanel.tsx @@ -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({ )}
+ {alias !== undefined && onAliasChange && ( +
+ + onAliasChange(e.target.value)} + placeholder="np. Deload" + maxLength={40} + /> + +
+ )}
{children}
); diff --git a/app/src/pages/plans/plan-editor/types.ts b/app/src/pages/plans/plan-editor/types.ts index ecdb5a4..394e75b 100644 --- a/app/src/pages/plans/plan-editor/types.ts +++ b/app/src/pages/plans/plan-editor/types.ts @@ -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) => ({ diff --git a/app/src/pages/plans/plan-editor/usePlanEditorState.ts b/app/src/pages/plans/plan-editor/usePlanEditorState.ts index e3c3259..497f9ee 100644 --- a/app/src/pages/plans/plan-editor/usePlanEditorState.ts +++ b/app/src/pages/plans/plan-editor/usePlanEditorState.ts @@ -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[0][]; } @@ -21,17 +23,19 @@ export function usePlanEditorState() { const [weeks, setWeeks] = useState(() => Array.from({ length: 4 }, () => emptyWeek()), ); + // Siłownia planu (informacyjna): null = „bez siłowni”. + const [gymId, setGymIdState] = useState(null); const [initialized, setInitialized] = useState(false); // snapshot startowy: tryb nowy = stan początkowy; tryb edycji = po initFromPlan const snapshotRef = useRef(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, diff --git a/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx b/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx index 0399225..652aef0 100644 --- a/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx +++ b/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx @@ -39,7 +39,11 @@ export function TraineePlansTab({ userId }: { userId: string }) { const { data, isLoading, error } = useTraineePlans(userId); const { data: meData } = useMe(); const [selectedId, setSelectedId] = useState(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 ( -
+
{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 }) {
{selectedDetail.weeks.map((w) => (
-

Tydzień {w.index + 1}

- {w.days.length === 0 &&

Brak dni treningowych.

} +
+

Tydzień {w.index + 1}

+ {w.customName && {w.customName}} +
+ {w.days.length === 0 && ( +

Brak dni treningowych.

+ )}
{w.days.map((d) => ( diff --git a/app/test/PlanEditor.test.tsx b/app/test/PlanEditor.test.tsx index 618ca82..4842c3c 100644 --- a/app/test/PlanEditor.test.tsx +++ b/app/test/PlanEditor.test.tsx @@ -40,7 +40,7 @@ interface Capture { createPlanBody?: Record; } -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(); diff --git a/app/test/e2e/mock-api.ts b/app/test/e2e/mock-api.ts index 7b5cb2e..3ae2575 100644 --- a/app/test/e2e/mock-api.ts +++ b/app/test/e2e/mock-api.ts @@ -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 }) }); }); diff --git a/app/test/e2e/plan-wizard.spec.ts b/app/test/e2e/plan-wizard.spec.ts new file mode 100644 index 0000000..be2b280 --- /dev/null +++ b/app/test/e2e/plan-wizard.spec.ts @@ -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(); +}); diff --git a/app/test/e2e/plans-mobile.spec.ts b/app/test/e2e/plans-mobile.spec.ts index c756b14..61eed54 100644 --- a/app/test/e2e/plans-mobile.spec.ts +++ b/app/test/e2e/plans-mobile.spec.ts @@ -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(); diff --git a/app/test/e2e/plans.spec.ts b/app/test/e2e/plans.spec.ts index ff98340..c26621f 100644 --- a/app/test/e2e/plans.spec.ts +++ b/app/test/e2e/plans.spec.ts @@ -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(); diff --git a/app/test/e2e/trainee-plans.spec.ts b/app/test/e2e/trainee-plans.spec.ts index cc936f1..4e34541 100644 --- a/app/test/e2e/trainee-plans.spec.ts +++ b/app/test/e2e/trainee-plans.spec.ts @@ -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(); diff --git a/app/test/plan-editor-state.test.ts b/app/test/plan-editor-state.test.ts index c29a78b..cd49e4c 100644 --- a/app/test/plan-editor-state.test.ts +++ b/app/test/plan-editor-state.test.ts @@ -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); diff --git a/app/test/trainee-plans.test.tsx b/app/test/trainee-plans.test.tsx index 16eb9e5..2d378ee 100644 --- a/app/test/trainee-plans.test.tsx +++ b/app/test/trainee-plans.test.tsx @@ -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 } } = {}) { 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 } = {}; + 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