1077 lines
42 KiB
TypeScript
1077 lines
42 KiB
TypeScript
import { describe, it, expect, beforeAll } from 'vitest';
|
||
import { prisma } from '../../src/lib/prisma.js';
|
||
import {
|
||
buildApp,
|
||
createExercise,
|
||
createUser,
|
||
loginViaApi,
|
||
rand,
|
||
seedPlan,
|
||
seedSession,
|
||
PASSWORD,
|
||
} from '../helpers.js';
|
||
|
||
async function createMembership(userId: string, gymId: string, roles: string[]) {
|
||
return prisma.gymMembership.create({
|
||
data: { userId, gymId, roles: roles as never },
|
||
});
|
||
}
|
||
|
||
describe('trainer — invitations and trainees', () => {
|
||
let app: ReturnType<typeof buildApp>;
|
||
let trainer: { id: string; email: string; token: string };
|
||
let trainee: { id: string; email: string; token: string };
|
||
let plain: { id: string; email: string; token: string };
|
||
let gymId: string;
|
||
|
||
beforeAll(async () => {
|
||
app = buildApp();
|
||
const t = await createUser({ firstName: 'Tomasz' });
|
||
const tr = await createUser({ firstName: 'Anna' });
|
||
const p = await createUser({ firstName: 'Piotr' });
|
||
const gym = await prisma.gym.create({ data: { name: `Trainer Gym ${rand()}` } });
|
||
gymId = gym.id;
|
||
await createMembership(t.user.id, gymId, ['TRAINER']);
|
||
await createMembership(tr.user.id, gymId, ['MEMBER']);
|
||
await createMembership(p.user.id, gymId, ['MEMBER']);
|
||
trainer = {
|
||
id: t.user.id,
|
||
email: t.user.email,
|
||
token: (await loginViaApi(t.user.email, PASSWORD)).token,
|
||
};
|
||
trainee = {
|
||
id: tr.user.id,
|
||
email: tr.user.email,
|
||
token: (await loginViaApi(tr.user.email, PASSWORD)).token,
|
||
};
|
||
plain = {
|
||
id: p.user.id,
|
||
email: p.user.email,
|
||
token: (await loginViaApi(p.user.email, PASSWORD)).token,
|
||
};
|
||
});
|
||
|
||
describe('authorization', () => {
|
||
it('rejects /trainer/trainees for a user without the TRAINER role with 403', async () => {
|
||
const res = await app
|
||
.get('/api/v1/trainer/trainees')
|
||
.set('Authorization', `Bearer ${plain.token}`);
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('rejects /trainer/search for a user without the TRAINER role with 403', async () => {
|
||
const res = await app
|
||
.get('/api/v1/trainer/search?firstName=Anna&lastName=X')
|
||
.set('Authorization', `Bearer ${plain.token}`);
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('rejects /trainer/trainees without a token with 401', async () => {
|
||
const res = await app.get('/api/v1/trainer/trainees');
|
||
expect(res.status).toBe(401);
|
||
});
|
||
});
|
||
|
||
describe('invitations', () => {
|
||
it('sends an invitation (trainer -> trainee) as PENDING', async () => {
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ userId: trainee.id });
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.coaching).toMatchObject({
|
||
trainerId: trainer.id,
|
||
userId: trainee.id,
|
||
invitedBy: trainer.id,
|
||
status: 'PENDING',
|
||
});
|
||
expect(res.body.coaching.expiresAt).toBeTruthy();
|
||
});
|
||
|
||
it('rejects a duplicate invitation with 409', async () => {
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ userId: trainee.id });
|
||
expect(res.status).toBe(409);
|
||
});
|
||
|
||
it('rejects a self-invitation with 400', async () => {
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ userId: trainer.id });
|
||
expect(res.status).toBe(400);
|
||
});
|
||
|
||
it('rejects an invitation when neither party is a trainer with 400', async () => {
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${plain.token}`)
|
||
.send({ userId: trainee.id });
|
||
expect(res.status).toBe(400);
|
||
});
|
||
|
||
it('rejects an unknown target with 404', async () => {
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ userId: 'unknown-user' });
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('lists pending invitations for both parties with the right direction', async () => {
|
||
const sent = await app
|
||
.get('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(sent.status).toBe(200);
|
||
const sentItem = sent.body.invitations.find(
|
||
(i: { other: { id: string } }) => i.other.id === trainee.id,
|
||
);
|
||
expect(sentItem).toMatchObject({ direction: 'sent' });
|
||
expect(sentItem.other).toMatchObject({ id: trainee.id, email: trainee.email });
|
||
expect(sentItem.other).toHaveProperty('nickname');
|
||
|
||
const received = await app
|
||
.get('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainee.token}`);
|
||
expect(received.status).toBe(200);
|
||
const receivedItem = received.body.invitations.find(
|
||
(i: { other: { id: string } }) => i.other.id === trainer.id,
|
||
);
|
||
expect(receivedItem).toMatchObject({ direction: 'received' });
|
||
});
|
||
|
||
it('rejects accepting the sender own invitation with 403', async () => {
|
||
const coaching = await prisma.coaching.findUnique({
|
||
where: { trainerId_userId: { trainerId: trainer.id, userId: trainee.id } },
|
||
});
|
||
const res = await app
|
||
.post(`/api/v1/trainer/invitations/${coaching!.id}/accept`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('rejects accept/decline from a user outside the invitation pair with 403', async () => {
|
||
const coaching = await prisma.coaching.findUnique({
|
||
where: { trainerId_userId: { trainerId: trainer.id, userId: trainee.id } },
|
||
});
|
||
const accept = await app
|
||
.post(`/api/v1/trainer/invitations/${coaching!.id}/accept`)
|
||
.set('Authorization', `Bearer ${plain.token}`);
|
||
expect(accept.status).toBe(403);
|
||
const decline = await app
|
||
.post(`/api/v1/trainer/invitations/${coaching!.id}/decline`)
|
||
.set('Authorization', `Bearer ${plain.token}`);
|
||
expect(decline.status).toBe(403);
|
||
});
|
||
|
||
it('the invited party accepts -> ACTIVE', async () => {
|
||
const coaching = await prisma.coaching.findUnique({
|
||
where: { trainerId_userId: { trainerId: trainer.id, userId: trainee.id } },
|
||
});
|
||
const res = await app
|
||
.post(`/api/v1/trainer/invitations/${coaching!.id}/accept`)
|
||
.set('Authorization', `Bearer ${trainee.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.coaching.status).toBe('ACTIVE');
|
||
});
|
||
|
||
it('rejects acting on a non-pending invitation with 409', async () => {
|
||
const coaching = await prisma.coaching.findUnique({
|
||
where: { trainerId_userId: { trainerId: trainer.id, userId: trainee.id } },
|
||
});
|
||
const res = await app
|
||
.post(`/api/v1/trainer/invitations/${coaching!.id}/decline`)
|
||
.set('Authorization', `Bearer ${trainee.token}`);
|
||
expect(res.status).toBe(409);
|
||
});
|
||
|
||
it('rejects an unknown invitation with 404', async () => {
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations/unknown-id/accept')
|
||
.set('Authorization', `Bearer ${trainee.token}`);
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('rejects an expired invitation with 410', async () => {
|
||
const gym2 = await prisma.gym.create({ data: { name: `Expired Gym ${rand()}` } });
|
||
const other = await createUser({ firstName: 'Ewa' });
|
||
await createMembership(other.user.id, gym2.id, ['MEMBER']);
|
||
const otherToken = (await loginViaApi(other.user.email, PASSWORD)).token;
|
||
const expired = await prisma.coaching.create({
|
||
data: {
|
||
trainerId: trainer.id,
|
||
userId: other.user.id,
|
||
invitedBy: trainer.id,
|
||
invitedAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000),
|
||
expiresAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
|
||
},
|
||
});
|
||
const res = await app
|
||
.post(`/api/v1/trainer/invitations/${expired.id}/accept`)
|
||
.set('Authorization', `Bearer ${otherToken}`);
|
||
expect(res.status).toBe(410);
|
||
});
|
||
|
||
it('the sender withdraws a pending invitation (204, relation removed)', async () => {
|
||
const gym2 = await prisma.gym.create({ data: { name: `Withdraw Gym ${rand()}` } });
|
||
const other = await createUser({ firstName: 'Iga' });
|
||
await createMembership(other.user.id, gym2.id, ['MEMBER']);
|
||
const created = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ userId: other.user.id });
|
||
const coachingId = created.body.coaching.id as string;
|
||
const del = await app
|
||
.delete(`/api/v1/trainer/invitations/${coachingId}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(del.status).toBe(204);
|
||
const gone = await prisma.coaching.findUnique({ where: { id: coachingId } });
|
||
expect(gone).toBeNull();
|
||
});
|
||
|
||
it('the invited party cannot withdraw with 403', async () => {
|
||
const gym2 = await prisma.gym.create({ data: { name: `NoWithdraw Gym ${rand()}` } });
|
||
const other = await createUser({ firstName: 'Ola' });
|
||
await createMembership(other.user.id, gym2.id, ['MEMBER']);
|
||
const created = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ userId: other.user.id });
|
||
const coachingId = created.body.coaching.id as string;
|
||
const otherToken = (await loginViaApi(other.user.email, PASSWORD)).token;
|
||
const res = await app
|
||
.delete(`/api/v1/trainer/invitations/${coachingId}`)
|
||
.set('Authorization', `Bearer ${otherToken}`);
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('a trainee inviting a trainer makes the trainer the trainer-side', async () => {
|
||
const gym2 = await prisma.gym.create({ data: { name: `Reverse Gym ${rand()}` } });
|
||
const newTrainer = await createUser({ firstName: 'Marek' });
|
||
await createMembership(newTrainer.user.id, gym2.id, ['TRAINER']);
|
||
const token = (await loginViaApi(newTrainer.user.email, PASSWORD)).token;
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${plain.token}`)
|
||
.send({ userId: newTrainer.user.id });
|
||
expect(res.status).toBe(201);
|
||
expect(res.body.coaching).toMatchObject({
|
||
trainerId: newTrainer.user.id,
|
||
userId: plain.id,
|
||
invitedBy: plain.id,
|
||
});
|
||
});
|
||
|
||
it('enforces the pending invitation limit (10) with 409', async () => {
|
||
const gym2 = await prisma.gym.create({ data: { name: `Limit Gym ${rand()}` } });
|
||
const limited = await createUser({ firstName: 'Limit' });
|
||
await createMembership(limited.user.id, gym2.id, ['MEMBER']);
|
||
for (let i = 0; i < 10; i += 1) {
|
||
const filler = await createUser({ firstName: `Filler${i}` });
|
||
await createMembership(filler.user.id, gym2.id, ['MEMBER']);
|
||
await prisma.coaching.create({
|
||
data: {
|
||
trainerId: limited.user.id,
|
||
userId: filler.user.id,
|
||
invitedBy: limited.user.id,
|
||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||
},
|
||
});
|
||
}
|
||
const res = await app
|
||
.post('/api/v1/trainer/invitations')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ userId: limited.user.id });
|
||
expect(res.status).toBe(409);
|
||
});
|
||
});
|
||
|
||
describe('trainee list and detail', () => {
|
||
it('lists active trainees with metrics (pending relations excluded)', async () => {
|
||
const res = await app
|
||
.get('/api/v1/trainer/trainees')
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const found = res.body.trainees.find(
|
||
(t: { user: { id: string } }) => t.user.id === trainee.id,
|
||
);
|
||
expect(found).toBeTruthy();
|
||
expect(found.user).toMatchObject({ id: trainee.id, firstName: 'Anna' });
|
||
expect(found.gyms.some((g: { id: string }) => g.id === gymId)).toBe(true);
|
||
expect(found.killstreak).toBe(0);
|
||
expect(found.flags).toBeInstanceOf(Array);
|
||
expect(found.activePlan).toBeNull();
|
||
});
|
||
|
||
it('excludes trainees who do not belong to the filtered gym', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees?gymId=${gymId}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const found = res.body.trainees.find(
|
||
(t: { user: { id: string } }) => t.user.id === trainee.id,
|
||
);
|
||
expect(found).toBeTruthy();
|
||
|
||
const otherGym = await prisma.gym.create({ data: { name: `Other Gym ${rand()}` } });
|
||
const filtered = await app
|
||
.get(`/api/v1/trainer/trainees?gymId=${otherGym.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(
|
||
filtered.body.trainees.find((t: { user: { id: string } }) => t.user.id === trainee.id),
|
||
).toBeUndefined();
|
||
});
|
||
|
||
it('returns 404 for a detail of a non-assigned user', async () => {
|
||
const stranger = await createUser({ firstName: 'Obca' });
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${stranger.user.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('returns a restricted detail (training metrics only, no body parameters/profile)', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.user).toMatchObject({ id: trainee.id, firstName: 'Anna' });
|
||
expect(res.body).toHaveProperty('killstreak');
|
||
expect(res.body).toHaveProperty('nextTraining');
|
||
expect(res.body).toHaveProperty('extra');
|
||
expect(res.body).toHaveProperty('missing');
|
||
expect(res.body).toHaveProperty('lastSessionAt');
|
||
expect(res.body).toHaveProperty('flags');
|
||
// coaching relation id — allows messaging the trainee directly from the detail page
|
||
const coaching = await prisma.coaching.findUnique({
|
||
where: { trainerId_userId: { trainerId: trainer.id, userId: trainee.id } },
|
||
});
|
||
expect(res.body.coachingId).toBe(coaching!.id);
|
||
// restricted: no profile/body data leaks
|
||
expect(res.body).not.toHaveProperty('age');
|
||
expect(res.body).not.toHaveProperty('heightCm');
|
||
expect(res.body).not.toHaveProperty('priorities');
|
||
expect(res.body).not.toHaveProperty('weight');
|
||
expect(res.body).not.toHaveProperty('circumferences');
|
||
});
|
||
|
||
it('includes gym equipment in the detail gyms (limits exercises in the plan editor)', async () => {
|
||
const equipment = await prisma.equipment.create({
|
||
data: { name: `Sztanga ${rand()}`, kind: 'BARBELL' },
|
||
});
|
||
await prisma.gymEquipment.create({ data: { gymId, equipmentId: equipment.id, quantity: 2 } });
|
||
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const gym = res.body.gyms.find((g: { id: string }) => g.id === gymId);
|
||
expect(gym).toBeTruthy();
|
||
expect(gym.equipment).toEqual([
|
||
expect.objectContaining({
|
||
equipmentId: equipment.id,
|
||
quantity: 2,
|
||
equipment: expect.objectContaining({ id: equipment.id, kind: 'BARBELL' }),
|
||
}),
|
||
]);
|
||
});
|
||
|
||
it('returns the trainee history with plan vs. actual', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/history`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.sessions).toBeInstanceOf(Array);
|
||
});
|
||
|
||
it('exposes nickname in the trainee list and nickname + socialMedia in the detail', async () => {
|
||
await prisma.user.update({
|
||
where: { id: trainee.id },
|
||
data: {
|
||
nickname: 'annafit',
|
||
socialMedia: [{ platform: 'TIKTOK', url: 'https://tiktok.com/@annafit' }],
|
||
},
|
||
});
|
||
|
||
const list = await app
|
||
.get('/api/v1/trainer/trainees')
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
const found = list.body.trainees.find(
|
||
(t: { user: { id: string } }) => t.user.id === trainee.id,
|
||
);
|
||
expect(found.user).toMatchObject({ id: trainee.id, nickname: 'annafit' });
|
||
|
||
const detail = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(detail.body.user).toMatchObject({ id: trainee.id, nickname: 'annafit' });
|
||
expect(detail.body.socialMedia).toEqual([
|
||
{ platform: 'TIKTOK', url: 'https://tiktok.com/@annafit' },
|
||
]);
|
||
});
|
||
|
||
it('archives the relation and removes the trainee from the list', async () => {
|
||
const res = await app
|
||
.delete(`/api/v1/trainer/trainees/${trainee.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(204);
|
||
const list = await app
|
||
.get('/api/v1/trainer/trainees')
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(
|
||
list.body.trainees.find((t: { user: { id: string } }) => t.user.id === trainee.id),
|
||
).toBeUndefined();
|
||
});
|
||
|
||
it('rejects archiving a non-assigned user with 404', async () => {
|
||
const res = await app
|
||
.delete(`/api/v1/trainer/trainees/${trainee.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(404);
|
||
});
|
||
});
|
||
|
||
describe('search', () => {
|
||
it('finds users by first + last name (case-insensitive, partial)', async () => {
|
||
const target = await createUser({ firstName: 'Szymon', lastName: 'Kowalski' });
|
||
const res = await app
|
||
.get('/api/v1/trainer/search?firstName=szy&lastName=KOWALSKI')
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const found = res.body.users.find((u: { id: string }) => u.id === target.user.id);
|
||
expect(found).toBeTruthy();
|
||
expect(found.email).toBe(target.user.email);
|
||
expect(found).toHaveProperty('phone');
|
||
expect(found).toHaveProperty('nickname');
|
||
expect(found).toHaveProperty('gyms');
|
||
});
|
||
|
||
it('rejects missing query parameters with 400', async () => {
|
||
const res = await app
|
||
.get('/api/v1/trainer/search?firstName=Jan')
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(400);
|
||
});
|
||
});
|
||
|
||
describe('report and moves', () => {
|
||
beforeAll(async () => {
|
||
// the relation was archived by the previous block — re-establish it
|
||
await prisma.coaching.upsert({
|
||
where: { trainerId_userId: { trainerId: trainer.id, userId: trainee.id } },
|
||
update: { status: 'ACTIVE' },
|
||
create: {
|
||
trainerId: trainer.id,
|
||
userId: trainee.id,
|
||
invitedBy: trainer.id,
|
||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||
},
|
||
});
|
||
await prisma.focusArea.upsert({
|
||
where: { muscle: 'chest' },
|
||
update: { setsMin: 10, setsMax: 20 },
|
||
create: { name: 'Klatka piersiowa', muscle: 'chest', setsMin: 10, setsMax: 20 },
|
||
});
|
||
const ex = await createExercise({ name: 'Squat' });
|
||
const seeded = await seedPlan({
|
||
userId: trainee.id,
|
||
title: 'Report Plan',
|
||
status: 'ACTIVE',
|
||
startDate: new Date('2026-08-17T00:00:00Z'),
|
||
weeks: [
|
||
{
|
||
index: 0,
|
||
days: [
|
||
{
|
||
dayOfWeek: 1,
|
||
date: new Date('2026-08-17T00:00:00Z'),
|
||
status: 'COMPLETED',
|
||
exercises: [
|
||
{
|
||
exerciseId: ex.id,
|
||
order: 0,
|
||
sets: [
|
||
{ index: 0, reps: 10, loadKg: 60, restSec: 90 },
|
||
{ index: 1, reps: 10, loadKg: 60, restSec: 90 },
|
||
],
|
||
},
|
||
],
|
||
},
|
||
{ dayOfWeek: 4, date: new Date('2026-08-20T00:00:00Z'), status: 'SKIPPED' },
|
||
],
|
||
},
|
||
],
|
||
});
|
||
const dayId = seeded.weeks[0].days[0].id;
|
||
const [planSet1, planSet2] = seeded.weeks[0].days[0].exercises[0].sets;
|
||
await seedSession(dayId, {
|
||
status: 'COMPLETED',
|
||
exercises: [
|
||
{
|
||
exerciseId: ex.id,
|
||
order: 0,
|
||
sets: [
|
||
{ planSetId: planSet1.id, reps: 10, index: 0 },
|
||
{ planSetId: planSet2.id, reps: 8, index: 1 },
|
||
{ planSetId: null, reps: 5, index: 2 },
|
||
],
|
||
},
|
||
],
|
||
});
|
||
await prisma.dayMove.create({
|
||
data: {
|
||
dayId,
|
||
fromDate: new Date('2026-08-19T00:00:00Z'),
|
||
toDate: new Date('2026-08-20T00:00:00Z'),
|
||
reason: 'choroba',
|
||
},
|
||
});
|
||
});
|
||
|
||
it('returns the plan vs. actual report per muscle group', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/report`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.plan).toMatchObject({ title: 'Report Plan' });
|
||
const chest = res.body.muscles.find((m: { muscle: string }) => m.muscle === 'chest');
|
||
expect(chest.planned).toEqual({ sets: 2, reps: 20 });
|
||
expect(chest.actual).toEqual({ sets: 2, reps: 18 });
|
||
expect(chest.extra).toEqual({ sets: 1 });
|
||
expect(chest.missing).toEqual({ sets: 0 });
|
||
expect(chest.completionPct).toBe(100);
|
||
// weekly range scaled to the plan duration (1 week)
|
||
expect(chest.recommendedRange).toEqual({ setsMin: 10, setsMax: 20 });
|
||
expect(chest.outOfRange).toBe(true); // 2 actual sets < 10 min
|
||
// plan days for the discipline heatmap (moved day flagged)
|
||
expect(res.body.days).toHaveLength(2);
|
||
const [d1, d2] = res.body.days;
|
||
expect(d1.status).toBe('COMPLETED');
|
||
expect(d1.moved).toBe(true);
|
||
expect(d2.status).toBe('SKIPPED');
|
||
expect(d2.moved).toBe(false);
|
||
});
|
||
|
||
it('returns the moved-day log', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/moves`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.moves).toHaveLength(1);
|
||
expect(res.body.moves[0]).toMatchObject({ reason: 'choroba' });
|
||
expect(res.body.moves[0].fromDate).toBe('2026-08-19T00:00:00.000Z');
|
||
expect(res.body.moves[0].toDate).toBe('2026-08-20T00:00:00.000Z');
|
||
});
|
||
|
||
it('returns an empty report for a trainee without an active plan', async () => {
|
||
const stranger = await createUser({ firstName: 'NoPlan' });
|
||
await prisma.coaching.create({
|
||
data: {
|
||
trainerId: trainer.id,
|
||
userId: stranger.user.id,
|
||
invitedBy: trainer.id,
|
||
status: 'ACTIVE',
|
||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||
},
|
||
});
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${stranger.user.id}/report`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.plan).toBeNull();
|
||
expect(res.body.muscles).toEqual([]);
|
||
expect(res.body.days).toEqual([]);
|
||
});
|
||
|
||
it('returns 404 for a non-assigned user', async () => {
|
||
const stranger = await createUser({ firstName: 'NoRel' });
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${stranger.user.id}/report`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(404);
|
||
const moves = await app
|
||
.get(`/api/v1/trainer/trainees/${stranger.user.id}/moves`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(moves.status).toBe(404);
|
||
});
|
||
});
|
||
|
||
describe('phone', () => {
|
||
it('sets phone via PATCH /me and returns it in the profile', async () => {
|
||
const res = await app
|
||
.patch('/api/v1/me')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ phone: '+48 600 100 200' });
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.user.phone).toBe('+48 600 100 200');
|
||
const me = await app.get('/api/v1/me').set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(me.body.user.phone).toBe('+48 600 100 200');
|
||
});
|
||
|
||
it('rejects a duplicate phone with 409', async () => {
|
||
const res = await app
|
||
.patch('/api/v1/me')
|
||
.set('Authorization', `Bearer ${trainee.token}`)
|
||
.send({ phone: '+48 600 100 200' });
|
||
expect(res.status).toBe(409);
|
||
});
|
||
|
||
it('clears phone with null', async () => {
|
||
const res = await app
|
||
.patch('/api/v1/me')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ phone: null });
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.user.phone).toBeNull();
|
||
});
|
||
|
||
it('rejects a too-short phone with 400', async () => {
|
||
const res = await app
|
||
.patch('/api/v1/me')
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ phone: '123' });
|
||
expect(res.status).toBe(400);
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('trainer — managing a trainee plan', () => {
|
||
let app: ReturnType<typeof buildApp>;
|
||
let trainer: { id: string; token: string };
|
||
let trainee: { id: string; token: string };
|
||
let plain: { id: string; token: string };
|
||
let gymId: string;
|
||
let exerciseId: string;
|
||
let planId: string;
|
||
|
||
const planBody = (title: string) => ({
|
||
title,
|
||
weeksCount: 1,
|
||
weeks: [
|
||
{
|
||
index: 0,
|
||
days: [
|
||
{
|
||
dayOfWeek: 1,
|
||
exercises: [
|
||
{ exerciseId, order: 0, sets: [{ index: 0, reps: 10, loadKg: 60, restSec: 90 }] },
|
||
],
|
||
},
|
||
],
|
||
},
|
||
],
|
||
});
|
||
|
||
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')}`;
|
||
}
|
||
|
||
beforeAll(async () => {
|
||
app = buildApp();
|
||
const t = await createUser({ firstName: 'PlanTrainer' });
|
||
const tr = await createUser({ firstName: 'PlanTrainee' });
|
||
const p = await createUser({ firstName: 'PlanPlain' });
|
||
const gym = await prisma.gym.create({ data: { name: `Plan Gym ${rand()}` } });
|
||
gymId = gym.id;
|
||
await createMembership(t.user.id, gymId, ['TRAINER']);
|
||
await createMembership(tr.user.id, gymId, ['MEMBER']);
|
||
await createMembership(p.user.id, gymId, ['MEMBER']);
|
||
trainer = { id: t.user.id, token: (await loginViaApi(t.user.email, PASSWORD)).token };
|
||
trainee = { id: tr.user.id, token: (await loginViaApi(tr.user.email, PASSWORD)).token };
|
||
plain = { id: p.user.id, token: (await loginViaApi(p.user.email, PASSWORD)).token };
|
||
await prisma.coaching.create({
|
||
data: {
|
||
trainerId: trainer.id,
|
||
userId: trainee.id,
|
||
invitedBy: trainer.id,
|
||
status: 'ACTIVE',
|
||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||
},
|
||
});
|
||
const ex = await createExercise({ name: 'PlanSquat' });
|
||
exerciseId = ex.id;
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send(planBody('Plan trenerski'));
|
||
expect(res.status).toBe(201);
|
||
planId = res.body.plan.id;
|
||
});
|
||
|
||
it('creates a plan owned by the trainee with the trainer as creator', async () => {
|
||
const stored = await prisma.trainingPlan.findUnique({ where: { id: planId } });
|
||
expect(stored!.userId).toBe(trainee.id);
|
||
expect(stored!.creatorId).toBe(trainer.id);
|
||
expect(stored!.status).toBe('DRAFT');
|
||
});
|
||
|
||
it('lists the trainee plans with the creator included', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.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.creator).toMatchObject({ id: trainer.id, firstName: 'PlanTrainer' });
|
||
});
|
||
|
||
it('returns the full plan structure', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/plans/${planId}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.plan.weeks).toHaveLength(1);
|
||
expect(res.body.plan.weeks[0].days[0].exercises[0].exercise.id).toBe(exerciseId);
|
||
});
|
||
|
||
it('the owner (trainee) can read and edit the trainer-created draft', async () => {
|
||
const read = await app
|
||
.get(`/api/v1/plans/${planId}`)
|
||
.set('Authorization', `Bearer ${trainee.token}`);
|
||
expect(read.status).toBe(200);
|
||
const patch = await app
|
||
.patch(`/api/v1/plans/${planId}`)
|
||
.set('Authorization', `Bearer ${trainee.token}`)
|
||
.send(planBody('Plan trenerski v2'));
|
||
expect(patch.status).toBe(200);
|
||
expect(patch.body).toMatchObject({ ok: true });
|
||
});
|
||
|
||
it('rejects a user without the TRAINER role with 403', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${plain.token}`);
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('rejects a trainer without an ACTIVE relation to the trainee with 404', async () => {
|
||
const otherTrainer = await createUser({ firstName: 'OtherTrainer' });
|
||
await createMembership(otherTrainer.user.id, gymId, ['TRAINER']);
|
||
const token = (await loginViaApi(otherTrainer.user.email, PASSWORD)).token;
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${token}`);
|
||
expect(res.status).toBe(404);
|
||
});
|
||
|
||
it('rejects activation on a non-Monday date 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
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${planId}/activate`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ startDate: tuesdayIso });
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error.message).toBe('Start date must be a Monday');
|
||
});
|
||
|
||
it('activates the draft on a Monday', async () => {
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${planId}/activate`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ startDate: mondayIso(1) });
|
||
expect(res.status).toBe(200);
|
||
const stored = await prisma.trainingPlan.findUnique({ where: { id: planId } });
|
||
expect(stored!.status).toBe('ACTIVE');
|
||
});
|
||
|
||
it('rejects activating a second plan while one is active with 409', async () => {
|
||
const created = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send(planBody('Second plan'));
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/activate`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ startDate: mondayIso(2) });
|
||
expect(res.status).toBe(409);
|
||
expect(res.body.error.message).toBe('User already has an active plan');
|
||
});
|
||
|
||
it('abandons an active plan', async () => {
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${planId}/abandon`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const stored = await prisma.trainingPlan.findUnique({ where: { id: planId } });
|
||
expect(stored!.status).toBe('ABANDONED');
|
||
});
|
||
|
||
it('rejects completing a draft plan with 400', async () => {
|
||
const created = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send(planBody('Draft complete'));
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/complete`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error.message).toBe('Only an active plan can be completed');
|
||
});
|
||
|
||
it('completes an active plan', async () => {
|
||
// porzucony plan odzwolnił miejsce — nowy szkic da się aktywować
|
||
const created = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send(planBody('To complete'));
|
||
const activated = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/activate`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ startDate: mondayIso(1) });
|
||
expect(activated.status).toBe(200);
|
||
// plan w trakcie realizacji (dni PLANNED) — najpierw odmowa, potem domknięcie dni
|
||
const pending = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/complete`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(pending.status).toBe(400);
|
||
expect(pending.body.error.message).toBe(
|
||
'Plan has pending training days — it can only be abandoned',
|
||
);
|
||
await prisma.planDay.updateMany({
|
||
where: { week: { planId: created.body.plan.id } },
|
||
data: { status: 'COMPLETED' },
|
||
});
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/complete`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
});
|
||
|
||
it('rejects reopening an active plan with 400', async () => {
|
||
const created = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send(planBody('Reopen active'));
|
||
await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/activate`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ startDate: mondayIso(1) });
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/reopen`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(400);
|
||
expect(res.body.error.message).toBe('Only a completed or abandoned plan can be reopened');
|
||
// sprzątanie — zwolnij slot aktywnego planu
|
||
await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/abandon`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
});
|
||
|
||
it('reopens a trainee plan abandoned by the trainer', async () => {
|
||
const created = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send(planBody('Trainer reopen'));
|
||
const id = created.body.plan.id;
|
||
await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/activate`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send({ startDate: mondayIso(1) });
|
||
await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/abandon`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
const res = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/reopen`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const stored = await prisma.trainingPlan.findUnique({ where: { id } });
|
||
expect(stored!.status).toBe('ACTIVE');
|
||
// sprzątanie
|
||
await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${id}/abandon`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
});
|
||
|
||
it('deletes a draft plan', async () => {
|
||
const created = await app
|
||
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
||
.set('Authorization', `Bearer ${trainer.token}`)
|
||
.send(planBody('To delete'));
|
||
const res = await app
|
||
.delete(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(204);
|
||
});
|
||
|
||
it('exercise-latest returns the last session per exercise', async () => {
|
||
const ex = await createExercise({ name: 'LatestSquat' });
|
||
const seeded = await seedPlan({
|
||
userId: trainee.id,
|
||
title: 'Latest Plan',
|
||
status: 'ACTIVE',
|
||
startDate: new Date('2026-08-17T00:00:00Z'),
|
||
weeks: [
|
||
{
|
||
index: 0,
|
||
days: [
|
||
{
|
||
dayOfWeek: 1,
|
||
date: new Date('2026-08-17T00:00:00Z'),
|
||
status: 'COMPLETED',
|
||
exercises: [
|
||
{
|
||
exerciseId: ex.id,
|
||
order: 0,
|
||
sets: [{ index: 0, reps: 10, loadKg: 60, restSec: 90 }],
|
||
},
|
||
],
|
||
},
|
||
],
|
||
},
|
||
],
|
||
});
|
||
const dayId = seeded.weeks[0].days[0].id;
|
||
const [planSet1] = seeded.weeks[0].days[0].exercises[0].sets;
|
||
await seedSession(dayId, {
|
||
status: 'COMPLETED',
|
||
startedAt: new Date('2026-08-17T07:00:00Z'),
|
||
exercises: [
|
||
{ exerciseId: ex.id, order: 0, sets: [{ planSetId: planSet1.id, reps: 10, index: 0 }] },
|
||
],
|
||
});
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/exercise-latest`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const found = res.body.results.find((r: { exerciseId: string }) => r.exerciseId === ex.id);
|
||
expect(found).toBeTruthy();
|
||
expect(found.sets).toEqual([{ reps: 10, loadKg: 60 }]);
|
||
// 60 × (1 + 10/30) = 80
|
||
expect(found.oneRm).toBe(80);
|
||
});
|
||
|
||
it('exercise-latest returns empty for a trainee without sessions', async () => {
|
||
const fresh = await createUser({ firstName: 'NoSession' });
|
||
await prisma.coaching.create({
|
||
data: {
|
||
trainerId: trainer.id,
|
||
userId: fresh.user.id,
|
||
invitedBy: trainer.id,
|
||
status: 'ACTIVE',
|
||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||
},
|
||
});
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${fresh.user.id}/exercise-latest`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.results).toEqual([]);
|
||
});
|
||
});
|
||
|
||
describe('trainer — trainee calendar', () => {
|
||
let app: ReturnType<typeof buildApp>;
|
||
let trainer: { id: string; token: string };
|
||
let trainee: { id: string; token: string };
|
||
let plain: { id: string; token: string };
|
||
|
||
beforeAll(async () => {
|
||
app = buildApp();
|
||
const t = await createUser({ firstName: 'CalTrainer' });
|
||
const tr = await createUser({ firstName: 'CalTrainee' });
|
||
const p = await createUser({ firstName: 'CalPlain' });
|
||
const gym = await prisma.gym.create({ data: { name: `Cal Gym ${rand()}` } });
|
||
await createMembership(t.user.id, gym.id, ['TRAINER']);
|
||
await createMembership(tr.user.id, gym.id, ['MEMBER']);
|
||
await createMembership(p.user.id, gym.id, ['MEMBER']);
|
||
trainer = { id: t.user.id, token: (await loginViaApi(t.user.email, PASSWORD)).token };
|
||
trainee = { id: tr.user.id, token: (await loginViaApi(tr.user.email, PASSWORD)).token };
|
||
plain = { id: p.user.id, token: (await loginViaApi(p.user.email, PASSWORD)).token };
|
||
await prisma.coaching.create({
|
||
data: {
|
||
trainerId: trainer.id,
|
||
userId: trainee.id,
|
||
invitedBy: trainer.id,
|
||
status: 'ACTIVE',
|
||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||
},
|
||
});
|
||
const ex = await createExercise({ name: 'CalSquat' });
|
||
await seedPlan({
|
||
userId: trainee.id,
|
||
title: 'Calendar Plan',
|
||
status: 'ACTIVE',
|
||
startDate: new Date('2026-08-17T00:00:00Z'),
|
||
weeks: [
|
||
{
|
||
index: 0,
|
||
days: [
|
||
{
|
||
dayOfWeek: 1,
|
||
date: new Date('2026-08-17T00:00:00Z'),
|
||
status: 'COMPLETED',
|
||
exercises: [{ exerciseId: ex.id, order: 0, sets: [{ index: 0, reps: 10 }] }],
|
||
},
|
||
{ dayOfWeek: 4, date: new Date('2026-08-20T00:00:00Z'), status: 'PLANNED' },
|
||
],
|
||
},
|
||
],
|
||
});
|
||
});
|
||
|
||
it('returns the trainee training days of the requested month', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/calendar?month=2026-08`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.month).toBe('2026-08');
|
||
expect(res.body.days).toHaveLength(2);
|
||
expect(res.body.days[0]).toMatchObject({ status: 'COMPLETED', dayOfWeek: 1 });
|
||
expect(res.body.days[0].exercises).toEqual([{ name: 'CalSquat', muscle: 'chest' }]);
|
||
expect(res.body.days[1]).toMatchObject({ status: 'PLANNED', dayOfWeek: 4 });
|
||
});
|
||
|
||
it('returns an empty month when the trainee has no training days there', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/calendar?month=2026-09`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
expect(res.body.month).toBe('2026-09');
|
||
expect(res.body.days).toEqual([]);
|
||
});
|
||
|
||
it('defaults to the current month when month is omitted', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/calendar`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(200);
|
||
const now = new Date();
|
||
expect(res.body.month).toBe(
|
||
`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`,
|
||
);
|
||
});
|
||
|
||
it('rejects an invalid month format with 400', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/calendar?month=2026-13`)
|
||
.set('Authorization', `Bearer ${trainer.token}`);
|
||
expect(res.status).toBe(400);
|
||
});
|
||
|
||
it('rejects a user without the TRAINER role with 403', async () => {
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/calendar?month=2026-08`)
|
||
.set('Authorization', `Bearer ${plain.token}`);
|
||
expect(res.status).toBe(403);
|
||
});
|
||
|
||
it('rejects a trainer without an ACTIVE relation to the trainee with 404', async () => {
|
||
const otherTrainer = await createUser({ firstName: 'CalOtherTrainer' });
|
||
const gym2 = await prisma.gym.create({ data: { name: `CalOther Gym ${rand()}` } });
|
||
await createMembership(otherTrainer.user.id, gym2.id, ['TRAINER']);
|
||
const token = (await loginViaApi(otherTrainer.user.email, PASSWORD)).token;
|
||
const res = await app
|
||
.get(`/api/v1/trainer/trainees/${trainee.id}/calendar?month=2026-08`)
|
||
.set('Authorization', `Bearer ${token}`);
|
||
expect(res.status).toBe(404);
|
||
});
|
||
});
|