Plans: wznawianie planu tylko dla wlasciciela (usuniete akcje trenera)

This commit is contained in:
tisachi
2026-10-22 23:53:49 +02:00
parent 50df81dbf0
commit 83ee38dc3a
13 changed files with 54 additions and 175 deletions

View File

@@ -33,7 +33,6 @@ import {
deletePlan,
getPlan,
listPlans,
reopenPlan,
updatePlan,
} from '../services/plans.js';
import { activateSchema, createPlanSchema, updatePlanSchema } from './plans-schemas.js';
@@ -640,36 +639,6 @@ 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:

View File

@@ -429,12 +429,13 @@ export async function completePlan(prisma: PrismaClient, planId: string, userId:
* 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.
* Wznowić może wyłącznie właściciel planu (trener nie ma takiej akcji).
*/
export async function reopenPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
const plan = await assertPlanOwner(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).
// Jeden aktywny plan dotyczy właściciela.
// Pre-check + częściowy indeks unikalny (TrainingPlan_userId_active_key)
// rozstrzyga równoległe wznowienia/aktywacje.
const otherActive = await prisma.trainingPlan.findFirst({

View File

@@ -845,31 +845,11 @@ describe('trainer — managing a trainee plan', () => {
expect(res.status).toBe(200);
});
it('rejects reopening an active plan with 400', async () => {
it('rejects reopening a trainee plan — only the owner can resume (404)', 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'));
.send(planBody('Trainer reopen denied'));
const id = created.body.plan.id;
await app
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/activate`)
@@ -881,13 +861,9 @@ describe('trainer — managing a trainee plan', () => {
const res = await app
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/reopen`)
.set('Authorization', `Bearer ${trainer.token}`);
expect(res.status).toBe(200);
expect(res.status).toBe(404);
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}`);
expect(stored!.status).toBe('ABANDONED');
});
it('deletes a draft plan', async () => {

View File

@@ -167,6 +167,16 @@ describe('draft-only rules', () => {
});
});
it('reopenPlan: rejects reopening a plan owned by another user with 404', async () => {
const { prisma } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });
await expect(reopenPlan(prisma, 'p1', 'trainer1')).rejects.toMatchObject({
status: 404,
message: 'Plan not found',
});
expect(prisma.trainingPlan.update).not.toHaveBeenCalled();
});
it('reopenPlan: rejects when the owner has another active plan with 409', async () => {
const { prisma } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });

View File

@@ -846,10 +846,6 @@ 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' });
}
// ---------- aktualności (feed) ----------
export function useFeed(limit = 20) {
return useInfiniteQuery({

View File

@@ -6,8 +6,10 @@ import type { Plan } from '../../api/types';
/**
* Akcje planu zależne od statusu (DRAFT: Aktywuj/Edytuj/Usuń + WeekPicker + hint;
* ACTIVE: Oznacz jako ukończony/Porzuć; COMPLETED/ABANDONED: Wznów) + actionError.
* Współdzielone przez PlanDetail i zakładkę „Plany" panelu podopiecznego.
* ACTIVE: Oznacz jako ukończony/Porzuć) + actionError.
* Współdzielone wyłącznie przez zakładkę „Plany" panelu podopiecznego —
* wznowienie (COMPLETED/ABANDONED -> ACTIVE) przysługuje tylko właścicielowi
* planu w jego własnej aplikacji (PlanDetail).
*/
export function PlanActions({
plan,
@@ -20,10 +22,8 @@ export function PlanActions({
onDelete,
onComplete,
onAbandon,
onReopen,
hint,
activateDisabled,
reopenDisabled,
}: {
plan: Plan;
editTo: string;
@@ -35,13 +35,10 @@ 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;
}) {
const { t } = useTranslation('plans');
// Aktywny plan w trakcie realizacji (został dzień PLANNED) można tylko
@@ -99,20 +96,7 @@ export function PlanActions({
</Button>
</>
)}
{(plan.status === 'COMPLETED' || plan.status === 'ABANDONED') && (
<Button
variant="secondary"
disabled={busy || reopenDisabled}
onClick={onReopen}
className="w-full sm:w-auto"
>
{t('actions.reopen')}
</Button>
)}
</div>
{(plan.status === 'COMPLETED' || plan.status === 'ABANDONED') && reopenDisabled && (
<p className="mt-3 text-dim text-[0.875rem]">{t('actions.reopenBlockedHint')}</p>
)}
{plan.status === 'DRAFT' && (
<div className="mt-4">
<p className="mb-2 text-dim text-[0.875rem]">{t('detail.startWeekLabel')}</p>

View File

@@ -161,8 +161,7 @@
"abandon": "Abandon",
"reopen": "Resume",
"completeLabel": "Complete",
"share": "Share",
"reopenBlockedHint": "The trainee already has an active plan — only one plan can be active. To resume this plan, complete or abandon the active one first."
"share": "Share"
},
"dialog": {
"title": "Share plan",

View File

@@ -161,8 +161,7 @@
"abandon": "Porzuć",
"reopen": "Wznów",
"completeLabel": "Ukończ",
"share": "Udostępnij",
"reopenBlockedHint": "Podopieczny ma już aktywny plan — tylko jeden plan może być aktywny. Aby wznowić ten plan, najpierw ukończ lub porzuć aktywny."
"share": "Udostępnij"
},
"dialog": {
"title": "Udostępnij plan",

View File

@@ -128,16 +128,19 @@ export default function PlanDetail() {
onClick: () => setConfirm('abandon'),
},
]
: // plan zamknięty (ukończony/porzucony) — można wznowić w celu poprawek
[
{
label: t('actions.reopen'),
icon: RotateCcw,
variant: 'secondary' as const,
disabled: busy || hasOtherActivePlan,
onClick: () => setConfirm('reopen'),
},
]),
: // plan zamknięty (ukończony/porzucony) — wznowienie tylko dla
// właściciela (trener nie wznawia planów podopiecznych)
(isOwner
? [
{
label: t('actions.reopen'),
icon: RotateCcw,
variant: 'secondary' as const,
disabled: busy || hasOtherActivePlan,
onClick: () => setConfirm('reopen'),
},
]
: [])),
// udostępnianie = tylko właściciel planu
...(isOwner
? [
@@ -247,7 +250,7 @@ export default function PlanDetail() {
</div>
)}
{(plan.status === 'COMPLETED' || plan.status === 'ABANDONED') &&
canManage &&
isOwner &&
hasOtherActivePlan && (
<p className="mt-3 text-[0.875rem] text-warn">{t('detail.activeConflictReopen')}</p>
)}

View File

@@ -6,7 +6,6 @@ import {
activateTraineePlan,
completeTraineePlan,
deleteTraineePlan,
reopenTraineePlan,
useMe,
useTraineePlan,
useTraineePlans,
@@ -29,13 +28,14 @@ import { useToast } from '../../../components/toast';
import type { Plan } from '../../../api/types';
type PlanAction = {
type: 'delete' | 'abandon' | 'complete' | 'activate' | 'reopen';
type: 'delete' | 'abandon' | 'complete' | 'activate';
planId: string;
};
/**
* Zakładka „Plany" w panelu podopiecznego: lista planów podopiecznego + akcje
* (edytuj/aktywuj/usuń/porzuć/ukończ/wznów) + podgląd struktury inline.
* (edytuj/aktywuj/usuń/porzuć/ukończ) + podgląd struktury inline.
* Wznowienie planu (reopen) = tylko właściciel w swojej aplikacji.
* Tworzenie planu: akcja „Utwórz plan" w menu kontekstowym strony (TraineeDetail).
*/
export function TraineePlansTab({ userId }: { userId: string }) {
@@ -171,11 +171,7 @@ 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 ? t('detail.traineeConflictActivate') : undefined}
/>
</div>
@@ -260,19 +256,6 @@ export function TraineePlansTab({ userId }: { userId: string }) {
confirmLabel={t('actions.completeLabel')}
busy={busy}
/>
<ConfirmDialog
open={confirm?.type === 'reopen'}
onClose={() => setConfirm(null)}
onConfirm={() => {
const planId = confirm!.planId;
setConfirm(null);
void act(() => reopenTraineePlan(userId, planId), t('toasts.reopened'));
}}
title={t('detail.confirmReopenTitle')}
description={t('detail.confirmReopenDesc')}
confirmLabel={t('actions.reopen')}
busy={busy}
/>
</>
);
}

View File

@@ -677,7 +677,7 @@ export const TEST_TRAINEE_PLAN_DETAIL_FINISHED = {
],
};
/** Plan ukończony — dostępna akcja „Wznów" (reopen w celu poprawek). */
/** Plan ukończony — w panelu trenera bez akcji „Wznów" (reopen tylko u właściciela). */
export const TEST_TRAINEE_PLAN_DETAIL_DONE = {
...TEST_TRAINEE_PLAN_DETAIL_FINISHED,
id: 'tp-4',
@@ -1811,8 +1811,7 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) {
if (
url.includes('/activate') ||
url.includes('/abandon') ||
url.includes('/complete') ||
url.includes('/reopen')
url.includes('/complete')
) {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
}

View File

@@ -1,10 +1,5 @@
import { test, expect } from './fixtures';
import {
mockTraineePlans,
TEST_GYM_OWNED,
TEST_TRAINEE_PLANS,
TEST_USER,
} from './mock-api';
import { mockTraineePlans, TEST_GYM_OWNED, TEST_USER } from './mock-api';
function trainerMe() {
return {
@@ -107,31 +102,15 @@ 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 ({
test('zakładka Plany: ukończony plan — brak akcji „Wznów" (wznowienie tylko u właściciela)', 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();
// struktura inline załadowana — mimo to treść bez akcji wznowienia
await expect(page.getByText(/Wyciskanie/).first()).toBeVisible();
await expect(page.getByRole('button', { name: 'Wznów' })).toHaveCount(0);
});
test('edytor planu podopiecznego: „Wstaw wyniki" prefylluje serie z ostatniej sesji', async ({

View File

@@ -217,7 +217,7 @@ const FINISHED_DETAIL = {
],
};
// Plan ukończony — dostępna akcja „Wznów" (reopen w celu poprawek).
// Plan ukończony — brak akcji „Wznów" (wznowienie tylko u właściciela w app).
const PLAN_DONE = {
id: 'plan-4',
title: 'Plan ukończony',
@@ -307,7 +307,7 @@ function jsonResponse(status: number, body: unknown) {
function mockApi(
opts: {
plans?: unknown[];
capture?: { createBody?: Record<string, unknown>; reopenUrl?: string };
capture?: { createBody?: Record<string, unknown> };
} = {},
) {
const plans = opts.plans ?? PLANS;
@@ -346,10 +346,6 @@ function mockApi(
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`)) {
@@ -468,32 +464,17 @@ describe('Zakładka „Plany" w panelu podopiecznego', () => {
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 });
it('ukończony plan: brak akcji „Wznów" (trener nie wznawia planu podopiecznego)', async () => {
// nawet bez innego aktywnego planu — wznowienie przysługuje tylko właścicielowi
mockApi({ plans: [PLAN_DONE] });
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();
await screen.findByText(/Przysiady|Wyciskanie/);
expect(screen.queryByRole('button', { name: 'Wznów' })).not.toBeInTheDocument();
});
});