import { describe, it, expect, beforeAll, beforeEach } from 'vitest'; import { prisma } from '../../src/lib/prisma.js'; import { buildApp, createUser, createUserWithToken, createExercise, loginViaApi, rand, registerViaApi, seedPlan, PASSWORD, } from '../helpers.js'; // Daty dynamiczne: tydzień startu musi być bieżący lub przyszły (nie miniony). function mondayIso(offsetWeeks: number): string { const d = new Date(); d.setDate(d.getDate() - ((d.getDay() + 6) % 7) + offsetWeeks * 7); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; } const MONDAY = mondayIso(1); // przyszły tydzień — ważna data startu const PAST_MONDAY = mondayIso(-1); // miniony tydzień — odrzucona const SUNDAY = (() => { const [y, m, d] = MONDAY.split('-').map(Number); const sun = new Date(y, m - 1, d - 1); return `${sun.getFullYear()}-${String(sun.getMonth() + 1).padStart(2, '0')}-${String(sun.getDate()).padStart(2, '0')}`; })(); describe('plans routes', () => { let token: string; let otherToken: string; let planId: string; let exerciseId: string; const planBody = (title: string, weeksCount = 2) => ({ title, weeksCount, weeks: [ { index: 0, days: [ { dayOfWeek: 1, exercises: [ { exerciseId, order: 0, sets: [ { index: 0, reps: 10, loadKg: 60, restSec: 90, rir: 2 }, { index: 1, reps: 8, loadKg: 62.5, restSec: 90 }, ], }, ], }, { dayOfWeek: 3, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 12 }] }] }, ], }, { index: 1, days: [ { dayOfWeek: 2, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 12 }] }] }, ], }, ], }); beforeAll(async () => { token = (await registerViaApi()).token; otherToken = (await registerViaApi()).token; const exercise = await createExercise(); exerciseId = exercise.id; const app = buildApp(); const res = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Mój plan')); expect(res.status).toBe(201); planId = res.body.plan.id; }); it('creates a draft plan with the given structure', async () => { const app = buildApp(); const res = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Draft 2')); expect(res.status).toBe(201); expect(res.body.plan).toMatchObject({ title: 'Draft 2', status: 'DRAFT', weeksCount: 2 }); expect(res.body.plan.startDate).toBeNull(); }); it('rejects a plan whose weeks.length != weeksCount with 400', async () => { const app = buildApp(); const body = planBody('Mismatch'); body.weeksCount = 3; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects duplicated weeks index with 400', async () => { const app = buildApp(); const body = planBody('Dup week'); body.weeks[1].index = 0; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects a week index outside 0..weeksCount-1 with 400', async () => { const app = buildApp(); const body = planBody('Out of range'); body.weeks[1].index = 5; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects duplicated dayOfWeek within a week with 400', async () => { const app = buildApp(); const body = planBody('Dup day'); body.weeks[0].days[1].dayOfWeek = 1; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects duplicated set index within an exercise with 400', async () => { const app = buildApp(); const body = planBody('Dup set'); body.weeks[0].days[0].exercises[0].sets[1].index = 0; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects duplicated exercise order within a day with 400', async () => { const app = buildApp(); const body = planBody('Dup order'); body.weeks[0].days[0].exercises.push({ exerciseId, order: 0, sets: [{ index: 0, reps: 5 }], }); const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects a plan with more than 8 weeks with 400', async () => { const app = buildApp(); const body = planBody('Too long'); body.weeksCount = 9; body.weeks = Array.from({ length: 9 }, (_, i) => ({ index: i, days: [] })); const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects an unknown exerciseId with 400', async () => { const app = buildApp(); const body = planBody('Bad exercise'); body.weeks[0].days[0].exercises[0].exerciseId = 'nonexistent-exercise'; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Unknown exerciseId in plan'); }); it('rejects an exercise without sets with 400', async () => { const app = buildApp(); const body = planBody('No sets'); body.weeks[0].days[0].exercises = [{ exerciseId, order: 0, sets: [] }]; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('rejects an invalid set field with 400', async () => { const app = buildApp(); const body = planBody('Bad set'); body.weeks[0].days[0].exercises[0].sets = [{ index: 0, reps: -5 }]; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); }); it('lists only the current user plans', async () => { const app = buildApp(); const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); const titles = res.body.plans.map((p: { title: string }) => p.title); expect(titles).toContain('Mój plan'); expect(titles).toContain('Draft 2'); }); it('lists plans with a progress summary (completed/total/percent)', async () => { const app = buildApp(); const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); const mine = res.body.plans.find((p: { title: string }) => p.title === 'Mój plan'); expect(mine.progress).toEqual({ completed: 0, total: 3, percent: 0 }); }); it('returns plan details with weeks, days, exercises and sets', async () => { const app = buildApp(); const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); const plan = res.body.plan; expect(plan.status).toBe('DRAFT'); expect(plan.weeks).toHaveLength(2); const week0 = plan.weeks.find((w: { index: number }) => w.index === 0); expect(week0.days).toHaveLength(2); const day1 = week0.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); expect(day1.exercises).toHaveLength(1); expect(day1.exercises[0].exercise.id).toBe(exerciseId); expect(day1.exercises[0].sets.map((s: { index: number }) => s.index)).toEqual([0, 1]); }); it('returns 404 for another user plan', async () => { const app = buildApp(); const res = await app .get(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${otherToken}`); expect(res.status).toBe(404); }); it('replaces the structure of a draft plan via PATCH', async () => { const app = buildApp(); const body = planBody('Zmieniony'); body.weeks[0].days[0].exercises[0].sets = [{ index: 0, reps: 5 }]; const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send(body); expect(res.status).toBe(200); const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); expect(detail.body.plan.title).toBe('Zmieniony'); const day1 = detail.body.plan.weeks .find((w: { index: number }) => w.index === 0) .days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); expect(day1.exercises[0].sets).toHaveLength(1); }); it('activates a draft plan on a Monday and computes day dates', async () => { const app = buildApp(); const res = await app .post(`/api/v1/plans/${planId}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: MONDAY }); expect(res.status).toBe(200); const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); expect(detail.body.plan.status).toBe('ACTIVE'); const localDate = (iso: string) => { const d = new Date(iso); return [d.getFullYear(), d.getMonth() + 1, d.getDate()]; }; const [sy, sm, sd] = MONDAY.split('-').map(Number); const plusDays = (n: number) => { const d = new Date(sy, sm - 1, sd + n); return [d.getFullYear(), d.getMonth() + 1, d.getDate()]; }; const week0 = detail.body.plan.weeks.find((w: { index: number }) => w.index === 0); const day1 = week0.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); const day3 = week0.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 3); expect(localDate(day1.date)).toEqual(plusDays(0)); expect(localDate(day3.date)).toEqual(plusDays(2)); }); it('rejects activation with a past-week startDate with 400', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Past activate')); const res = await app .post(`/api/v1/plans/${created.body.plan.id}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: PAST_MONDAY }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Start date cannot be in the past'); }); it('rejects activation on a non-Monday date with 400', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Sunday plan')); const res = await app .post(`/api/v1/plans/${created.body.plan.id}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: SUNDAY }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Start date must be a Monday'); }); it('rejects an invalid start date with 400', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Bad date')); const res = await app .post(`/api/v1/plans/${created.body.plan.id}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: 'not-a-date' }); expect(res.status).toBe(400); }); it('rejects activating a second plan while one is active with 409', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Second active')); const res = await app .post(`/api/v1/plans/${created.body.plan.id}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: mondayIso(2) }); expect(res.status).toBe(409); expect(res.body.error.message).toBe('User already has an active plan'); }); it('edits an active plan when a change note is given and records the edit', async () => { interface DetailSet { id: string; index: number; } interface DetailExercise { id: string; exerciseId: string; order: number; sets: DetailSet[]; } interface DetailDay { id: string; dayOfWeek: number; exercises: DetailExercise[]; } const app = buildApp(); const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); const weeks = (detail.body.plan.weeks as { index: number; days: DetailDay[] }[]).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: 15 })), })), })), })); const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send({ title: 'Poprawiony w trakcie', weeksCount: 2, weeks, changeNote: 'Korekta obciążeń', }); expect(res.status).toBe(200); const after = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); expect(after.body.plan.status).toBe('ACTIVE'); expect(after.body.plan.title).toBe('Poprawiony w trakcie'); const day1 = after.body.plan.weeks .find((w: { index: number }) => w.index === 0) .days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); expect(day1.exercises[0].sets.map((s: { reps: number }) => s.reps)).toEqual([15]); // dni i cwiczenia zostaly tymi samymi wierszami (bez rekolekcji) expect(day1.exercises[0].id).toBe( (detail.body.plan.weeks as { index: number; days: DetailDay[] }[]) .find((w) => w.index === 0)! .days.find((d) => d.dayOfWeek === 1)!.exercises[0].id, ); expect(after.body.plan.edits).toHaveLength(1); expect(after.body.plan.edits[0]).toMatchObject({ note: 'Korekta obciążeń', actor: { id: expect.any(String) }, summary: { setsChanged: 3, daysAdded: 0, exercisesRemoved: 0 }, }); }); 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({ where: { id: (await prisma.planDay.findFirstOrThrow({ where: { week: { planId }, dayOfWeek: 3 } })) .id, }, data: { status: 'COMPLETED' }, }); const body = planBody('Bez dnia z historia'); body.weeks[0].days = body.weeks[0].days.filter((d: { dayOfWeek: number }) => d.dayOfWeek !== 3); const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send({ ...body, changeNote: 'Usuwanie dnia' }); expect(res.status).toBe(400); expect(res.body.error.message).toContain('has training history'); expect(res.body.error.code).toBe('PLAN_DAY_HAS_HISTORY'); }); it('forceRemoveDays soft-removes a day with history — plan hides it, /me/history keeps the session', async () => { const app = buildApp(); const day3 = await prisma.planDay.findFirstOrThrow({ where: { week: { planId }, dayOfWeek: 3 }, }); const pe = await prisma.planExercise.findFirstOrThrow({ where: { dayId: day3.id }, include: { sets: true }, }); await prisma.planDay.update({ where: { id: day3.id }, data: { status: 'COMPLETED' } }); const session = await prisma.trainingSession.create({ data: { dayId: day3.id, status: 'COMPLETED', startedAt: new Date(Date.now() - 3_600_000), endedAt: new Date(), exercises: { create: [ { exerciseId: pe.exerciseId, planExerciseId: pe.id, order: 0, sets: { create: [{ planSetId: pe.sets[0].id, index: 0, reps: 12 }] }, }, ], }, }, select: { id: true }, }); const body = planBody('Dzien usuniety silowo'); body.weeks[0].days = body.weeks[0].days.filter((d: { dayOfWeek: number }) => d.dayOfWeek !== 3); const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send({ ...body, changeNote: 'Silowe usuniecie dnia z historia', forceRemoveDays: true }); expect(res.status).toBe(200); const after = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); const days0 = after.body.plan.weeks.find((w: { index: number }) => w.index === 0).days; expect(days0.some((d: { dayOfWeek: number }) => d.dayOfWeek === 3)).toBe(false); expect(after.body.plan.edits[0].summary).toMatchObject({ daysForceRemoved: 1 }); const removed = await prisma.planDay.findUnique({ where: { id: day3.id } }); expect(removed.removedAt).not.toBeNull(); const history = await app.get('/api/v1/me/history').set('Authorization', `Bearer ${token}`); expect(history.body.sessions.some((s: { id: string }) => s.id === session.id)).toBe(true); }); it('rejects a plan day without exercises with 400', async () => { const app = buildApp(); const body = planBody('Dzien bez cwiczen'); body.weeks[0].days[1].exercises = []; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); expect(JSON.stringify(res.body.error.details ?? {})).toContain('at least one exercise'); }); it('abandons an active plan and refuses to close it twice', async () => { const app = buildApp(); const res = await app .post(`/api/v1/plans/${planId}/abandon`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); const again = await app .post(`/api/v1/plans/${planId}/abandon`) .set('Authorization', `Bearer ${token}`); expect(again.status).toBe(400); expect(again.body.error.message).toBe('Only an active plan can be abandoned'); }); it('rejects abandoning a draft plan with 400', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Draft abandon')); const res = await app .post(`/api/v1/plans/${created.body.plan.id}/abandon`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Only an active plan can be abandoned'); }); it('rejects completing a draft plan with 400', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Draft complete')); const res = await app .post(`/api/v1/plans/${created.body.plan.id}/complete`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(400); 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 .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('To complete')); 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); // 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}`); expect(res.status).toBe(200); const again = await app .post(`/api/v1/plans/${id}/complete`) .set('Authorization', `Bearer ${token}`); 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('rejects suspending a draft plan with 400', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Draft suspend')); const res = await app .post(`/api/v1/plans/${created.body.plan.id}/suspend`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Only an active plan can be suspended'); }); it('suspends an active plan, frees the active slot and blocks resume while another plan runs', async () => { const app = buildApp(); const first = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Do pauzy')); const firstId = first.body.plan.id; await app .post(`/api/v1/plans/${firstId}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: MONDAY }); const suspended = await app .post(`/api/v1/plans/${firstId}/suspend`) .set('Authorization', `Bearer ${token}`); expect(suspended.status).toBe(200); const again = await app .post(`/api/v1/plans/${firstId}/suspend`) .set('Authorization', `Bearer ${token}`); expect(again.status).toBe(400); expect(again.body.error.message).toBe('Only an active plan can be suspended'); // wstrzymany plan nie zajmuje slotu aktywnego — inny plan da się aktywować const second = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Drugi w kolejce')); const secondId = second.body.plan.id; const activated = await app .post(`/api/v1/plans/${secondId}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: MONDAY }); expect(activated.status).toBe(200); // wznowienie koliduje z aktywnym planem const blocked = await app .post(`/api/v1/plans/${firstId}/resume`) .set('Authorization', `Bearer ${token}`); expect(blocked.status).toBe(409); expect(blocked.body.error.message).toBe('User already has an active plan'); // po zwolnieniu slotu wznowienie przechodzi (wszystkie dni przyszłe — zero przesunięć) await app.post(`/api/v1/plans/${secondId}/abandon`).set('Authorization', `Bearer ${token}`); const resumed = await app .post(`/api/v1/plans/${firstId}/resume`) .set('Authorization', `Bearer ${token}`); expect(resumed.status).toBe(200); expect(resumed.body.movedDays).toBe(0); const stored = await prisma.trainingPlan.findUnique({ where: { id: firstId } }); expect(stored!.status).toBe('ACTIVE'); // sprzątanie await app.post(`/api/v1/plans/${firstId}/abandon`).set('Authorization', `Bearer ${token}`); }); it('resuming a suspended plan keeps planned days and shifts past ones into later weeks', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Wznawiany')); const id = created.body.plan.id; await app .post(`/api/v1/plans/${id}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: MONDAY }); // dwa dni cofnięte o 3 tygodnie — symulacja terminów, które minęły przed wznowieniem const before = await prisma.planDay.findMany({ where: { week: { planId: id } }, orderBy: { date: 'asc' }, }); expect(before.length).toBe(3); for (const d of before.slice(0, 2)) { const past = new Date(d.date!); past.setDate(past.getDate() - 21); await prisma.planDay.update({ where: { id: d.id }, data: { date: past } }); } const suspended = await app .post(`/api/v1/plans/${id}/suspend`) .set('Authorization', `Bearer ${token}`); expect(suspended.status).toBe(200); const resumed = await app .post(`/api/v1/plans/${id}/resume`) .set('Authorization', `Bearer ${token}`); expect(resumed.status).toBe(200); expect(resumed.body.movedDays).toBe(2); const after = await prisma.planDay.findMany({ where: { week: { planId: id } } }); // żaden dzień nie został usunięty ani zmieniony statusowo — wszystkie PLANNED expect(after.length).toBe(3); const today = new Date(); today.setHours(0, 0, 0, 0); for (const d of after) { expect(d.status).toBe('PLANNED'); expect(d.removedAt).toBeNull(); expect(d.date!.getTime()).toBeGreaterThanOrEqual(today.getTime()); } // przesunięcie pełnymi tygodniami: ten sam dzień tygodnia co w szablonie const moved = after.find((d) => d.id === before[0].id)!; expect(moved.date!.getDay()).toBe(before[0].date!.getDay()); const logs = await prisma.dayMove.count({ where: { dayId: { in: [before[0].id, before[1].id] }, reason: 'wznowienie planu' }, }); expect(logs).toBe(2); // sprzątanie await app.post(`/api/v1/plans/${id}/abandon`).set('Authorization', `Bearer ${token}`); }); it('deletes a draft plan', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('To delete')); const res = await app .delete(`/api/v1/plans/${created.body.plan.id}`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(204); const detail = await app .get(`/api/v1/plans/${created.body.plan.id}`) .set('Authorization', `Bearer ${token}`); expect(detail.status).toBe(404); }); it('rejects /me-style access without token with 401', async () => { const app = buildApp(); const res = await app.get('/api/v1/plans'); expect(res.status).toBe(401); }); it('rejects creation with a non-Monday startDate with 400', async () => { const app = buildApp(); const body = planBody('Sunday create'); body.startDate = SUNDAY; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Start date must be a Monday'); }); it('rejects creation with a past-week startDate with 400', async () => { const app = buildApp(); const body = planBody('Past create'); body.startDate = PAST_MONDAY; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Start date cannot be in the past'); }); it('creates a DRAFT with a planned startDate; activation is a separate step', async () => { const app = buildApp(); const body = planBody('One-step plan'); body.startDate = MONDAY; const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(201); expect(res.body.plan).toMatchObject({ title: 'One-step plan', status: 'DRAFT' }); expect(res.body).not.toHaveProperty('activationSkipped'); expect(res.body.plan.startDate).not.toBeNull(); // szkic z planowanym startem: dni bez dat — daty dopiero przy aktywacji const detail = await app .get(`/api/v1/plans/${res.body.plan.id}`) .set('Authorization', `Bearer ${token}`); expect(detail.body.plan.status).toBe('DRAFT'); const localDate = (iso: string) => { const d = new Date(iso); return [d.getFullYear(), d.getMonth() + 1, d.getDate()]; }; const [sy, sm, sd] = MONDAY.split('-').map(Number); const week0 = detail.body.plan.weeks.find((w: { index: number }) => w.index === 0); const day1 = week0.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); expect(day1.date).toBeNull(); // aktywacja osobną akcją — daty wyliczone od startu const act = await app .post(`/api/v1/plans/${res.body.plan.id}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: MONDAY }); expect(act.status).toBe(200); const detail2 = await app .get(`/api/v1/plans/${res.body.plan.id}`) .set('Authorization', `Bearer ${token}`); expect(detail2.body.plan.status).toBe('ACTIVE'); const week0b = detail2.body.plan.weeks.find((w: { index: number }) => w.index === 0); const day1b = week0b.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); expect(localDate(day1b.date)).toEqual([sy, sm, sd]); }); it('creates a DRAFT with startDate even while another plan is active (no auto-activation)', async () => { // "One-step plan" from the previous test is ACTIVE (activated explicitly). const app = buildApp(); const body = planBody('Conflicting plan'); body.startDate = mondayIso(2); const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body); expect(res.status).toBe(201); expect(res.body).not.toHaveProperty('activationSkipped'); expect(res.body.plan).toMatchObject({ title: 'Conflicting plan', status: 'DRAFT' }); // planowany start zostaje zapisany mimo aktywnego planu właściciela expect(res.body.plan.startDate).not.toBeNull(); }); it('allows multiple draft plans while one plan is active', async () => { // Wdrożenie paru planów: szkice mogą współistnieć z aktywnym planem, // blokada dotyczy wyłącznie posiadania więcej niż jednego AKTYWNEGO. const app = buildApp(); const first = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Draft A')); expect(first.status).toBe(201); expect(first.body.plan.status).toBe('DRAFT'); const second = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(planBody('Draft B')); expect(second.status).toBe(201); expect(second.body.plan.status).toBe('DRAFT'); const list = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`); const statuses = list.body.plans .filter((p: { title: string }) => ['Draft A', 'Draft B', 'One-step plan'].includes(p.title)) .map((p: { status: string }) => p.status); expect(statuses.filter((s: string) => s === 'ACTIVE')).toHaveLength(1); expect(statuses.filter((s: string) => s === 'DRAFT')).toHaveLength(2); }); it('rejects concurrent activation of two drafts — at most one ends up ACTIVE', async () => { // "One-step plan" został ukończony/porzucony? Nie — jest ACTIVE, więc // najpierw go porzucamy, by dwa nowe szkice mogły walczyć o aktywację. const app = buildApp(); const list = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`); const active = list.body.plans.find((p: { status: string }) => p.status === 'ACTIVE'); if (active) { await app.post(`/api/v1/plans/${active.id}/abandon`).set('Authorization', `Bearer ${token}`); } const [a, b] = await Promise.all( ['Race A', 'Race B'].map((title) => app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(planBody(title)), ), ); const results = await Promise.all( [a, b].map((created, i) => app .post(`/api/v1/plans/${created.body.plan.id}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: mondayIso(i + 1) }), ), ); const ok = results.filter((r) => r.status === 200); const conflicted = results.filter((r) => r.status === 409); expect(ok).toHaveLength(1); expect(conflicted).toHaveLength(1); const after = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`); const activeCount = after.body.plans.filter( (p: { status: string }) => p.status === 'ACTIVE', ).length; expect(activeCount).toBe(1); }); }); describe('plans: gym and week alias', () => { let token: string; let exerciseId: string; let gymId: string; let otherGymId: string; const body = (title: string) => ({ title, weeksCount: 1, weeks: [ { index: 0, customName: 'Deload', days: [ { dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] }, ], }, ], }); beforeAll(async () => { const reg = await registerViaApi(); token = reg.token; exerciseId = (await createExercise()).id; const gym = await prisma.gym.create({ data: { name: `Plan Gym ${rand()}` } }); gymId = gym.id; const other = await prisma.gym.create({ data: { name: `Other Gym ${rand()}` } }); otherGymId = other.id; await prisma.gymMembership.create({ data: { userId: reg.user.id, gymId, roles: ['MEMBER'] as never }, }); }); it('creates a plan with gymId and per-week customName', async () => { const app = buildApp(); const res = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send({ ...body('Z siłownią'), gymId }); expect(res.status).toBe(201); expect(res.body.plan.gym).toMatchObject({ id: gymId }); expect(res.body.plan.gym.name).toBeTruthy(); const detail = await app .get(`/api/v1/plans/${res.body.plan.id}`) .set('Authorization', `Bearer ${token}`); expect(detail.body.plan.gym).toMatchObject({ id: gymId }); expect(detail.body.plan.weeks[0].customName).toBe('Deload'); }); it('lists plans with the gym attached', async () => { const app = buildApp(); const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`); const found = res.body.plans.find((p: { title: string }) => p.title === 'Z siłownią'); expect(found.gym).toMatchObject({ id: gymId }); }); it('rejects creation with a gym the user is not a member of with 400', async () => { const app = buildApp(); const res = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send({ ...body('Bez członkostwa'), gymId: otherGymId }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Plan owner is not a member of the gym'); }); it('rejects creation with an unknown gymId with 400', async () => { const app = buildApp(); const res = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send({ ...body('Nieznana siłownia'), gymId: 'nonexistent-gym' }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Unknown gymId in plan'); }); it('rejects a week alias longer than 40 chars with 400', async () => { const app = buildApp(); const b = body('Długi alias'); b.weeks[0].customName = 'a'.repeat(41); const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(b); expect(res.status).toBe(400); }); it('updates gymId and customName via PATCH', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(body('Do zmiany')); const id = created.body.plan.id; const res = await app .patch(`/api/v1/plans/${id}`) .set('Authorization', `Bearer ${token}`) .send({ ...body('Do zmiany v2'), gymId, weeks: [{ index: 0, customName: null, days: [] }] }); expect(res.status).toBe(200); const detail = await app.get(`/api/v1/plans/${id}`).set('Authorization', `Bearer ${token}`); expect(detail.body.plan.gym).toMatchObject({ id: gymId }); expect(detail.body.plan.weeks[0].customName).toBeNull(); }); it('clears gymId to null when the gym is deleted', async () => { const app = buildApp(); const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send({ ...body('Plan z siłownią do usunięcia'), gymId }); const id = created.body.plan.id; await prisma.gym.delete({ where: { id: gymId } }); const detail = await app.get(`/api/v1/plans/${id}`).set('Authorization', `Bearer ${token}`); expect(detail.body.plan.gym).toBeNull(); }); }); describe('plans: direct seeding sanity', () => { it('seedPlan creates a consistent structure in the database', async () => { const { user } = await createUser(); const exercise = await createExercise(); const plan = await seedPlan({ userId: user.id, status: 'ACTIVE', startDate: new Date(Date.UTC(2026, 7, 24)), weeks: [ { index: 0, days: [ { dayOfWeek: 1, date: new Date(Date.UTC(2026, 7, 24)), exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }], }, ], }, ], }); expect(plan.weeks).toHaveLength(1); const day = plan.weeks[0].days[0]; expect(day.exercises).toHaveLength(1); expect(day.exercises[0].sets).toHaveLength(1); expect(day.exercises[0].sets[0].reps).toBe(10); expect(day.exercises[0].exercise.id).toBe(exercise.id); await prisma.trainingPlan.delete({ where: { id: plan.id } }); }); }); describe('plans: trainer-created plan (creator + owner access)', () => { let app: ReturnType; let trainerToken: string; let traineeToken: string; let plainToken: string; let trainerId: string; let traineeId: string; let exerciseId: string; let planId: string; const body = (title: string) => ({ title, weeksCount: 1, weeks: [ { index: 0, days: [ { dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10, loadKg: 60 }] }], }, ], }, ], }); beforeAll(async () => { app = buildApp(); const t = await createUser({ firstName: 'VisTrainer' }); const tr = await createUser({ firstName: 'VisTrainee' }); const p = await createUser({ firstName: 'VisPlain' }); trainerId = t.user.id; traineeId = tr.user.id; const gym = await prisma.gym.create({ data: { name: `Vis Gym ${rand()}` } }); await prisma.gymMembership.create({ data: { userId: trainerId, gymId: gym.id, roles: ['TRAINER'] as never }, }); await prisma.gymMembership.create({ data: { userId: traineeId, gymId: gym.id, roles: ['MEMBER'] as never }, }); await prisma.gymMembership.create({ data: { userId: p.user.id, gymId: gym.id, roles: ['MEMBER'] as never }, }); trainerToken = (await loginViaApi(t.user.email, PASSWORD)).token; traineeToken = (await loginViaApi(tr.user.email, PASSWORD)).token; plainToken = (await loginViaApi(p.user.email, PASSWORD)).token; await prisma.coaching.create({ data: { trainerId, userId: traineeId, invitedBy: trainerId, status: 'ACTIVE', expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), }, }); const ex = await createExercise(); exerciseId = ex.id; const res = await app .post(`/api/v1/trainer/trainees/${traineeId}/plans`) .set('Authorization', `Bearer ${trainerToken}`) .send(body('Plan trenerski')); expect(res.status).toBe(201); planId = res.body.plan.id; }); it('includes the creator in GET /plans for the owner', async () => { const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${traineeToken}`); expect(res.status).toBe(200); const found = res.body.plans.find((pl: { id: string }) => pl.id === planId); expect(found).toBeTruthy(); expect(found.creator).toMatchObject({ id: trainerId, firstName: 'VisTrainer' }); }); it('the owner (trainee) can edit the trainer-created draft', async () => { const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${traineeToken}`) .send(body('Plan trenerski v2')); expect(res.status).toBe(200); expect(res.body).toMatchObject({ ok: true }); }); it('a third user gets 404 for the plan', async () => { const res = await app .get(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${plainToken}`); expect(res.status).toBe(404); }); it('trainer can attach a gym the trainee is a member of', async () => { const gym = await prisma.gym.create({ data: { name: `Trainee Gym ${rand()}` } }); await prisma.gymMembership.create({ data: { userId: traineeId, gymId: gym.id, roles: ['MEMBER'] as never }, }); const res = await app .post(`/api/v1/trainer/trainees/${traineeId}/plans`) .set('Authorization', `Bearer ${trainerToken}`) .send({ ...body('Plan z siłownią'), gymId: gym.id }); expect(res.status).toBe(201); expect(res.body.plan.gym).toMatchObject({ id: gym.id }); }); it('trainer cannot attach a gym the trainee is NOT a member of (400)', async () => { const gym = await prisma.gym.create({ data: { name: `Trainer-only Gym ${rand()}` } }); await prisma.gymMembership.create({ data: { userId: trainerId, gymId: gym.id, roles: ['TRAINER'] as never }, }); const res = await app .post(`/api/v1/trainer/trainees/${traineeId}/plans`) .set('Authorization', `Bearer ${trainerToken}`) .send({ ...body('Plan bez członkostwa'), gymId: gym.id }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Plan owner is not a member of the gym'); }); }); describe('plans: sharing (PlanShare)', () => { let app: ReturnType; let trainer: { user: { id: string }; token: string }; let trainee: { user: { id: string }; token: string }; let stranger: { user: { id: string }; token: string }; let exerciseId: string; let planId: string; const body = (title: string) => ({ title, weeksCount: 1, weeks: [ { index: 0, days: [ { dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] }, ], }, ], }); beforeAll(async () => { app = buildApp(); trainer = await createUserWithToken({ firstName: 'ShareTrainer' }); trainee = await createUserWithToken({ firstName: 'ShareTrainee' }); stranger = await createUserWithToken({ firstName: 'ShareStranger' }); // ACTIVE coaching: trainer -> trainee await prisma.coaching.create({ data: { trainerId: trainer.user.id, userId: trainee.user.id, invitedBy: trainer.user.id, status: 'ACTIVE', expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), }, }); const ex = await createExercise(); exerciseId = ex.id; // plan należy do podopiecznego (właściciel = podopieczny) const res = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${trainee.token}`) .send(body('Plan do udostępnienia')); expect(res.status).toBe(201); planId = res.body.plan.id; }); it('non-owner (trainer) cannot share the plan (403)', async () => { const res = await app .post(`/api/v1/plans/${planId}/share`) .set('Authorization', `Bearer ${trainer.token}`) .send({ userId: trainee.user.id }); expect(res.status).toBe(403); expect(res.body.error.message).toBe('Only the plan owner can share the plan'); }); it('owner cannot share the plan with themselves (400)', async () => { const res = await app .post(`/api/v1/plans/${planId}/share`) .set('Authorization', `Bearer ${trainee.token}`) .send({ userId: trainee.user.id }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Cannot share a plan with yourself'); }); it('owner cannot share with a user without an active coaching relation (400)', async () => { const res = await app .post(`/api/v1/plans/${planId}/share`) .set('Authorization', `Bearer ${trainee.token}`) .send({ userId: stranger.user.id }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('No active coaching relation with this user'); }); it('owner shares the plan with the trainer (201)', async () => { const res = await app .post(`/api/v1/plans/${planId}/share`) .set('Authorization', `Bearer ${trainee.token}`) .send({ userId: trainer.user.id }); expect(res.status).toBe(201); expect(res.body.share).toMatchObject({ id: expect.any(String) }); }); it('duplicate share is rejected with 409', async () => { const res = await app .post(`/api/v1/plans/${planId}/share`) .set('Authorization', `Bearer ${trainee.token}`) .send({ userId: trainer.user.id }); expect(res.status).toBe(409); expect(res.body.error.message).toBe('Plan is already shared with this user'); }); it('the owner sees the recipients in the plan detail', async () => { const res = await app .get(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${trainee.token}`); expect(res.status).toBe(200); expect(res.body.plan.shares).toEqual([ { userId: trainer.user.id, user: { id: trainer.user.id, firstName: 'ShareTrainer', lastName: null }, }, ]); expect(res.body.plan.canManage).toBe(true); }); it('the recipient sees the plan in /plans/shared-with-me', async () => { const res = await app .get('/api/v1/plans/shared-with-me') .set('Authorization', `Bearer ${trainer.token}`); expect(res.status).toBe(200); const found = res.body.plans.find((p: { id: string }) => p.id === planId); expect(found).toBeTruthy(); expect(found.sharedBy).toMatchObject({ id: trainee.user.id, firstName: 'ShareTrainee' }); expect(found.progress).toEqual({ completed: 0, total: 1, percent: 0 }); }); it('the trainee sees the trainer in /me/trainers', async () => { const res = await app .get('/api/v1/me/trainers') .set('Authorization', `Bearer ${trainee.token}`); expect(res.status).toBe(200); expect(res.body.trainers).toEqual([ { id: trainer.user.id, firstName: 'ShareTrainer', lastName: null, nickname: null }, ]); }); it('the trainer (ACTIVE coaching) still manages the plan via the owner route? NO — owner route is owner-only (404)', async () => { const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${trainer.token}`) .send(body('Trener edytuje')); expect(res.status).toBe(404); }); it('the share survives the coaching ending: recipient keeps read-only access', async () => { await prisma.coaching.updateMany({ where: { trainerId: trainer.user.id, userId: trainee.user.id }, data: { status: 'ARCHIVED' }, }); const res = await app .get(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${trainer.token}`); expect(res.status).toBe(200); expect(res.body.plan.canManage).toBe(false); expect(res.body.plan.shares).toBeUndefined(); }); it('a stranger gets 404 for the shared plan', async () => { const res = await app .get(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${stranger.token}`); expect(res.status).toBe(404); }); it('the owner revokes the share (204) and the recipient loses access', async () => { const res = await app .delete(`/api/v1/plans/${planId}/share/${trainer.user.id}`) .set('Authorization', `Bearer ${trainee.token}`); expect(res.status).toBe(204); const detail = await app .get(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${trainer.token}`); expect(detail.status).toBe(404); const list = await app .get('/api/v1/plans/shared-with-me') .set('Authorization', `Bearer ${trainer.token}`); expect(list.body.plans.find((p: { id: string }) => p.id === planId)).toBeUndefined(); }); it('revoking a missing share is 404', async () => { const res = await app .delete(`/api/v1/plans/${planId}/share/${trainer.user.id}`) .set('Authorization', `Bearer ${trainee.token}`); expect(res.status).toBe(404); }); }); describe('plans: PATCH with startDate (planowany start, bez autoaktywacji)', () => { let app: ReturnType; let token: string; let userId: string; let exerciseId: string; let planId: string; const body = (title: string, weeksCount = 1) => ({ title, weeksCount, weeks: [ { index: 0, days: [ { dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] }, ], }, ], }); beforeAll(async () => { app = buildApp(); const reg = await createUserWithToken(); token = reg.token; userId = reg.user.id; const ex = await createExercise(); exerciseId = ex.id; const res = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(body('Draft do aktywacji')); expect(res.status).toBe(201); planId = res.body.plan.id; }); it('PATCH without startDate keeps the plan DRAFT', async () => { const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send(body('Draft v2')); expect(res.status).toBe(200); const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); expect(detail.body.plan.status).toBe('DRAFT'); expect(detail.body.plan.startDate).toBeNull(); }); it('PATCH with a non-Monday startDate is rejected with 400', async () => { const [y, m, d] = mondayIso(1).split('-').map(Number); const tuesday = new Date(y, m - 1, d + 1); const tuesdayIso = `${tuesday.getFullYear()}-${String(tuesday.getMonth() + 1).padStart(2, '0')}-${String(tuesday.getDate()).padStart(2, '0')}`; const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send({ ...body('Wtorek'), startDate: tuesdayIso }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Start date must be a Monday'); }); it('PATCH with a past-week startDate is rejected with 400', async () => { const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send({ ...body('Miniony'), startDate: mondayIso(-1) }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Start date cannot be in the past'); }); it('PATCH with startDate updates the structure and stores the planned start (still DRAFT)', async () => { const res = await app .patch(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`) .send({ ...body('Aktywowany'), startDate: mondayIso(1) }); expect(res.status).toBe(200); const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`); expect(detail.body.plan.status).toBe('DRAFT'); expect(detail.body.plan.title).toBe('Aktywowany'); // startDate = północ lokalna — serializowana jako ISO w UTC, więc porównanie przez datę lokalną const localKey = (iso: string) => { const d = new Date(iso); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }; expect(localKey(String(detail.body.plan.startDate))).toBe(mondayIso(1)); // aktywacja osobną akacją domyka flow: status + daty dni const act = await app .post(`/api/v1/plans/${planId}/activate`) .set('Authorization', `Bearer ${token}`) .send({ startDate: mondayIso(1) }); expect(act.status).toBe(200); const detail2 = await app .get(`/api/v1/plans/${planId}`) .set('Authorization', `Bearer ${token}`); expect(detail2.body.plan.status).toBe('ACTIVE'); const localDate = (iso: string) => { const d = new Date(iso); return [d.getFullYear(), d.getMonth() + 1, d.getDate()]; }; const [sy, sm, sd] = mondayIso(1).split('-').map(Number); const day1 = detail2.body.plan.weeks .find((w: { index: number }) => w.index === 0) .days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); expect(localDate(day1.date)).toEqual([sy, sm, sd]); }); it('PATCH with startDate saves the planned start as a DRAFT (no auto-activation)', async () => { const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(body('Konflikt')); const res = await app .patch(`/api/v1/plans/${created.body.plan.id}`) .set('Authorization', `Bearer ${token}`) .send({ ...body('Konflikt'), startDate: mondayIso(2) }); expect(res.status).toBe(200); expect(res.body).not.toHaveProperty('activationSkipped'); const detail = await app .get(`/api/v1/plans/${created.body.plan.id}`) .set('Authorization', `Bearer ${token}`); expect(detail.body.plan).toMatchObject({ status: 'DRAFT' }); // planowany start zapisany — daty dni wciąż puste (aktywacja osobno); // porównanie przez datę lokalną (północ lokalna serializowana jako ISO UTC) const localKey = (iso: string) => { const d = new Date(iso); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }; expect(localKey(String(detail.body.plan.startDate))).toBe(mondayIso(2)); const day1 = detail.body.plan.weeks .find((w: { index: number }) => w.index === 0) .days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1); expect(day1.date).toBeNull(); }); it('PATCH with startDate and a day falling before today → 400 PLAN_DAY_IN_PAST', async () => { const created = await app .post('/api/v1/plans') .set('Authorization', `Bearer ${token}`) .send(body('Minione dni')); // poniedziałek bieżącego tygodnia: dni przed dzisiaj wypadałyby w przeszłości const dowToday = ((new Date().getDay() + 6) % 7) + 1; // 1=Pn .. 7=Nd if (dowToday <= 1) return; // w poniedziałek nie ma minionych dni w tym tygodniu const pastBody = body('Minione dni'); pastBody.weeks[0].days = [ { dayOfWeek: dowToday - 1, exercises: pastBody.weeks[0].days[0].exercises }, ]; const res = await app .patch(`/api/v1/plans/${created.body.plan.id}`) .set('Authorization', `Bearer ${token}`) .send({ ...pastBody, startDate: mondayIso(0) }); expect(res.status).toBe(400); expect(res.body.error.code).toBe('PLAN_DAY_IN_PAST'); }); }); describe('PATCH /plans/:id/gym — zmiana siłowni planu (modal rozpoczęcia treningu)', () => { it('changes the informational gym of an ACTIVE plan (owner + member) and returns the gym', async () => { const app = buildApp(); const { user, token } = await registerViaApi(); const gym = await prisma.gym.create({ data: { name: `Plan Gym ${rand()}`, kind: 'REAL' } }); await prisma.gymMembership.create({ data: { userId: user.id, gymId: gym.id, roles: ['MEMBER'] }, }); const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' }); const res = await app .patch(`/api/v1/plans/${plan.id}/gym`) .set('Authorization', `Bearer ${token}`) .send({ gymId: gym.id }); expect(res.status).toBe(200); expect(res.body.plan).toEqual({ id: plan.id, gym: { id: gym.id, name: gym.name } }); const row = await prisma.trainingPlan.findUnique({ where: { id: plan.id } }); expect(row?.gymId).toBe(gym.id); const cleared = await app .patch(`/api/v1/plans/${plan.id}/gym`) .set('Authorization', `Bearer ${token}`) .send({ gymId: null }); expect(cleared.status).toBe(200); expect(cleared.body.plan.gym).toBeNull(); }); it('rejects a gym the owner is not a member of with 400 and an unknown gym with 400', async () => { const app = buildApp(); const { user, token } = await registerViaApi(); const foreign = await prisma.gym.create({ data: { name: `Foreign Gym ${rand()}`, kind: 'REAL' }, }); const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' }); const notMember = await app .patch(`/api/v1/plans/${plan.id}/gym`) .set('Authorization', `Bearer ${token}`) .send({ gymId: foreign.id }); expect(notMember.status).toBe(400); expect(notMember.body.error.message).toMatch(/member/i); const unknown = await app .patch(`/api/v1/plans/${plan.id}/gym`) .set('Authorization', `Bearer ${token}`) .send({ gymId: 'nope' }); expect(unknown.status).toBe(400); expect(unknown.body.error.message).toMatch(/Unknown gymId/); }); it('returns 404 for another user plan and 400 when gymId field is missing', async () => { const app = buildApp(); const { user } = await registerViaApi(); const intruder = await registerViaApi(); const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' }); const res = await app .patch(`/api/v1/plans/${plan.id}/gym`) .set('Authorization', `Bearer ${intruder.token}`) .send({ gymId: null }); expect(res.status).toBe(404); const missing = await app .patch(`/api/v1/plans/${plan.id}/gym`) .set('Authorization', `Bearer ${intruder.token}`) .send({}); expect(missing.status).toBe(400); }); }); describe('usuwanie planów (dowolny status)', () => { it('deletes an ACTIVE plan together with its days (kaskada)', async () => { const app = buildApp(); const { user, token } = await createUserWithToken(); const exercise = await createExercise(); const plan = await seedPlan({ userId: user.id, status: 'ACTIVE', startDate: new Date(), weeks: [ { index: 0, days: [ { dayOfWeek: 1, date: new Date(), exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }], }, ], }, ], }); const res = await app .delete(`/api/v1/plans/${plan.id}`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(204); expect(await prisma.trainingPlan.findUnique({ where: { id: plan.id } })).toBeNull(); expect(await prisma.planDay.count({ where: { week: { planId: plan.id } } })).toBe(0); expect(await prisma.planExercise.count({ where: { day: { week: { planId: plan.id } } } })).toBe( 0, ); }); it('deletes a COMPLETED plan', async () => { const app = buildApp(); const { user, token } = await createUserWithToken(); const plan = await seedPlan({ userId: user.id, status: 'COMPLETED' }); const res = await app .delete(`/api/v1/plans/${plan.id}`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(204); expect(await prisma.trainingPlan.findUnique({ where: { id: plan.id } })).toBeNull(); }); it('returns 404 when a non-owner deletes the plan', async () => { const app = buildApp(); const { user } = await createUserWithToken(); const intruder = await createUserWithToken(); const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' }); const res = await app .delete(`/api/v1/plans/${plan.id}`) .set('Authorization', `Bearer ${intruder.token}`); expect(res.status).toBe(404); expect(await prisma.trainingPlan.findUnique({ where: { id: plan.id } })).not.toBeNull(); }); }); describe('PATCH /plans/:id/days/:dayId/move — przesunięcie dnia treningowego', () => { let token: string; let planId: string; let skippedDayId: string; let completedDayId: string; let plannedDayId: string; let nextDayId: string; function localDay(offset: number): Date { const d = new Date(); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + offset); return d; } function isoDay(offset: number): string { const d = localDay(offset); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; } const localParts = (iso: string) => { const d = new Date(iso); return [d.getFullYear(), d.getMonth() + 1, d.getDate()]; }; beforeEach(async () => { const { user, token: t } = await createUserWithToken(); token = t; const exercise = await createExercise(); const seedEx = [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }]; const plan = await seedPlan({ userId: user.id, status: 'ACTIVE', startDate: localDay(-7), weeks: [ { index: 0, days: [ { dayOfWeek: 1, date: localDay(-7), status: 'SKIPPED' }, { dayOfWeek: 3, date: localDay(-5), status: 'COMPLETED' }, { dayOfWeek: 5, date: localDay(0), status: 'PLANNED', exercises: seedEx }, { dayOfWeek: 6, date: localDay(1), status: 'PLANNED', exercises: seedEx }, ], }, ], }); planId = plan.id; const byDow = new Map(plan.weeks[0].days.map((d) => [d.dayOfWeek, d.id] as const)); skippedDayId = byDow.get(1)!; completedDayId = byDow.get(3)!; plannedDayId = byDow.get(5)!; nextDayId = byDow.get(6)!; }); it('postpones a planned day and writes the move log with the reason', async () => { const app = buildApp(); const res = await app .patch(`/api/v1/plans/${planId}/days/${plannedDayId}/move`) .set('Authorization', `Bearer ${token}`) .send({ date: isoDay(3), reason: 'wyjazd służbowy' }); expect(res.status).toBe(200); expect(res.body.day).toMatchObject({ id: plannedDayId, status: 'PLANNED' }); const day = await prisma.planDay.findUnique({ where: { id: plannedDayId }, include: { moveLog: true }, }); expect(localParts(day!.date!.toISOString())).toEqual(localParts(isoDay(3))); expect(day!.status).toBe('PLANNED'); expect(day!.moveLog).toHaveLength(1); expect(day!.moveLog[0].reason).toBe('wyjazd służbowy'); // kalendarz pokazuje dzień w nowej dacie const cal = await app .get(`/api/v1/calendar?month=${isoDay(3).slice(0, 7)}`) .set('Authorization', `Bearer ${token}`); const ids = cal.body.days.map((d: { id: string }) => d.id); expect(ids).toContain(plannedDayId); expect(cal.body.days.find((d: { id: string }) => d.id === plannedDayId).moves).toBe(1); expect(cal.body.days.find((d: { id: string }) => d.id === plannedDayId).planId).toBe(planId); }); it('revives a skipped day when it is moved into the future', async () => { const app = buildApp(); const res = await app .patch(`/api/v1/plans/${planId}/days/${skippedDayId}/move`) .set('Authorization', `Bearer ${token}`) .send({ date: isoDay(2), reason: 'choroba' }); expect(res.status).toBe(200); expect(res.body.day).toMatchObject({ status: 'PLANNED' }); const day = await prisma.planDay.findUnique({ where: { id: skippedDayId } }); expect(day!.status).toBe('PLANNED'); expect(day!.skippedAt).toBeNull(); // decyzja wyzerowana — gdy przesunięty dzień znowu minie, dialog zapyta ponownie expect(day!.skipResolvedAt).toBeNull(); }); it('refuses to move a completed day with 400', async () => { const app = buildApp(); const res = await app .patch(`/api/v1/plans/${planId}/days/${completedDayId}/move`) .set('Authorization', `Bearer ${token}`) .send({ date: isoDay(2) }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('A completed day cannot be moved'); }); it('refuses a date in the past with 400', async () => { const app = buildApp(); const res = await app .patch(`/api/v1/plans/${planId}/days/${plannedDayId}/move`) .set('Authorization', `Bearer ${token}`) .send({ date: isoDay(-1) }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Target date cannot be in the past'); }); it('refuses to move a day of a non-active plan with 400', async () => { const app = buildApp(); const { user, token: ownerToken } = await createUserWithToken(); const draft = await seedPlan({ userId: user.id, status: 'DRAFT', weeks: [{ index: 0, days: [{ dayOfWeek: 1, status: 'PLANNED' }] }], }); const res = await app .patch(`/api/v1/plans/${draft.id}/days/${draft.weeks[0].days[0].id}/move`) .set('Authorization', `Bearer ${ownerToken}`) .send({ date: isoDay(2) }); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Only active plans have movable training days'); }); it('conflicts with a planned day on the target date and swaps on request', async () => { const app = buildApp(); const clash = await app .patch(`/api/v1/plans/${planId}/days/${plannedDayId}/move`) .set('Authorization', `Bearer ${token}`) .send({ date: isoDay(1) }); expect(clash.status).toBe(409); expect(clash.body.error.message).toBe('Another training is already planned on that date'); // klient (kalendarz) potrzebuje id kolidanta, żeby zaproponować zamianę expect(clash.body.error.code).toBe('PLAN_DAY_TAKEN'); expect(clash.body.error.details).toMatchObject({ conflictDayId: expect.any(String) }); const swapped = await app .patch(`/api/v1/plans/${planId}/days/${plannedDayId}/move`) .set('Authorization', `Bearer ${token}`) .send({ date: isoDay(1), swapWithDayId: nextDayId, reason: 'zamiana dni' }); expect(swapped.status).toBe(200); expect(swapped.body.swappedWith).toBe(nextDayId); const a = await prisma.planDay.findUnique({ where: { id: plannedDayId } }); const b = await prisma.planDay.findUnique({ where: { id: nextDayId } }); expect(localParts(a!.date!.toISOString())).toEqual(localParts(isoDay(1))); expect(localParts(b!.date!.toISOString())).toEqual(localParts(isoDay(0))); expect(await prisma.dayMove.count({ where: { dayId: plannedDayId } })).toBe(1); expect(await prisma.dayMove.count({ where: { dayId: nextDayId } })).toBe(1); }); it('returns 404 for a day that is not part of the plan and for another user', async () => { const app = buildApp(); const stranger = await createUserWithToken(); const strangerPlan = await seedPlan({ userId: stranger.user.id, status: 'ACTIVE', startDate: localDay(-7), weeks: [{ index: 0, days: [{ dayOfWeek: 2, date: localDay(-6), status: 'PLANNED' }] }], }); const foreignDayId = strangerPlan.weeks[0].days[0].id; const wrongDay = await app .patch(`/api/v1/plans/${planId}/days/${foreignDayId}/move`) .set('Authorization', `Bearer ${token}`) .send({ date: isoDay(2) }); expect(wrongDay.status).toBe(404); expect(wrongDay.body.error.message).toBe('Training day not found'); const intruder = await app .patch(`/api/v1/plans/${planId}/days/${plannedDayId}/move`) .set('Authorization', `Bearer ${stranger.token}`) .send({ date: isoDay(2) }); expect(intruder.status).toBe(404); expect(intruder.body.error.message).toBe('Plan not found'); }); }); describe('POST /plans/:id/days/:dayId/skip/accept — akceptacja pominiętego dnia', () => { let token: string; let planId: string; let skippedDayId: string; let plannedDayId: string; function localDay(offset: number): Date { const d = new Date(); d.setHours(0, 0, 0, 0); d.setDate(d.getDate() + offset); return d; } beforeEach(async () => { const { user, token: t } = await createUserWithToken(); token = t; const plan = await seedPlan({ userId: user.id, status: 'ACTIVE', startDate: localDay(-7), weeks: [ { index: 0, days: [ { dayOfWeek: 1, date: localDay(-6), status: 'SKIPPED', skippedAt: localDay(-5) }, { dayOfWeek: 5, date: localDay(0), status: 'PLANNED' }, ], }, ], }); planId = plan.id; const byDow = new Map(plan.weeks[0].days.map((d) => [d.dayOfWeek, d.id] as const)); skippedDayId = byDow.get(1)!; plannedDayId = byDow.get(5)!; }); it('accepts an unresolved skipped day: 200, skipResolvedAt in DB and an audit entry', async () => { const app = buildApp(); const res = await app .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); expect(res.body.day).toMatchObject({ id: skippedDayId, status: 'SKIPPED' }); expect(res.body.day.skipResolvedAt).toEqual(expect.any(String)); const day = await prisma.planDay.findUnique({ where: { id: skippedDayId } }); expect(day!.status).toBe('SKIPPED'); expect(day!.skipResolvedAt).toBeInstanceOf(Date); const log = await prisma.activityLog.findFirst({ where: { action: 'plan.day.skip.accepted', entityId: planId }, }); expect(log).not.toBeNull(); expect(log!.details).toMatchObject({ dayId: skippedDayId }); }); it('is idempotent: a second accept returns 200 without rewriting the decision', async () => { const app = buildApp(); const first = await app .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) .set('Authorization', `Bearer ${token}`); expect(first.status).toBe(200); const second = await app .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) .set('Authorization', `Bearer ${token}`); expect(second.status).toBe(200); expect(second.body.day.skipResolvedAt).toBe(first.body.day.skipResolvedAt); const day = await prisma.planDay.findUnique({ where: { id: skippedDayId } }); expect(day!.skipResolvedAt).toBeInstanceOf(Date); }); it('refuses a planned day with 400', async () => { const app = buildApp(); const res = await app .post(`/api/v1/plans/${planId}/days/${plannedDayId}/skip/accept`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(400); expect(res.body.error.message).toBe('Only a skipped training day can be accepted'); }); it('returns 404 for another user and for a day outside the plan', async () => { const app = buildApp(); const stranger = await createUserWithToken(); const strangerPlan = await seedPlan({ userId: stranger.user.id, status: 'ACTIVE', startDate: localDay(-7), weeks: [{ index: 0, days: [{ dayOfWeek: 2, date: localDay(-6), status: 'SKIPPED' }] }], }); const intruder = await app .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) .set('Authorization', `Bearer ${stranger.token}`); expect(intruder.status).toBe(404); expect(intruder.body.error.message).toBe('Plan not found'); const wrongDay = await app .post(`/api/v1/plans/${planId}/days/${strangerPlan.weeks[0].days[0].id}/skip/accept`) .set('Authorization', `Bearer ${token}`); expect(wrongDay.status).toBe(404); expect(wrongDay.body.error.message).toBe('Training day not found'); }); });