Files
FitOS/api/test/integration/plans.test.ts

1005 lines
37 KiB
TypeScript

import { describe, it, expect, beforeAll } 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: [] },
],
},
{ index: 1, days: [{ dayOfWeek: 2, exercises: [] }] },
],
});
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 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('rejects editing an active plan 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('Only draft plans can be edited');
});
it('rejects deleting an active plan with 400', async () => {
const app = buildApp();
const res = await app.delete(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Only draft plans can be deleted');
});
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('Plan is already closed');
});
it('completes a draft 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 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('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 and activates a plan in one step when startDate is provided', 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: 'ACTIVE' });
expect(res.body.plan.startDate).not.toBeNull();
const detail = await app
.get(`/api/v1/plans/${res.body.plan.id}`)
.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 week0 = detail.body.plan.weeks.find((w: { index: number }) => w.index === 0);
const day1 = week0.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1);
expect(localDate(day1.date)).toEqual([sy, sm, sd]);
});
it('creates a DRAFT with activationSkipped when startDate is set while another plan is active', async () => {
// "One-step plan" from the previous test is ACTIVE.
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.activationSkipped).toBe(true);
expect(res.body.plan).toMatchObject({ title: 'Conflicting plan', status: 'DRAFT' });
expect(res.body.plan.startDate).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<typeof buildApp>;
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<typeof buildApp>;
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 (update + activate)', () => {
let app: ReturnType<typeof buildApp>;
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 activates the plan', 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('ACTIVE');
expect(detail.body.plan.title).toBe('Aktywowany');
expect(detail.body.plan.startDate).not.toBeNull();
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 = detail.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 while another plan is active saves the structure as a DRAFT (activationSkipped)', 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).toMatchObject({ ok: true, activationSkipped: true });
const detail = await app
.get(`/api/v1/plans/${created.body.plan.id}`)
.set('Authorization', `Bearer ${token}`);
expect(detail.body.plan).toMatchObject({ status: 'DRAFT' });
expect(detail.body.plan.startDate).toBeNull();
});
});