Plany: blokada recznego ukonczenia planu z planowanymi treningami (w trakcie realizacji zostaje tylko porzucenie)

This commit is contained in:
Tilumca
2026-10-15 01:20:52 +02:00
parent 85a5cd9e99
commit 8044b0a4bd
11 changed files with 239 additions and 19 deletions

View File

@@ -614,11 +614,11 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/complete:
* post:
* summary: Mark the trainee's plan as completed
* summary: Mark the trainee's plan as completed (only when no training day is still planned)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Plan already closed }
* 400: { description: Plan already closed / plan has pending training days }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/

View File

@@ -400,6 +400,13 @@ export async function completePlan(prisma: PrismaClient, planId: string, userId:
const plan = await assertPlanAccess(prisma, planId, userId);
// Tylko aktywny plan można ukończyć — DRAFT nie zaczął się jeszcze realizować.
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be completed');
// Ręczne ukończenie tylko po domknięciu wszystkich dni (completed/skipped —
// ta sama reguła co auto-ukończenie w schedulerze). Plan w trakcie realizacji
// (dzień PLANNED = trening przed nami) można wyłącznie porzucić.
const pending = await prisma.planDay.count({
where: { week: { planId: plan.id }, status: 'PLANNED' },
});
if (pending > 0) throw badRequest('Plan has pending training days — it can only be abandoned');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'COMPLETED' },

View File

@@ -716,12 +716,12 @@ export const openapi: Record<string, unknown> = {
'/plans/{id}/complete': {
post: {
tags: ['Plans'],
summary: 'Manually archive plan (only from ACTIVE status)',
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' },
400: { description: 'Only an active plan can be completed / plan has pending training days' },
404: { description: 'Plan not found' },
},
},

View File

@@ -366,6 +366,31 @@ describe('plans routes', () => {
expect(res.body.error.message).toBe('Only an active plan can be completed');
});
it('rejects completing an active plan with pending training days with 400', async () => {
const app = buildApp();
const created = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send(planBody('In progress'));
const id = created.body.plan.id;
const activated = await app
.post(`/api/v1/plans/${id}/activate`)
.set('Authorization', `Bearer ${token}`)
.send({ startDate: MONDAY });
expect(activated.status).toBe(200);
const res = await app
.post(`/api/v1/plans/${id}/complete`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Plan has pending training days — it can only be abandoned');
// w trakcie realizacji pozostaje tylko porzucenie
const abandoned = await app
.post(`/api/v1/plans/${id}/abandon`)
.set('Authorization', `Bearer ${token}`);
expect(abandoned.status).toBe(200);
});
it('completes an active plan and refuses to close it twice', async () => {
const app = buildApp();
const created = await app
@@ -378,6 +403,11 @@ describe('plans routes', () => {
.set('Authorization', `Bearer ${token}`)
.send({ startDate: MONDAY });
expect(activated.status).toBe(200);
// wszystkie dni domknięte — dopiero wtedy plan można ukończyć ręcznie
await prisma.planDay.updateMany({
where: { week: { planId: id } },
data: { status: 'COMPLETED' },
});
const res = await app
.post(`/api/v1/plans/${id}/complete`)
.set('Authorization', `Bearer ${token}`);

View File

@@ -827,6 +827,18 @@ describe('trainer — managing a trainee plan', () => {
.set('Authorization', `Bearer ${trainer.token}`)
.send({ startDate: mondayIso(1) });
expect(activated.status).toBe(200);
// plan w trakcie realizacji (dni PLANNED) — najpierw odmowa, potem domknięcie dni
const pending = await app
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/complete`)
.set('Authorization', `Bearer ${trainer.token}`);
expect(pending.status).toBe(400);
expect(pending.body.error.message).toBe(
'Plan has pending training days — it can only be abandoned',
);
await prisma.planDay.updateMany({
where: { week: { planId: created.body.plan.id } },
data: { status: 'COMPLETED' },
});
const res = await app
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/complete`)
.set('Authorization', `Bearer ${trainer.token}`);

View File

@@ -33,6 +33,7 @@ function mockPrisma() {
exercise: { findMany: vi.fn() },
coaching: { findUnique: vi.fn(), findMany: vi.fn() },
planWeek: { findMany: vi.fn() },
planDay: { count: vi.fn() },
planShare: {
findUnique: vi.fn(),
create: vi.fn(),
@@ -123,6 +124,28 @@ describe('draft-only rules', () => {
message: 'Only an active plan can be completed',
});
});
it('completePlan: rejects an active plan with pending training days with 400', async () => {
const { prisma } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' });
prisma.planDay.count.mockResolvedValue(1);
await expect(completePlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Plan has pending training days — it can only be abandoned',
});
expect(prisma.trainingPlan.update).not.toHaveBeenCalled();
});
it('completePlan: completes an active plan once no day is planned (skipped days allowed)', async () => {
const { prisma } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' });
prisma.planDay.count.mockResolvedValue(0);
await expect(completePlan(prisma, 'p1', 'u1')).resolves.toEqual({ ok: true });
expect(prisma.trainingPlan.update).toHaveBeenCalledWith({
where: { id: 'p1' },
data: { status: 'COMPLETED' },
});
});
});
describe('createPlan', () => {

View File

@@ -37,6 +37,9 @@ export function PlanActions({
/** Blokada aktywacji (np. właściciel ma już inny aktywny plan). */
activateDisabled?: boolean;
}) {
// Aktywny plan w trakcie realizacji (został dzień PLANNED) można tylko
// porzucić — „Oznacz jako ukończony" pojawia się po domknięciu wszystkich dni.
const hasPendingDays = plan.weeks.flatMap((w) => w.days).some((d) => d.status === 'PLANNED');
return (
<>
<div className="flex flex-col sm:flex-row gap-3">
@@ -64,9 +67,11 @@ export function PlanActions({
)}
{plan.status === 'ACTIVE' && (
<>
<Button variant="secondary" disabled={busy} onClick={onComplete} className="w-full sm:w-auto">
Oznacz jako ukończony
</Button>
{!hasPendingDays && (
<Button variant="secondary" disabled={busy} onClick={onComplete} className="w-full sm:w-auto">
Oznacz jako ukończony
</Button>
)}
<Button variant="danger" disabled={busy} onClick={onAbandon} className="w-full sm:w-auto">
Porzuć
</Button>

View File

@@ -53,6 +53,11 @@ export default function PlanDetail() {
const hasOtherActivePlan = (plansData?.plans ?? []).some(
(p) => p.status === 'ACTIVE' && p.id !== planData?.id,
);
// Aktywny plan w trakcie realizacji (został dzień PLANNED) można tylko
// porzucić — „Oznacz jako ukończony" pojawia się po domknięciu wszystkich dni.
const hasPendingDays = (planData?.weeks ?? [])
.flatMap((w) => w.days)
.some((d) => d.status === 'PLANNED');
const act = async (fn: () => Promise<unknown>, msg: string) => {
setActionError('');
@@ -101,12 +106,18 @@ export default function PlanDetail() {
]
: planData.status === 'ACTIVE'
? [
{
label: 'Oznacz jako ukończony',
variant: 'secondary' as const,
disabled: busy,
onClick: () => void act(() => completePlan(planData.id), 'Plan ukończony'),
},
// plan w trakcie realizacji (dni PLANNED) można tylko porzucić
...(hasPendingDays
? []
: [
{
label: 'Oznacz jako ukończony',
variant: 'secondary' as const,
disabled: busy,
onClick: () =>
void act(() => completePlan(planData.id), 'Plan ukończony'),
},
]),
{
label: 'Porzuć',
variant: 'danger' as const,

View File

@@ -503,6 +503,17 @@ export const TEST_TRAINEE_PLANS = [
creator: null,
weeks: [],
},
{
id: 'tp-3',
userId: 'trainee-1',
title: 'Plan domknięty',
status: 'ACTIVE',
weeksCount: 1,
startDate: '2026-08-24',
gym: null,
creator: null,
weeks: [],
},
];
export const TEST_TRAINEE_PLAN_DETAIL = {
@@ -600,6 +611,42 @@ export const TEST_TRAINEE_PLAN_DETAIL_ACTIVE = {
],
};
/** Plan aktywny bez zaplanowanych dni (wszystkie ukończone) — można go ukończyć ręcznie. */
export const TEST_TRAINEE_PLAN_DETAIL_FINISHED = {
...TEST_TRAINEE_PLAN_DETAIL_ACTIVE,
id: 'tp-3',
title: 'Plan domknięty',
weeksCount: 1,
weeks: [
{
id: 'tw-3',
index: 0,
customName: null,
days: [
{
id: 'td-3',
dayOfWeek: 1,
date: '2026-08-24',
status: 'COMPLETED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'tpe-3',
exerciseId: 'ex-2',
order: 0,
exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
sets: [
{ id: 'tps-3', index: 0, reps: 8, loadKg: 40, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null },
],
},
],
},
],
},
],
};
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 },
];
@@ -1616,6 +1663,9 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) {
if (url.endsWith('/tp-2')) {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_ACTIVE }) });
}
if (url.endsWith('/tp-3')) {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_FINISHED }) });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL }) });
});
page.route('**/api/v1/trainer/trainees/*/plans', (route) => {

View File

@@ -31,9 +31,9 @@ test('zakładka Plany: lista planów podopiecznego z badge statusu i etykietą t
await expect(page.getByRole('button', { name: 'Utwórz plan' })).toBeVisible();
await expect(page.getByText('Plan masowy')).toBeVisible();
await expect(page.getByText('Plan aktywny')).toBeVisible();
// badge statusu (exact — tytuł planu zawiera „aktywny")
// badge statusu (exact — tytuł planu zawiera „aktywny"); dwa plany ACTIVE
await expect(page.getByText('Szkic', { exact: true })).toBeVisible();
await expect(page.getByText('Aktywny', { exact: true })).toBeVisible();
await expect(page.getByText('Aktywny', { exact: true })).toHaveCount(2);
// etykieta twórcy (twórca ≠ zalogowany trener)
await expect(page.getByText('utworzył: Jan Kowalski')).toBeVisible();
});
@@ -51,11 +51,22 @@ test('zakładka Plany: szkic — akcje Edytuj/Aktywuj/Usuń i struktura inline',
await expect(page.getByText(/Przysiady/)).toBeVisible();
});
test('zakładka Plany: aktywny — akcje „Oznacz jako ukończony" i „Porzuć"', async ({ page }) => {
test('zakładka Plany: aktywny w trakcie realizacji — tylko „Porzuć"', async ({ page }) => {
await openTraineePlansTab(page);
await page.getByRole('button', { name: 'Plan aktywny' }).click();
await expect(page.getByRole('button', { name: 'Porzuć' })).toBeVisible();
// dzień PLANNED = trening przed nami — planu nie da się oznaczyć jako ukończony
await expect(page.getByRole('button', { name: 'Oznacz jako ukończony' })).toHaveCount(0);
});
test('zakładka Plany: aktywny bez zaplanowanych dni — akcje „Oznacz jako ukończony" i „Porzuć"', async ({
page,
}) => {
await openTraineePlansTab(page);
await page.getByRole('button', { name: 'Plan domknięty' }).click();
await expect(page.getByRole('button', { name: 'Porzuć' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Oznacz jako ukończony' })).toBeVisible();
});

View File

@@ -67,6 +67,15 @@ const PLANS = [
creator: null,
weeks: [],
},
{
id: 'plan-3',
title: 'Plan domknięty',
status: 'ACTIVE',
weeksCount: 1,
startDate: '2026-08-24',
creator: null,
weeks: [],
},
];
const DRAFT_DETAIL = {
@@ -161,6 +170,53 @@ const ACTIVE_DETAIL = {
],
};
// Plan aktywny bez zaplanowanych dni (wszystkie domknięte) — dostępny „Oznacz jako ukończony".
const FINISHED_DETAIL = {
id: 'plan-3',
title: 'Plan domknięty',
status: 'ACTIVE',
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: 'pe3',
exerciseId: 'ex-2',
order: 0,
exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
sets: [
{
id: 's3',
index: 0,
reps: 8,
loadKg: 40,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
],
},
],
},
],
};
const LATEST_RESULTS = [
{
exerciseId: 'ex-1',
@@ -227,6 +283,8 @@ function mockApi(
}
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans/plan-2`))
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`)) {
if (method === 'POST') {
if (opts.capture) opts.capture.createBody = JSON.parse(String(init?.body));
@@ -286,9 +344,9 @@ describe('Zakładka „Plany" w panelu podopiecznego', () => {
expect(screen.getByRole('button', { name: 'Utwórz plan' })).toBeInTheDocument();
expect(screen.getByText('Plan masowy')).toBeInTheDocument();
expect(screen.getByText('Plan aktywny')).toBeInTheDocument();
// badge statusu
// badge statusu (dwa plany ACTIVE: plan-2 i plan-3)
expect(screen.getByText('Szkic')).toBeInTheDocument();
expect(screen.getByText('Aktywny')).toBeInTheDocument();
expect(screen.getAllByText('Aktywny')).toHaveLength(2);
// etykieta twórcy (twórca ≠ zalogowany trener)
expect(screen.getByText('utworzył: Jan Kowalski')).toBeInTheDocument();
});
@@ -318,7 +376,7 @@ describe('Zakładka „Plany" w panelu podopiecznego', () => {
expect(screen.getByText(/Przysiady/)).toBeInTheDocument();
});
it('aktywny: akcje „Oznacz jako ukończony" i „Porzuć"', async () => {
it('aktywny w trakcie realizacji: tylko „Porzuć" (brak „Oznacz jako ukończony")', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}?tab=plans`);
@@ -326,6 +384,19 @@ describe('Zakładka „Plany" w panelu podopiecznego', () => {
await screen.findByRole('heading', { name: 'Plany podopiecznego' });
await user.click(screen.getByRole('button', { name: 'Plan aktywny' }));
expect(await screen.findByRole('button', { name: 'Porzuć' })).toBeInTheDocument();
// dzień PLANNED = trening przed nami — planu nie da się oznaczyć jako ukończony
expect(screen.queryByRole('button', { name: 'Oznacz jako ukończony' })).not.toBeInTheDocument();
});
it('aktywny bez zaplanowanych dni: akcje „Oznacz jako ukończony" i „Porzuć"', async () => {
mockApi();
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 domknięty' }));
expect(await screen.findByRole('button', { name: 'Porzuć' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Oznacz jako ukończony' })).toBeInTheDocument();
});