From 27a1507e506fb0fcf6c4b8984c1edd2b8ef13dfe Mon Sep 17 00:00:00 2001 From: Tilumca Date: Thu, 15 Oct 2026 01:42:26 +0200 Subject: [PATCH] Plany: wznowienie ukonczonego/porzuconego planu (poprawki bez tworzenia nowego, blokada przy innym aktywnym) --- admin/src/pages/Logs.tsx | 1 + api/src/routes/plans.ts | 28 ++++++ api/src/routes/trainer.ts | 31 ++++++ api/src/services/plans.ts | 29 ++++++ api/src/swagger.ts | 57 +++++++++-- api/test/integration/plans.test.ts | 92 ++++++++++++++++++ api/test/integration/trainer.test.ts | 45 +++++++++ api/test/unit/services-plans.test.ts | 41 ++++++++ app/src/api/queries.ts | 26 +++-- app/src/components/plans/PlanActions.tsx | 46 ++++++++- app/src/pages/plans/PlanDetail.tsx | 36 ++++++- .../trainee-detail/TraineePlansTab.tsx | 25 ++++- app/test/PlanDetail.test.tsx | 47 +++++++++ app/test/e2e/mock-api.ts | 29 +++++- app/test/e2e/trainee-plans.spec.ts | 50 +++++++++- app/test/trainee-plans.test.tsx | 97 ++++++++++++++++++- 16 files changed, 649 insertions(+), 31 deletions(-) diff --git a/admin/src/pages/Logs.tsx b/admin/src/pages/Logs.tsx index 2b76815..08bd72d 100644 --- a/admin/src/pages/Logs.tsx +++ b/admin/src/pages/Logs.tsx @@ -21,6 +21,7 @@ export const ACTION_LABELS: Record = { 'plan.activated': 'Plan aktywowany', 'plan.abandoned': 'Plan porzucony', 'plan.completed': 'Plan ukończony', + 'plan.reopened': 'Plan wznowiony', 'session.started': 'Sesja rozpoczęta', 'session.completed': 'Sesja zakończona', 'session.abandoned': 'Sesja porzucona', diff --git a/api/src/routes/plans.ts b/api/src/routes/plans.ts index 69806b1..4b8f22d 100644 --- a/api/src/routes/plans.ts +++ b/api/src/routes/plans.ts @@ -13,6 +13,7 @@ import { getPlan, listPlans, listSharedWithMe, + reopenPlan, sharePlan, unsharePlan, updatePlan, @@ -250,6 +251,33 @@ export function createPlanRoutes({ prisma }: AppDeps) { }), ); + /** + * @openapi + * /plans/{id}/reopen: + * post: + * summary: Reopen a completed or abandoned plan (back to ACTIVE) + * tags: [Plans] + * responses: + * 200: { description: OK } + * 400: { description: Only a completed or abandoned plan can be reopened } + * 409: { description: User already has an active plan } + */ + router.post( + '/:id/reopen', + asyncHandler(async (req, res) => { + await assertPlanOwner(prisma, req.params.id, req.user!.id); + const result = await reopenPlan(prisma, req.params.id, req.user!.id); + await logActivity(prisma, { + actorId: req.user!.id, + action: 'plan.reopened', + entityType: 'plan', + entityId: req.params.id, + details: { title: result.title }, + }); + res.json(result); + }), + ); + /** * @openapi * /plans/{id}/share: diff --git a/api/src/routes/trainer.ts b/api/src/routes/trainer.ts index b141a4d..0c4f9e3 100644 --- a/api/src/routes/trainer.ts +++ b/api/src/routes/trainer.ts @@ -33,6 +33,7 @@ import { deletePlan, getPlan, listPlans, + reopenPlan, updatePlan, } from '../services/plans.js'; import { activateSchema, createPlanSchema, updatePlanSchema } from './plans-schemas.js'; @@ -639,6 +640,36 @@ export function createTrainerRoutes({ prisma }: AppDeps) { }), ); + /** + * @openapi + * /trainer/trainees/{userId}/plans/{planId}/reopen: + * post: + * summary: Reopen the trainee's completed/abandoned plan (back to ACTIVE) + * tags: [Trainer] + * responses: + * 200: { description: OK } + * 400: { description: Only a completed or abandoned plan can be reopened } + * 403: { description: Trainer role required } + * 404: { description: Trainee or plan not found } + * 409: { description: Trainee already has an active plan } + */ + router.post( + '/trainees/:userId/plans/:planId/reopen', + trainerOnly, + asyncHandler(async (req, res) => { + await assertActiveTrainee(prisma, req.user!.id, req.params.userId); + const result = await reopenPlan(prisma, req.params.planId, req.user!.id); + await logActivity(prisma, { + actorId: req.user!.id, + action: 'plan.reopened', + entityType: 'plan', + entityId: req.params.planId, + details: { title: result.title, traineeId: req.params.userId }, + }); + res.json(result); + }), + ); + /** * @openapi * /trainer/trainees/{userId}/comments: diff --git a/api/src/services/plans.ts b/api/src/services/plans.ts index 32f16e5..02e1a9c 100644 --- a/api/src/services/plans.ts +++ b/api/src/services/plans.ts @@ -414,6 +414,35 @@ export async function completePlan(prisma: PrismaClient, planId: string, userId: return { ok: true, title: plan.title }; } +/** + * Cofnięcie zamknięcia planu (COMPLETED/ABANDONED -> ACTIVE). Służy do naprawy + * pomyłek (np. błędnie oznaczony plan) — dni SKIPPED nie są wskrzeszane, a plan + * bez dni zaplanowanych zostanie ponownie ukończony przez scheduler, gdy tylko + * wszystkie dni pozostaną domknięte. + */ +export async function reopenPlan(prisma: PrismaClient, planId: string, userId: string) { + const plan = await assertPlanAccess(prisma, planId, userId); + if (plan.status !== 'COMPLETED' && plan.status !== 'ABANDONED') + throw badRequest('Only a completed or abandoned plan can be reopened'); + // Jeden aktywny plan dotyczy właściciela (inicjatorem może być trener). + // Pre-check + częściowy indeks unikalny (TrainingPlan_userId_active_key) + // rozstrzyga równoległe wznowienia/aktywacje. + const otherActive = await prisma.trainingPlan.findFirst({ + where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id } }, + }); + if (otherActive) throw conflict('User already has an active plan'); + try { + await prisma.trainingPlan.update({ + where: { id: plan.id }, + data: { status: 'ACTIVE' }, + }); + } catch (e) { + if (isPrismaUnique(e)) throw conflict('User already has an active plan'); + throw e; + } + return { ok: true, title: plan.title }; +} + /** * The owner shares the plan with a user in an ACTIVE coaching relation * (trainer <-> trainee, either direction). Recipients get read-only access. diff --git a/api/src/swagger.ts b/api/src/swagger.ts index c70c1a1..4ae034b 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -204,7 +204,8 @@ export const openapi: Record = { }, post: { tags: ['Gyms'], - summary: 'Create a gym (creator becomes OWNER; admins only for REAL, REAL requires address)', + summary: + 'Create a gym (creator becomes OWNER; admins only for REAL, REAL requires address)', security: [{ bearerAuth: [] }], requestBody: { required: true, @@ -716,16 +717,34 @@ export const openapi: Record = { '/plans/{id}/complete': { post: { tags: ['Plans'], - summary: 'Manually archive plan (only from ACTIVE status and only when no training day is still planned; an in-progress plan can only be abandoned)', + summary: + 'Manually archive plan (only from ACTIVE status and only when no training day is still planned; an in-progress plan can only be abandoned)', security: [{ bearerAuth: [] }], parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], responses: { 200: { description: 'OK' }, - 400: { description: 'Only an active plan can be completed / plan has pending training days' }, + 400: { + description: 'Only an active plan can be completed / plan has pending training days', + }, 404: { description: 'Plan not found' }, }, }, }, + '/plans/{id}/reopen': { + post: { + tags: ['Plans'], + summary: + 'Reopen a completed or abandoned plan (back to ACTIVE; skipped days are not revived)', + security: [{ bearerAuth: [] }], + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + responses: { + 200: { description: 'OK' }, + 400: { description: 'Only a completed or abandoned plan can be reopened' }, + 404: { description: 'Plan not found' }, + 409: { description: 'User already has an active plan' }, + }, + }, + }, '/plans/{id}/share': { post: { tags: ['Plans'], @@ -936,14 +955,22 @@ export const openapi: Record = { properties: { name: { type: 'string' }, ownerId: { type: 'string', description: 'User mianowany właścicielem (OWNER)' }, - addressLine1: { type: 'string', description: 'Ulica i numer, np. Mokotowska 12A' }, - addressLine2: { type: 'string', nullable: true, description: 'Lokal/piętro itp.' }, + addressLine1: { + type: 'string', + description: 'Ulica i numer, np. Mokotowska 12A', + }, + addressLine2: { + type: 'string', + nullable: true, + description: 'Lokal/piętro itp.', + }, postalCode: { type: 'string', description: 'Kod pocztowy 00-001' }, city: { type: 'string' }, countryCode: { type: 'string', default: 'PL', description: 'ISO 3166-1 alpha-2' }, location: { type: 'string', - description: 'Pole derivowane z adresu (ulica, kod miasto[, kraj]) — nie do zapisu', + description: + 'Pole derivowane z adresu (ulica, kod miasto[, kraj]) — nie do zapisu', }, availability: { type: 'array', @@ -1007,10 +1034,22 @@ export const openapi: Record = { name: { type: 'string' }, addressLine1: { type: 'string', nullable: true }, addressLine2: { type: 'string', nullable: true }, - postalCode: { type: 'string', nullable: true, description: 'Kod pocztowy 00-001' }, + postalCode: { + type: 'string', + nullable: true, + description: 'Kod pocztowy 00-001', + }, city: { type: 'string', nullable: true }, - countryCode: { type: 'string', nullable: true, description: 'ISO 3166-1 alpha-2' }, - availability: { type: 'array', nullable: true, items: { type: 'object', nullable: true } }, + countryCode: { + type: 'string', + nullable: true, + description: 'ISO 3166-1 alpha-2', + }, + availability: { + type: 'array', + nullable: true, + items: { type: 'object', nullable: true }, + }, capacity: { type: 'integer', nullable: true }, }, }, diff --git a/api/test/integration/plans.test.ts b/api/test/integration/plans.test.ts index 9daf8ac..ef99cc6 100644 --- a/api/test/integration/plans.test.ts +++ b/api/test/integration/plans.test.ts @@ -419,6 +419,98 @@ describe('plans routes', () => { expect(again.status).toBe(400); }); + it('rejects reopening a draft plan with 400', async () => { + const app = buildApp(); + const created = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${token}`) + .send(planBody('Draft reopen')); + const res = await app + .post(`/api/v1/plans/${created.body.plan.id}/reopen`) + .set('Authorization', `Bearer ${token}`); + expect(res.status).toBe(400); + expect(res.body.error.message).toBe('Only a completed or abandoned plan can be reopened'); + }); + + it('reopens a completed or abandoned plan', async () => { + const app = buildApp(); + const created = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${token}`) + .send(planBody('Reopen me')); + const id = created.body.plan.id; + await app + .post(`/api/v1/plans/${id}/activate`) + .set('Authorization', `Bearer ${token}`) + .send({ startDate: MONDAY }); + await prisma.planDay.updateMany({ where: { week: { planId: id } }, data: { status: 'COMPLETED' } }); + const completed = await app + .post(`/api/v1/plans/${id}/complete`) + .set('Authorization', `Bearer ${token}`); + expect(completed.status).toBe(200); + + const reopened = await app + .post(`/api/v1/plans/${id}/reopen`) + .set('Authorization', `Bearer ${token}`); + expect(reopened.status).toBe(200); + const stored = await prisma.trainingPlan.findUnique({ where: { id } }); + expect(stored!.status).toBe('ACTIVE'); + + // aktywny plan znów tylko się porzuca — i da się wznowić także po porzuceniu + const again = await app + .post(`/api/v1/plans/${id}/reopen`) + .set('Authorization', `Bearer ${token}`); + expect(again.status).toBe(400); + const abandoned = await app + .post(`/api/v1/plans/${id}/abandon`) + .set('Authorization', `Bearer ${token}`); + expect(abandoned.status).toBe(200); + const reopened2 = await app + .post(`/api/v1/plans/${id}/reopen`) + .set('Authorization', `Bearer ${token}`); + expect(reopened2.status).toBe(200); + + // sprzątanie — zwolnij slot aktywnego planu + await app.post(`/api/v1/plans/${id}/abandon`).set('Authorization', `Bearer ${token}`); + }); + + it('rejects reopening when the user has another active plan with 409', async () => { + const app = buildApp(); + // plan A: ukończony, plan B: aktywny — wznowienie A koliduje z B + const a = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${token}`) + .send(planBody('Closed A')); + const aId = a.body.plan.id; + await app + .post(`/api/v1/plans/${aId}/activate`) + .set('Authorization', `Bearer ${token}`) + .send({ startDate: MONDAY }); + await prisma.planDay.updateMany({ where: { week: { planId: aId } }, data: { status: 'COMPLETED' } }); + await app.post(`/api/v1/plans/${aId}/complete`).set('Authorization', `Bearer ${token}`); + + const b = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${token}`) + .send(planBody('Active B')); + const activated = await app + .post(`/api/v1/plans/${b.body.plan.id}/activate`) + .set('Authorization', `Bearer ${token}`) + .send({ startDate: MONDAY }); + expect(activated.status).toBe(200); + + const res = await app + .post(`/api/v1/plans/${aId}/reopen`) + .set('Authorization', `Bearer ${token}`); + expect(res.status).toBe(409); + expect(res.body.error.message).toBe('User already has an active plan'); + + // sprzątanie + await app + .post(`/api/v1/plans/${b.body.plan.id}/abandon`) + .set('Authorization', `Bearer ${token}`); + }); + it('deletes a draft plan', async () => { const app = buildApp(); const created = await app diff --git a/api/test/integration/trainer.test.ts b/api/test/integration/trainer.test.ts index f5a2259..b705139 100644 --- a/api/test/integration/trainer.test.ts +++ b/api/test/integration/trainer.test.ts @@ -845,6 +845,51 @@ describe('trainer — managing a trainee plan', () => { expect(res.status).toBe(200); }); + it('rejects reopening an active plan with 400', async () => { + const created = await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans`) + .set('Authorization', `Bearer ${trainer.token}`) + .send(planBody('Reopen active')); + await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/activate`) + .set('Authorization', `Bearer ${trainer.token}`) + .send({ startDate: mondayIso(1) }); + const res = await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/reopen`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(res.status).toBe(400); + expect(res.body.error.message).toBe('Only a completed or abandoned plan can be reopened'); + // sprzątanie — zwolnij slot aktywnego planu + await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/abandon`) + .set('Authorization', `Bearer ${trainer.token}`); + }); + + it('reopens a trainee plan abandoned by the trainer', async () => { + const created = await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans`) + .set('Authorization', `Bearer ${trainer.token}`) + .send(planBody('Trainer reopen')); + const id = created.body.plan.id; + await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/activate`) + .set('Authorization', `Bearer ${trainer.token}`) + .send({ startDate: mondayIso(1) }); + await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/abandon`) + .set('Authorization', `Bearer ${trainer.token}`); + const res = await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/reopen`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(res.status).toBe(200); + const stored = await prisma.trainingPlan.findUnique({ where: { id } }); + expect(stored!.status).toBe('ACTIVE'); + // sprzątanie + await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/abandon`) + .set('Authorization', `Bearer ${trainer.token}`); + }); + it('deletes a draft plan', async () => { const created = await app .post(`/api/v1/trainer/trainees/${trainee.id}/plans`) diff --git a/api/test/unit/services-plans.test.ts b/api/test/unit/services-plans.test.ts index 97e8ef1..7d38f3b 100644 --- a/api/test/unit/services-plans.test.ts +++ b/api/test/unit/services-plans.test.ts @@ -10,6 +10,7 @@ import { getPlan, listPlans, listSharedWithMe, + reopenPlan, sharePlan, unsharePlan, updatePlan, @@ -146,6 +147,46 @@ describe('draft-only rules', () => { data: { status: 'COMPLETED' }, }); }); + + it('reopenPlan: rejects a draft plan with 400', async () => { + const { prisma } = mockPrisma(); + prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan); + await expect(reopenPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({ + status: 400, + message: 'Only a completed or abandoned plan can be reopened', + }); + }); + + it('reopenPlan: rejects an active plan with 400', async () => { + const { prisma } = mockPrisma(); + prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' }); + await expect(reopenPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({ + status: 400, + message: 'Only a completed or abandoned plan can be reopened', + }); + }); + + it('reopenPlan: rejects when the owner has another active plan with 409', async () => { + const { prisma } = mockPrisma(); + prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' }); + prisma.trainingPlan.findFirst.mockResolvedValue({ id: 'p2', status: 'ACTIVE' }); + await expect(reopenPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({ + status: 409, + message: 'User already has an active plan', + }); + expect(prisma.trainingPlan.update).not.toHaveBeenCalled(); + }); + + it('reopenPlan: reopens a completed plan', async () => { + const { prisma } = mockPrisma(); + prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' }); + prisma.trainingPlan.findFirst.mockResolvedValue(null); + await expect(reopenPlan(prisma, 'p1', 'u1')).resolves.toEqual({ ok: true }); + expect(prisma.trainingPlan.update).toHaveBeenCalledWith({ + where: { id: 'p1' }, + data: { status: 'ACTIVE' }, + }); + }); }); describe('createPlan', () => { diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index c6f6371..7f09205 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -161,14 +161,16 @@ export interface GymAddressBody { countryCode?: string | null; } -export function createGym(body: { - name: string; - location?: string | null; - availability?: Availability | null; - capacity?: number | null; - kind?: GymKind; - isPrivate?: boolean; -} & GymAddressBody) { +export function createGym( + body: { + name: string; + location?: string | null; + availability?: Availability | null; + capacity?: number | null; + kind?: GymKind; + isPrivate?: boolean; + } & GymAddressBody, +) { return api<{ gym: UserGym }>('/gyms', { method: 'POST', body }); } @@ -478,6 +480,10 @@ export function completePlan(id: string) { return api(`/plans/${id}/complete`, { method: 'POST' }); } +export function reopenPlan(id: string) { + return api(`/plans/${id}/reopen`, { method: 'POST' }); +} + // ---------- sessions ---------- export function useSession(id: string) { return useQuery({ @@ -803,3 +809,7 @@ export function abandonTraineePlan(userId: string, planId: string) { export function completeTraineePlan(userId: string, planId: string) { return api(`/trainer/trainees/${userId}/plans/${planId}/complete`, { method: 'POST' }); } + +export function reopenTraineePlan(userId: string, planId: string) { + return api(`/trainer/trainees/${userId}/plans/${planId}/reopen`, { method: 'POST' }); +} diff --git a/app/src/components/plans/PlanActions.tsx b/app/src/components/plans/PlanActions.tsx index c39d8eb..035f073 100644 --- a/app/src/components/plans/PlanActions.tsx +++ b/app/src/components/plans/PlanActions.tsx @@ -5,8 +5,8 @@ import type { Plan } from '../../api/types'; /** * Akcje planu zależne od statusu (DRAFT: Aktywuj/Edytuj/Usuń + WeekPicker + hint; - * ACTIVE: Oznacz jako ukończony/Porzuć) + actionError. Współdzielone przez - * PlanDetail i zakładkę „Plany" panelu podopiecznego. + * ACTIVE: Oznacz jako ukończony/Porzuć; COMPLETED/ABANDONED: Wznów) + actionError. + * Współdzielone przez PlanDetail i zakładkę „Plany" panelu podopiecznego. */ export function PlanActions({ plan, @@ -19,8 +19,10 @@ export function PlanActions({ onDelete, onComplete, onAbandon, + onReopen, hint, activateDisabled, + reopenDisabled, }: { plan: Plan; editTo: string; @@ -32,10 +34,13 @@ export function PlanActions({ onDelete: () => void; onComplete: () => void; onAbandon: () => void; + onReopen: () => void; /** Podpowiedź pod WeekPicker (DRAFT). */ hint?: string; /** Blokada aktywacji (np. właściciel ma już inny aktywny plan). */ activateDisabled?: boolean; + /** Blokada wznowienia (właściciel ma już inny aktywny plan). */ + reopenDisabled?: boolean; }) { // Aktywny plan w trakcie realizacji (został dzień PLANNED) można tylko // porzucić — „Oznacz jako ukończony" pojawia się po domknięciu wszystkich dni. @@ -59,7 +64,12 @@ export function PlanActions({ Edytuj - @@ -68,16 +78,42 @@ export function PlanActions({ {plan.status === 'ACTIVE' && ( <> {!hasPendingDays && ( - )} - )} + {(plan.status === 'COMPLETED' || plan.status === 'ABANDONED') && ( + + )} + {(plan.status === 'COMPLETED' || plan.status === 'ABANDONED') && reopenDisabled && ( +

+ Podopieczny ma już aktywny plan — tylko jeden plan może być aktywny. Aby wznowić ten plan, + najpierw ukończ lub porzuć aktywny. +

+ )} {plan.status === 'DRAFT' && (

Tydzień startu

diff --git a/app/src/pages/plans/PlanDetail.tsx b/app/src/pages/plans/PlanDetail.tsx index 2dee999..0083ac3 100644 --- a/app/src/pages/plans/PlanDetail.tsx +++ b/app/src/pages/plans/PlanDetail.tsx @@ -1,12 +1,13 @@ import { useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useQueryClient } from '@tanstack/react-query'; -import { CalendarDays, MapPin, Pencil, Play, Share2, Trash2 } from 'lucide-react'; +import { CalendarDays, MapPin, Pencil, Play, RotateCcw, Share2, Trash2 } from 'lucide-react'; import { abandonPlan, activatePlan, completePlan, deletePlan, + reopenPlan, useMe, usePlan, usePlans, @@ -41,7 +42,7 @@ export default function PlanDetail() { const [startDate, setStartDate] = useState(''); const [actionError, setActionError] = useState(''); const [busy, setBusy] = useState(false); - const [confirm, setConfirm] = useState(null); + const [confirm, setConfirm] = useState(null); const planData = data?.plan; const [shareOpen, setShareOpen] = useState(false); @@ -125,7 +126,16 @@ export default function PlanDetail() { onClick: () => setConfirm('abandon'), }, ] - : []), + : // plan zamknięty (ukończony/porzucony) — można wznowić w celu poprawek + [ + { + label: 'Wznów', + icon: RotateCcw, + variant: 'secondary' as const, + disabled: busy || hasOtherActivePlan, + onClick: () => setConfirm('reopen'), + }, + ]), // udostępnianie = tylko właściciel planu ...(isOwner ? [ @@ -223,6 +233,14 @@ export default function PlanDetail() { )}
)} + {(plan.status === 'COMPLETED' || plan.status === 'ABANDONED') && + canManage && + hasOtherActivePlan && ( +

+ Masz już aktywny plan — tylko jeden plan może być aktywny. Aby wznowić ten plan, + najpierw ukończ lub porzuć aktywny. +

+ )} @@ -254,6 +272,18 @@ export default function PlanDetail() { danger busy={busy} /> + setConfirm(null)} + onConfirm={() => { + setConfirm(null); + act(() => reopenPlan(plan.id), 'Plan wznowiony'); + }} + title="Wznowić plan?" + description="Plan wróci do statusu aktywnego — błędne sesje poprawisz w ich tygodniach. Pominięte dni pozostaną pominięte." + confirmLabel="Wznów" + busy={busy} + /> ); } diff --git a/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx b/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx index 652aef0..d474181 100644 --- a/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx +++ b/app/src/pages/trainees/trainee-detail/TraineePlansTab.tsx @@ -5,6 +5,7 @@ import { activateTraineePlan, completeTraineePlan, deleteTraineePlan, + reopenTraineePlan, useMe, useTraineePlan, useTraineePlans, @@ -26,11 +27,14 @@ import { import { useToast } from '../../../components/toast'; import type { Plan } from '../../../api/types'; -type PlanAction = { type: 'delete' | 'abandon' | 'complete' | 'activate'; planId: string }; +type PlanAction = { + type: 'delete' | 'abandon' | 'complete' | 'activate' | 'reopen'; + planId: string; +}; /** * Zakładka „Plany" w panelu podopiecznego: lista planów podopiecznego + akcje - * (edytuj/aktywuj/usuń/porzuć/ukończ) + podgląd struktury inline. + * (edytuj/aktywuj/usuń/porzuć/ukończ/wznów) + podgląd struktury inline. * Tworzenie planu: akcja „Utwórz plan" w menu kontekstowym strony (TraineeDetail). */ export function TraineePlansTab({ userId }: { userId: string }) { @@ -148,7 +152,11 @@ export function TraineePlansTab({ userId }: { userId: string }) { onAbandon={() => setConfirm({ type: 'abandon', planId: selectedDetail.id }) } + onReopen={() => + setConfirm({ type: 'reopen', planId: selectedDetail.id }) + } activateDisabled={hasActivePlan} + reopenDisabled={hasActivePlan} hint={ hasActivePlan ? 'Podopieczny ma już aktywny plan — tylko jeden plan może być aktywny. Aby aktywować ten plan, najpierw ukończ lub porzuć aktywny.' @@ -237,6 +245,19 @@ export function TraineePlansTab({ userId }: { userId: string }) { confirmLabel="Ukończ" busy={busy} /> + setConfirm(null)} + onConfirm={() => { + const planId = confirm!.planId; + setConfirm(null); + void act(() => reopenTraineePlan(userId, planId), 'Plan wznowiony'); + }} + title="Wznowić plan?" + description="Plan wróci do statusu aktywnego — błędne sesje poprawisz w ich tygodniach. Pominięte dni pozostaną pominięte." + confirmLabel="Wznów" + busy={busy} + /> ); } diff --git a/app/test/PlanDetail.test.tsx b/app/test/PlanDetail.test.tsx index 1bcb8d5..df679a1 100644 --- a/app/test/PlanDetail.test.tsx +++ b/app/test/PlanDetail.test.tsx @@ -118,6 +118,7 @@ interface MockOpts { interface Capture { shareBody?: Record; + reopenUrl?: string; } function mockApi(capture: Capture, opts: MockOpts) { @@ -160,6 +161,10 @@ function mockApi(capture: Capture, opts: MockOpts) { if (method === 'DELETE') return jsonResponse(200, { ok: true }); } if (url.endsWith('/plans')) return jsonResponse(200, { plans: opts.plans ?? [] }); + if (url.includes('/plans/plan-1/reopen') && method === 'POST') { + capture.reopenUrl = url; + return jsonResponse(200, { ok: true }); + } if (url.includes('/plans/plan-1')) return jsonResponse(200, { plan: opts.plan ?? planDetail() }); return jsonResponse(200, {}); @@ -318,3 +323,45 @@ describe('PlanDetail — udostępnianie planów (WP4)', () => { expect(screen.getByText('udostępnione: Anna Nowak')).toBeInTheDocument(); }); }); + +describe('PlanDetail — statusy i klikalność dni', () => { + it('plan ukończony: akcja „Wznów”; potwierdzenie = POST /plans/:id/reopen', async () => { + const capture: Capture = {}; + const closed = planDetail({ status: 'COMPLETED' }); + mockApi(capture, { user: OWNER, plans: [closed], plan: closed }); + const user = userEvent.setup(); + renderApp(); + await loginAndOpenPlans(user, OWNER.email); + + await user.click(screen.getByRole('link', { name: /Otwórz/ })); + expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument(); + + const header = document.querySelector('header')!; + await user.click(within(header).getByRole('button', { name: 'Wznów' })); + const dialog = await screen.findByRole('dialog', { name: 'Wznowić plan?' }); + await user.click(within(dialog).getByRole('button', { name: 'Wznów' })); + await waitFor(() => expect(capture.reopenUrl).toContain('/plans/plan-1/reopen')); + }); + + it('plan ukończony przy innym aktywnym: „Wznów” zablokowany + hint', async () => { + const closed = planDetail({ status: 'COMPLETED' }); + const other = planDetail({ + id: 'plan-2', + title: 'Inny plan', + status: 'ACTIVE', + weeksCount: 1, + startDate: '2026-10-12', + }); + mockApi({}, { user: OWNER, plans: [closed, other], plan: closed }); + const user = userEvent.setup(); + renderApp(); + await loginAndOpenPlans(user, OWNER.email); + + await user.click(screen.getByRole('link', { name: /Plan masowy/ })); + expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument(); + + const header = document.querySelector('header')!; + expect(within(header).getByRole('button', { name: 'Wznów' })).toBeDisabled(); + expect(screen.getByText(/Aby wznowić ten plan/)).toBeInTheDocument(); + }); +}); diff --git a/app/test/e2e/mock-api.ts b/app/test/e2e/mock-api.ts index 71290fb..6bf7374 100644 --- a/app/test/e2e/mock-api.ts +++ b/app/test/e2e/mock-api.ts @@ -514,6 +514,17 @@ export const TEST_TRAINEE_PLANS = [ creator: null, weeks: [], }, + { + id: 'tp-4', + userId: 'trainee-1', + title: 'Plan ukończony', + status: 'COMPLETED', + weeksCount: 1, + startDate: '2026-08-24', + gym: null, + creator: null, + weeks: [], + }, ]; export const TEST_TRAINEE_PLAN_DETAIL = { @@ -647,6 +658,14 @@ export const TEST_TRAINEE_PLAN_DETAIL_FINISHED = { ], }; +/** Plan ukończony — dostępna akcja „Wznów" (reopen w celu poprawek). */ +export const TEST_TRAINEE_PLAN_DETAIL_DONE = { + ...TEST_TRAINEE_PLAN_DETAIL_FINISHED, + id: 'tp-4', + title: 'Plan ukończony', + status: 'COMPLETED', +}; + export const TEST_TRAINEE_LATEST_RESULTS = [ { exerciseId: 'ex-1', name: 'Przysiady', muscle: 'legs', date: '2026-08-24', sets: [{ reps: 12, loadKg: 70 }], oneRm: 80.6 }, ]; @@ -1657,7 +1676,12 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) { if (req.method() === 'PATCH' || req.method() === 'DELETE') { return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) }); } - if (url.includes('/activate') || url.includes('/abandon') || url.includes('/complete')) { + if ( + url.includes('/activate') || + url.includes('/abandon') || + url.includes('/complete') || + url.includes('/reopen') + ) { return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) }); } if (url.endsWith('/tp-2')) { @@ -1666,6 +1690,9 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) { if (url.endsWith('/tp-3')) { return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_FINISHED }) }); } + if (url.endsWith('/tp-4')) { + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_DONE }) }); + } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL }) }); }); page.route('**/api/v1/trainer/trainees/*/plans', (route) => { diff --git a/app/test/e2e/trainee-plans.spec.ts b/app/test/e2e/trainee-plans.spec.ts index a69a713..6c0add0 100644 --- a/app/test/e2e/trainee-plans.spec.ts +++ b/app/test/e2e/trainee-plans.spec.ts @@ -1,5 +1,10 @@ import { test, expect } from './fixtures'; -import { mockTraineePlans, TEST_GYM_OWNED, TEST_USER } from './mock-api'; +import { + mockTraineePlans, + TEST_GYM_OWNED, + TEST_TRAINEE_PLANS, + TEST_USER, +} from './mock-api'; function trainerMe() { return { @@ -8,8 +13,22 @@ function trainerMe() { }; } -async function openTraineePlansTab(page: import('@playwright/test').Page) { +async function openTraineePlansTab( + page: import('@playwright/test').Page, + opts: { plansOverride?: unknown[] } = {}, +) { mockTraineePlans(page, { me: trainerMe() }); + // lista zarejestrowana później ma pierwszeństwo (Playwright: ostatni route wygrywa) + if (opts.plansOverride) { + const plans = opts.plansOverride; + await page.route('**/api/v1/trainer/trainees/trainee-1/plans', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ plans }), + }), + ); + } await page.goto('/login'); await page.locator('input[type="email"]').fill('test@fitos.pl'); await page.locator('input[type="password"]').fill('haslo123'); @@ -88,6 +107,33 @@ test('zakładka Plany: blokada aktywacji szkicu, gdy podopieczny ma już aktywny await expect(page.getByRole('button', { name: 'Aktywuj' })).toBeDisabled(); }); +test('zakładka Plany: ukończony plan — „Wznów" zablokowany, gdy podopieczny ma aktywny plan', async ({ + page, +}) => { + await openTraineePlansTab(page); + + await page.getByRole('button', { name: 'Plan ukończony' }).click(); + // aktywny plan podopiecznego (tp-2) blokuje wznowienie + await expect(page.getByRole('button', { name: 'Wznów' })).toBeDisabled(); + await expect(page.getByText(/Aby wznowić ten plan/)).toBeVisible(); +}); + +test('zakładka Plany: ukończony plan — „Wznów" = dialog + POST reopen + toast', async ({ + page, +}) => { + // bez innego aktywnego planu — przycisk odblokowany + await openTraineePlansTab(page, { plansOverride: [TEST_TRAINEE_PLANS[3]] }); + + await page.getByRole('button', { name: 'Plan ukończony' }).click(); + await page.getByRole('button', { name: 'Wznów' }).click(); + + const dialog = page.getByRole('dialog'); + await expect(dialog.getByText('Wznowić plan?')).toBeVisible(); + await dialog.getByRole('button', { name: 'Wznów' }).click(); + await expect(dialog).toHaveCount(0); + await expect(page.getByRole('status').getByText('Plan wznowiony')).toBeVisible(); +}); + test('edytor planu podopiecznego: „Wstaw wyniki" prefylluje serie z ostatniej sesji', async ({ page, }) => { diff --git a/app/test/trainee-plans.test.tsx b/app/test/trainee-plans.test.tsx index d926d02..4267e31 100644 --- a/app/test/trainee-plans.test.tsx +++ b/app/test/trainee-plans.test.tsx @@ -217,6 +217,63 @@ const FINISHED_DETAIL = { ], }; +// Plan ukończony — dostępna akcja „Wznów" (reopen w celu poprawek). +const PLAN_DONE = { + id: 'plan-4', + title: 'Plan ukończony', + status: 'COMPLETED', + weeksCount: 1, + startDate: '2026-08-24', + creator: null, + weeks: [], +}; + +const DONE_DETAIL = { + id: 'plan-4', + title: 'Plan ukończony', + status: 'COMPLETED', + weeksCount: 1, + startDate: '2026-08-24', + creator: null, + weeks: [ + { + id: 'w1', + index: 0, + days: [ + { + id: 'd1', + dayOfWeek: 1, + date: '2026-08-24', + status: 'COMPLETED', + moveLog: [], + sessions: [], + exercises: [ + { + id: 'pe4', + exerciseId: 'ex-2', + order: 0, + exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' }, + sets: [ + { + id: 's4', + index: 0, + reps: 8, + loadKg: 40, + restSec: 90, + rir: 2, + cardioBpm: null, + timeSec: null, + speed: null, + }, + ], + }, + ], + }, + ], + }, + ], +}; + const LATEST_RESULTS = [ { exerciseId: 'ex-1', @@ -248,7 +305,10 @@ function jsonResponse(status: number, body: unknown) { } function mockApi( - opts: { plans?: unknown[]; capture?: { createBody?: Record } } = {}, + opts: { + plans?: unknown[]; + capture?: { createBody?: Record; reopenUrl?: string }; + } = {}, ) { const plans = opts.plans ?? PLANS; vi.stubGlobal( @@ -285,6 +345,13 @@ function mockApi( return jsonResponse(200, { plan: ACTIVE_DETAIL }); if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans/plan-3`)) return jsonResponse(200, { plan: FINISHED_DETAIL }); + if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans/plan-4`)) { + if (method === 'POST' && url.includes('/reopen')) { + if (opts.capture) opts.capture.reopenUrl = url; + return jsonResponse(200, { ok: true }); + } + return jsonResponse(200, { plan: DONE_DETAIL }); + } if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans`)) { if (method === 'POST') { if (opts.capture) opts.capture.createBody = JSON.parse(String(init?.body)); @@ -400,6 +467,34 @@ describe('Zakładka „Plany" w panelu podopiecznego', () => { expect(await screen.findByRole('button', { name: 'Porzuć' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Oznacz jako ukończony' })).toBeInTheDocument(); }); + + it('ukończony plan: akcja „Wznów"; potwierdzenie = POST …/reopen', async () => { + const capture: { reopenUrl?: string } = {}; + // bez innego aktywnego planu — przycisk odblokowany + mockApi({ plans: [PLAN_DONE], capture }); + const user = userEvent.setup(); + renderAt(`/trainees/${TRAINEE_ID}?tab=plans`); + + await screen.findByRole('heading', { name: 'Plany podopiecznego' }); + await user.click(screen.getByRole('button', { name: 'Plan ukończony' })); + + await user.click(await screen.findByRole('button', { name: 'Wznów' })); + const dialog = await screen.findByRole('dialog', { name: 'Wznowić plan?' }); + await user.click(within(dialog).getByRole('button', { name: 'Wznów' })); + await waitFor(() => expect(capture.reopenUrl).toContain('/plans/plan-4/reopen')); + }); + + it('ukończony plan przy innym aktywnym: „Wznów" zablokowany + hint', async () => { + mockApi({ plans: [PLAN_DONE, PLANS[1]] }); + const user = userEvent.setup(); + renderAt(`/trainees/${TRAINEE_ID}?tab=plans`); + + await screen.findByRole('heading', { name: 'Plany podopiecznego' }); + await user.click(screen.getByRole('button', { name: 'Plan ukończony' })); + + expect(await screen.findByRole('button', { name: 'Wznów' })).toBeDisabled(); + expect(screen.getByText(/Aby wznowić ten plan/)).toBeInTheDocument(); + }); }); describe('PlanEditor — tryb podopiecznego', () => {