Plany: notatka o zmianach opcjonalna (brak = wpis historii bez powodu; pole tylko przy edycji planu realizowanego)

This commit is contained in:
tisachi
2026-11-05 22:57:03 +01:00
parent 41f04ff62c
commit 23c881d4f3
15 changed files with 132 additions and 108 deletions

View File

@@ -91,8 +91,14 @@ export const updatePlanSchema = planBaseSchema
.string()
.refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date')
.optional(),
// Plan ACTIVE: wymagana notatka audytowa, gdy struktura faktycznie się zmienia (pilnuje serwis).
changeNote: z.string().trim().min(3).max(300).optional(),
// Plan ACTIVE: notatka audytowa zmiany — opcjonalna (pusta = brak, serwis zapisuje
// wpis historii bez notatki).
changeNote: z
.string()
.trim()
.max(300)
.optional()
.transform((v) => (v ? v : undefined)),
// Plan ACTIVE: świadoma zgoda na usunięcie dnia z historią (soft-remove `removedAt`;
// historia sesji/serii zostaje). Bez flagi serwis odrzuca 400 PLAN_DAY_HAS_HISTORY.
forceRemoveDays: z.boolean().optional(),

View File

@@ -129,14 +129,14 @@ export function createPlanRoutes({ prisma }: AppDeps) {
* current or future week, activates the plan in one step). ACTIVE = differential edit
* (days with history are kept; removing a day with history returns 400
* PLAN_DAY_HAS_HISTORY unless forceRemoveDays: true soft-removes it with history
* preserved) and requires
* changeNote (min 3 chars) recorded in the plan's edit history.
* preserved) and records an optional
* changeNote in the plan's edit history.
* The update is always allowed; when the user already has an active plan the
* structure is saved and the response carries activationSkipped: true.
* tags: [Plans]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft/active plan / start date not a Monday / start week in the past / change note required / PLAN_DAY_HAS_HISTORY }
* 400: { description: Not a draft/active plan / start date not a Monday / start week in the past / PLAN_DAY_HAS_HISTORY }
*/
router.patch(
'/:id',

View File

@@ -492,8 +492,9 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* /trainer/trainees/{userId}/plans/{planId}:
* patch:
* summary: Update plan structure. DRAFT = full replace (optional startDate = a Monday
* activates the plan in one step); ACTIVE = differential edit requiring changeNote
* (recorded in the plan edit history; the trainee gets a PLAN_EDITED feed notification).
* activates the plan in one step); ACTIVE = differential edit with an optional
* changeNote (recorded in the plan edit history; the trainee gets a PLAN_EDITED
* feed notification).
* Same body as POST (gymId, weeks[].customName,
* forceRemoveDays for soft-removing days that have training history).
* tags: [Trainer]

View File

@@ -49,7 +49,7 @@ export interface CreatePlanInput {
}
export interface UpdatePlanInput extends CreatePlanInput {
/** Plan ACTIVE: notatka audytowa zmiany („co i dlaczego") — wymagana, gdy coś się różni. */
/** Plan ACTIVE: notatka audytowa zmiany („co i dlaczego") — opcjonalna. */
changeNote?: string;
/**
* Plan ACTIVE: zezwolenie na usunięcie dnia z historią (sesje/COMPLETED/SKIPPED).
@@ -571,7 +571,7 @@ async function reconcileDayExercises(
/**
* Edycja planu w trakcie realizacji. Zmiany są rozliczane wiersz po wierszu:
* dni z historią zostają nietknięte (ich usunięcie = 400), nowe dni dostają datę
* z szablonu planu, a każda faktyczna zmiana trafia do `PlanEdit` z wymaganą
* z szablonu planu, a każda faktyczna zmiana trafia do `PlanEdit` z opcjonalną
* notatką („co i dlaczego”). Startu aktywnego planu nie zmienia się.
* Edycja przez kogoś innego niż właściciel (trener) generuje dodatkowo
* powiadomienie `PLAN_EDITED` w feedzie właściciela.
@@ -608,6 +608,7 @@ async function updateActivePlan(
const titleChanged = data.title.trim() !== plan.title;
let aliasesChanged = false;
let notifyOwner = false;
let editNote = '';
await prisma.$transaction(async (tx) => {
const byIndex = new Map(weeks.map((w) => [w.index, w]));
@@ -719,9 +720,9 @@ async function updateActivePlan(
});
const changed = titleChanged || aliasesChanged || Object.values(c).some((n) => n > 0);
if (changed) {
// Notatka opcjonalna: brak = wpis historii bez informacji „dlaczego”.
const note = (data.changeNote ?? '').trim();
if (note.length < 3)
throw badRequest('A change note is required when editing an active plan');
editNote = note;
await tx.planEdit.create({
data: {
planId: plan.id,
@@ -739,8 +740,8 @@ async function updateActivePlan(
await createNotification(prisma, {
userId: ownerId,
type: 'PLAN_EDITED',
title: `Trener zmienił Twój plan: ${data.title.trim()} — ${data.changeNote!.trim()}`,
payload: { planId: plan.id, planTitle: data.title.trim(), note: data.changeNote!.trim() },
title: `Trener zmienił Twój plan: ${data.title.trim()}${editNote ? ` — ${editNote}` : ''}`,
payload: { planId: plan.id, planTitle: data.title.trim(), note: editNote },
});
}
return { ok: true, activationSkipped: false, edited: true };

View File

@@ -1380,10 +1380,9 @@ export const openapi: Record<string, unknown> = {
},
changeNote: {
type: 'string',
minLength: 3,
maxLength: 300,
description:
'PATCH only, required when an ACTIVE plan actually changes — stored in the plan edit history',
'PATCH only, optional note recorded in the plan edit history for ACTIVE-plan edits (empty/absent = no note)',
},
weeks: {
type: 'array',
@@ -1475,7 +1474,7 @@ export const openapi: Record<string, unknown> = {
patch: {
tags: ['Plans'],
summary:
'Update plan structure. DRAFT = full replace (same body as POST /plans; optional startDate (a Monday of the current or a future week) updates and activates the plan in one step, and an already-active plan of the user only saves the structure with activationSkipped: true). ACTIVE = differential edit: rows matched by the ids sent in the payload are updated in place, new rows are added, the plan start date is immutable, and any real change requires changeNote (recorded in the plan edit history, exposed as plan.edits). Removing a day that has training history is rejected with code PLAN_DAY_HAS_HISTORY unless the payload sets forceRemoveDays: true — then the day is soft-removed (removedAt), its row and sessions stay in history while the day disappears from the plan, calendar, stats and killstreak. When an ACTIVE plan actually changes and the editor is not its owner (trainer edit), the owner gets a PLAN_EDITED notification in their feed',
'Update plan structure. DRAFT = full replace (same body as POST /plans; optional startDate (a Monday of the current or a future week) updates and activates the plan in one step, and an already-active plan of the user only saves the structure with activationSkipped: true). ACTIVE = differential edit: rows matched by the ids sent in the payload are updated in place, new rows are added, the plan start date is immutable, and any real change is recorded in the plan edit history (plan.edits) with an optional changeNote. Removing a day that has training history is rejected with code PLAN_DAY_HAS_HISTORY unless the payload sets forceRemoveDays: true — then the day is soft-removed (removedAt), its row and sessions stay in history while the day disappears from the plan, calendar, stats and killstreak. When an ACTIVE plan actually changes and the editor is not its owner (trainer edit), the owner gets a PLAN_EDITED notification in their feed',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {

View File

@@ -312,16 +312,6 @@ describe('plans routes', () => {
expect(res.body.error.message).toBe('User already has an active plan');
});
it('rejects editing an active plan without a change note with 400', async () => {
const app = buildApp();
const res = await app
.patch(`/api/v1/plans/${planId}`)
.set('Authorization', `Bearer ${token}`)
.send(planBody('Edit active'));
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('A change note is required when editing an active plan');
});
it('edits an active plan when a change note is given and records the edit', async () => {
interface DetailSet {
id: string;
@@ -384,6 +374,55 @@ describe('plans routes', () => {
});
});
it('edits an active plan without a change note and records the edit (opcjonalna notatka)', async () => {
interface NoNoteSet {
id: string;
index: number;
reps: number;
}
interface NoNoteExercise {
id: string;
exerciseId: string;
order: number;
sets: NoNoteSet[];
}
interface NoNoteDay {
id: string;
dayOfWeek: number;
exercises: NoNoteExercise[];
}
const app = buildApp();
const detail = await app
.get(`/api/v1/plans/${planId}`)
.set('Authorization', `Bearer ${token}`);
// te same wiersze z tymi samymi parametrami — jedyna realna zmiana to tytuł
const weeks = (detail.body.plan.weeks as { index: number; days: NoNoteDay[] }[]).map((w) => ({
index: w.index,
days: w.days.map((d) => ({
id: d.id,
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e) => ({
id: e.id,
exerciseId: e.exerciseId,
order: e.order,
sets: e.sets.map((s) => ({ id: s.id, index: s.index, reps: s.reps })),
})),
})),
}));
const res = await app
.patch(`/api/v1/plans/${planId}`)
.set('Authorization', `Bearer ${token}`)
.send({ title: 'Edit bez notatki', weeksCount: weeks.length, weeks });
expect(res.status).toBe(200);
const after = await app
.get(`/api/v1/plans/${planId}`)
.set('Authorization', `Bearer ${token}`);
expect(after.body.plan.title).toBe('Edit bez notatki');
// drugi wpis historii (pierwszy z notatką z poprzedniego testu) — notatka pusta
expect(after.body.plan.edits).toHaveLength(2);
expect(after.body.plan.edits.map((e: { note: string }) => e.note)).toContain('');
});
it('refuses to remove a day that has training history from an active plan', async () => {
const app = buildApp();
await prisma.planDay.update({

View File

@@ -1025,7 +1025,7 @@ describe('trainer — managing a trainee plan', () => {
expect(log!.actorId).toBe(trainer.id);
});
it('edits an active trainee plan only with a change note', async () => {
it('edits an active trainee plan even without a change note (opcjonalna)', async () => {
await prisma.trainingPlan.updateMany({
where: { userId: trainee.id, status: 'ACTIVE' },
data: { status: 'ABANDONED' },
@@ -1053,16 +1053,8 @@ describe('trainer — managing a trainee plan', () => {
.patch(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}`)
.set('Authorization', `Bearer ${trainer.token}`)
.send(changed());
expect(withoutNote.status).toBe(400);
expect(withoutNote.body.error.message).toBe(
'A change note is required when editing an active plan',
);
expect(withoutNote.status).toBe(200);
const withNote = await app
.patch(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}`)
.set('Authorization', `Bearer ${trainer.token}`)
.send(changed('Korekta planu przez trenera'));
expect(withNote.status).toBe(200);
const after = await app
.get(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}`)
.set('Authorization', `Bearer ${trainer.token}`);
@@ -1070,6 +1062,7 @@ describe('trainer — managing a trainee plan', () => {
const edits = await prisma.planEdit.findMany({ where: { planId: id } });
expect(edits).toHaveLength(1);
expect(edits[0].actorId).toBe(trainer.id);
expect(edits[0].note).toBe('');
// zwalniamy slot aktywnego planu dla pozostalych testow
await prisma.trainingPlan.update({ where: { id }, data: { status: 'ABANDONED' } });
});

View File

@@ -440,18 +440,16 @@ describe('editing an active plan', () => {
return { prisma, tx };
}
it('requires a change note when something actually changed', async () => {
const { prisma } = activeMocks();
it('records the edit without a change note (opcjonalna — pusta notatka)', async () => {
const { prisma, tx } = activeMocks();
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
await expect(
updatePlan(prisma, 'p1', 'u1', {
title: 'Nowa nazwa',
weeksCount: 1,
weeks: sameWeekPayload(),
}),
).rejects.toMatchObject({
status: 400,
message: 'A change note is required when editing an active plan',
await updatePlan(prisma, 'p1', 'u1', {
title: 'Nowa nazwa',
weeksCount: 1,
weeks: sameWeekPayload(),
});
expect(tx.planEdit.create).toHaveBeenCalledWith({
data: expect.objectContaining({ planId: 'p1', actorId: 'u1', note: '' }),
});
});

View File

@@ -90,7 +90,7 @@
"startDateLockedHint": "This plan is in progress — its start date cannot change.",
"changeNoteLabel": "Change note",
"changeNotePlaceholder": "What you change in the in-progress plan and why",
"changeNoteHint": "Stored in the plan history along with a summary of the changes. At least 3 characters.",
"changeNoteHint": "Optional. Stored in the plan history along with a summary of the changes — without a note the history won't tell why the plan was changed.",
"editActiveHint": "Changes to an in-progress plan keep history intact: completed days and sessions are never rewritten."
},
"summary": {
@@ -133,7 +133,6 @@
"sumMirror": "mirrors week 1",
"weeksMismatch": "The plan has {{count}} weeks — define them all",
"emptyDayError": "Week {{week}}: {{day}} has no exercises — add exercises or remove the day",
"changeNoteRequired": "In-progress plan: add a change note (min. 3 characters)",
"draftCreatedOwn": "Plan created as a draft — you already have an active plan, activation skipped",
"draftSavedOwn": "Plan saved as a draft — you already have an active plan, activation skipped",
"draftCreatedTrainee": "Plan created as a draft — the trainee already has an active plan, activation skipped",
@@ -256,6 +255,7 @@
},
"edits": {
"title": "Plan change history",
"noNote": "No note — the reason for the change was not described.",
"byMe": "You",
"unknownActor": "unknown",
"titleChanged": "title changed",

View File

@@ -90,7 +90,7 @@
"startDateLockedHint": "Plan jest realizowany — data startu jest niezmienna.",
"changeNoteLabel": "Notatka o zmianach",
"changeNotePlaceholder": "Co i dlaczego zmieniasz w realizowanym planie",
"changeNoteHint": "Trafia do historii planu wraz z podsumowaniem zmian. Minimum 3 znaki.",
"changeNoteHint": "Opcjonalna. Trafia do historii planu wraz z podsumowaniem zmian — bez notatki historia nie powie, dlaczego zmieniono plan.",
"editActiveHint": "Zmiany w realizowanym planie są zapisywane bez utraty historii: ukończone dni i sesje pozostają nienaruszone."
},
"summary": {
@@ -133,7 +133,6 @@
"sumMirror": "odzwierciedla tyg. 1",
"weeksMismatch": "Plan ma {{count}} tygodni — zdefiniuj je wszystkie",
"emptyDayError": "Tydzień {{week}}: dzień {{day}} nie ma ćwiczeń — dodaj ćwiczenia lub usuń dzień",
"changeNoteRequired": "Realizowany plan: wpisz notatkę o zmianach (min. 3 znaki)",
"draftCreatedOwn": "Plan utworzony jako szkic — masz już aktywny plan, aktywacja pominięta",
"draftSavedOwn": "Plan zapisany jako szkic — masz już aktywny plan, aktywacja pominięta",
"draftCreatedTrainee": "Plan utworzony jako szkic — podopieczny ma już aktywny plan, aktywacja pominięta",
@@ -257,6 +256,7 @@
},
"edits": {
"title": "Historia zmian w planie",
"noNote": "Brak notatki — powód zmiany nie został opisany.",
"byMe": "Ty",
"unknownActor": "nieznany",
"titleChanged": "zmieniono tytuł",

View File

@@ -339,7 +339,7 @@ export default function PlanDetail() {
.filter((x) => x.n > 0);
return (
<li key={e.id} className="rounded-[10px] border border-line bg-card/40 p-3">
<p className="text-[0.9rem]">{e.note}</p>
<p className="text-[0.9rem]">{e.note || t('edits.noNote')}</p>
<div className="mt-2 flex flex-wrap items-center gap-2 text-[0.8125rem] text-dim">
<span>{fmtDateTime(e.createdAt)}</span>
<span aria-hidden="true">·</span>

View File

@@ -252,13 +252,8 @@ export default function PlanEditor() {
const [shrinkReq, setShrinkReq] = useState<{ n: number } | null>(null);
const [forceRemoveDays, setForceRemoveDays] = useState(false);
const [titleTouched, setTitleTouched] = useState(false);
// Notatka audytowa (edycja planu ACTIVE) — wymagana, gdy coś zmieniamy
// Notatka audytowa (edycja planu ACTIVE) — opcjonalna; brak = historia bez „dlaczego”
const [changeNote, setChangeNoteState] = useState('');
const [changeNoteTouched, setChangeNoteTouched] = useState(false);
const changeNoteError =
changeNoteTouched && isPlanActive && editor.dirty && changeNote.trim().length < 3
? t('wizard.changeNoteRequired')
: '';
const exercises = exData?.exercises ?? [];
// Wybrana siłownia (z wyposażeniem) — limituje picker ćwiczeń do dostępnego sprzętu.
@@ -345,14 +340,7 @@ export default function PlanEditor() {
return;
}
}
// Plan w trakcie realizacji: każda zmiana wymaga notatki (trafia do historii planu).
const noteRequired = isPlanActive && editor.dirty;
setChangeNoteTouched(true);
if (noteRequired && changeNote.trim().length < 3) {
push(t('wizard.changeNoteRequired'), 'error');
setStep(1);
return;
}
// Plan w trakcie realizacji: notatka audytowa opcjonalna (trafia do historii planu).
// Id wierszy z bazy wysyłamy tylko dla tygodni, do których faktycznie należą
// (lustro/kopia tygodnia 1 to nowe wiersze — bez id).
const body: PlanBody = {
@@ -384,7 +372,7 @@ export default function PlanEditor() {
};
}),
};
if (noteRequired) body.changeNote = changeNote.trim();
if (isPlanActive && changeNote.trim()) body.changeNote = changeNote.trim();
// Dzień z historią usunięty za potwierdzeniem „Usuń mimo historii” — backend
// soft-remuje go (removedAt), historia sesji/serii zostaje w bazie.
if (isPlanActive && forceRemoveDays) body.forceRemoveDays = true;
@@ -597,12 +585,8 @@ export default function PlanEditor() {
onStartDateChange={editor.setStartDate}
startWeekError={startWeekError}
startDateLocked={isPlanActive}
changeNote={changeNote}
onSetChangeNote={(v) => {
setChangeNoteState(v);
setChangeNoteTouched(true);
}}
changeNoteError={changeNoteError}
changeNote={isPlanActive ? changeNote : undefined}
onSetChangeNote={isPlanActive ? (v) => setChangeNoteState(v) : undefined}
/>
)}

View File

@@ -7,7 +7,7 @@ import { fmtDate } from '../../../lib/format';
kalendarz na pełną szerokość karty, błędy inline. Siłownia jest tu, bo realnie
decyduje o dostępnym sprzęcie w pickerze ćwiczeń (krok 2).
Plan w trakcie realizacji: start jest niezmienny (pole tylko do odczytu) i pojawia
się wymagana notatka o zmianach (historia edycji planu). */
się opcjonalna notatka o zmianach (historia edycji planu). */
export function PlanMetaForm({
title,
onTitleChange,
@@ -25,7 +25,6 @@ export function PlanMetaForm({
startDateLocked = false,
changeNote,
onSetChangeNote,
changeNoteError,
}: {
title: string;
onTitleChange: (v: string) => void;
@@ -44,10 +43,9 @@ export function PlanMetaForm({
startWeekError?: string;
/** Plan ACTIVE — start ustaliła aktywacja, nie da się go zmienić. */
startDateLocked?: boolean;
/** Notatka audytowa (tylko plan ACTIVE); wymagana, gdy plan faktycznie się zmienia. */
/** Notatka audytowa (tylko plan ACTIVE); opcjonalna — brak = historia bez „dlaczego”. */
changeNote?: string;
onSetChangeNote?: (v: string) => void;
changeNoteError?: string;
}) {
const { t } = useTranslation('plans');
const titleField = (
@@ -125,14 +123,9 @@ export function PlanMetaForm({
maxLength={300}
rows={3}
placeholder={t('meta.changeNotePlaceholder')}
aria-invalid={changeNoteError ? true : undefined}
className="w-full rounded-[10px] border border-line bg-input px-3 py-2 text-[0.9rem] text-ink placeholder:text-dim/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60"
/>
{changeNoteError ? (
<ErrorText>{changeNoteError}</ErrorText>
) : (
<p className="mt-1.5 text-dim text-[0.8125rem]">{t('meta.changeNoteHint')}</p>
)}
<p className="mt-1.5 text-dim text-[0.8125rem]">{t('meta.changeNoteHint')}</p>
</Field>
</div>
)}

View File

@@ -668,8 +668,8 @@ async function loginAndOpenEditor(user: userEvent.User) {
);
}
describe('PlanEditor — edycja aktywnego planu (notatka + id wierszy)', () => {
it('start planu zablokowany, notatka wymagana; zapis = PATCH z changeNote i id dni/ćwiczeń/serii', async () => {
describe('PlanEditor — edycja aktywnego planu (opcjonalna notatka + id wierszy)', () => {
it('start planu zablokowany, notatka opcjonalna; zapis bez notatki = PATCH bez changeNote z id dni/ćwiczeń/serii', async () => {
const capture: Capture = {};
const plan = activePlan();
mockEditApi(capture, plan);
@@ -678,7 +678,7 @@ describe('PlanEditor — edycja aktywnego planu (notatka + id wierszy)', () => {
await loginAndOpenEditor(user);
expect(await screen.findByRole('heading', { name: 'Edycja planu' })).toBeInTheDocument();
// krok 1 aktywnego planu: brak wyboru tygodnia startu, jest notatka o zmianach
// krok 1 aktywnego planu: brak wyboru tygodnia startu, jest opcjonalna notatka o zmianach
expect(screen.queryByRole('group', { name: 'Wybór tygodnia startu' })).not.toBeInTheDocument();
expect(
screen.getByText('Plan jest realizowany — data startu jest niezmienna.'),
@@ -692,23 +692,11 @@ describe('PlanEditor — edycja aktywnego planu (notatka + id wierszy)', () => {
await user.click(screen.getByRole('button', { name: 'Dalej' }));
await setSetField(user, 'Seria 1: Powt.', '12');
// zapis bez notatki = blokada (komunikat toast + błąd inline, brak PATCH, krok 1)
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
expect((await screen.findAllByText(/wpisz notatkę o zmianach/)).length).toBeGreaterThan(0);
expect(capture.patchPlanBody).toBeUndefined();
expect(screen.getByText('Notatka o zmianach')).toBeInTheDocument();
// notatka + zapis → PATCH z id istniejących wierszy (pole ponowne po powrocie na krok 1)
const noteFieldAfter = screen
.getByText('Notatka o zmianach')
.closest('[data-slot="field"]') as HTMLElement;
await user.type(within(noteFieldAfter).getByRole('textbox'), 'Korekta po kontuzji');
// zapis bez notatki = PATCH bez changeNote (notatka opcjonalna, brak blokady)
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
await waitFor(() => expect(capture.patchPlanBody).toBeDefined());
expect(capture.patchPlanBody).toMatchObject({
title: 'Plan w trakcie',
changeNote: 'Korekta po kontuzji',
});
expect(capture.patchPlanBody).not.toHaveProperty('changeNote');
expect(capture.patchPlanBody).toMatchObject({ title: 'Plan w trakcie' });
expect(capture.patchPlanBody).not.toHaveProperty('startDate');
const weeks = capture.patchPlanBody!.weeks as Record<string, unknown>[];
const day = (weeks[0].days as Record<string, unknown>[])[0];
@@ -720,6 +708,30 @@ describe('PlanEditor — edycja aktywnego planu (notatka + id wierszy)', () => {
reps: 12,
});
});
it('uzupełniona notatka trafia do PATCH jako changeNote', async () => {
const capture: Capture = {};
const plan = activePlan();
mockEditApi(capture, plan);
const user = userEvent.setup();
renderApp();
await loginAndOpenEditor(user);
await screen.findByRole('heading', { name: 'Edycja planu' });
const noteField = screen
.getByText('Notatka o zmianach')
.closest('[data-slot="field"]') as HTMLElement;
await user.type(within(noteField).getByRole('textbox'), 'Korekta po kontuzji');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
await setSetField(user, 'Seria 1: Powt.', '12');
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
await waitFor(() => expect(capture.patchPlanBody).toBeDefined());
expect(capture.patchPlanBody).toMatchObject({
title: 'Plan w trakcie',
changeNote: 'Korekta po kontuzji',
});
});
});
describe('PlanEditor — dzień z historią w aktywnym planie', () => {
@@ -749,16 +761,11 @@ describe('PlanEditor — dzień z historią w aktywnym planie', () => {
expect(screen.getByText(/historia treningowa zostanie zachowana/)).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Usuń mimo historii' }));
// zapis bez notatki = powrót na krok 1; tam uzupełniamy notatkę audytową i zapisujemy
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
expect((await screen.findAllByText(/wpisz notatkę o zmianach/)).length).toBeGreaterThan(0);
const noteField = screen
.getByText('Notatka o zmianach')
.closest('[data-slot="field"]') as HTMLElement;
await user.type(within(noteField).getByRole('textbox'), 'Zmiana po konsultacji z trenerem');
// zapis bez notatki = PATCH od razu (notatka opcjonalna)
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
await waitFor(() => expect(capture.patchPlanBody).toBeDefined());
expect(capture.patchPlanBody).toMatchObject({ forceRemoveDays: true });
expect(capture.patchPlanBody).not.toHaveProperty('changeNote');
const weeks = capture.patchPlanBody!.weeks as Record<string, unknown>[];
expect((weeks[0].days as unknown[]).length).toBe(0);
});

View File

@@ -40,6 +40,9 @@ test('formularz nowego planu ma wybór tygodnia startu i przycisk „Wstecz” w
// formularz zawiera wybór tygodnia startu (siatka miesiąca)
await expect(page.getByRole('group', { name: 'Wybór tygodnia startu' })).toBeVisible();
// nowy plan (DRAFT): pole „Notatka o zmianach” nie istnieje — tylko przy edycji realizacji
await expect(page.getByText('Notatka o zmianach')).not.toBeVisible();
// minione tygodnie są zablokowane — ostatni dzień poprzedniego tygodnia ma disabled
const prevWeekEnd = new Date();
prevWeekEnd.setDate(prevWeekEnd.getDate() - ((prevWeekEnd.getDay() + 6) % 7) - 1);