630 lines
28 KiB
TypeScript
630 lines
28 KiB
TypeScript
import { describe, it, expect, beforeAll } from 'vitest';
|
|
import { prisma } from '../../src/lib/prisma.js';
|
|
import {
|
|
buildApp,
|
|
createExercise,
|
|
createUser,
|
|
createUserWithToken,
|
|
loginViaApi,
|
|
rand,
|
|
seedPlan,
|
|
seedSession,
|
|
PASSWORD,
|
|
} from '../helpers.js';
|
|
|
|
/** Poniedziałek bieżącego tygodnia 00:00 czasu lokalnego. */
|
|
function mondayThisWeek(): Date {
|
|
const now = new Date();
|
|
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - ((now.getDay() + 6) % 7));
|
|
}
|
|
|
|
function localDate(daysFromMondayThisWeek: number): Date {
|
|
const d = mondayThisWeek();
|
|
d.setDate(d.getDate() + daysFromMondayThisWeek);
|
|
return d;
|
|
}
|
|
|
|
const daysAgo = (n: number) => localDate(-n);
|
|
const daysAhead = (n: number) => localDate(n);
|
|
|
|
describe('plan templates (kind=TEMPLATE)', () => {
|
|
let app: ReturnType<typeof buildApp>;
|
|
let owner: { id: string; token: string };
|
|
let stranger: { id: string; token: string };
|
|
let trainer: { id: string; token: string };
|
|
let trainee: { id: string; token: string };
|
|
let exerciseId: string;
|
|
let gymId: string;
|
|
|
|
beforeAll(async () => {
|
|
app = buildApp();
|
|
const o = await createUserWithToken({ firstName: 'Ola', lastName: 'Właściciel' });
|
|
const s = await createUserWithToken({ firstName: 'Stefan', lastName: 'Obcy' });
|
|
const t = await createUser({ firstName: 'Tomasz', lastName: 'Trener' });
|
|
const tr = await createUser({ firstName: 'Anna', lastName: 'Podopieczna' });
|
|
owner = { id: o.user.id, token: o.token };
|
|
stranger = { id: s.user.id, token: s.token };
|
|
const gym = await prisma.gym.create({ data: { name: `Templates Gym ${rand()}` } });
|
|
gymId = gym.id;
|
|
await prisma.gymMembership.create({ data: { userId: t.user.id, gymId, roles: ['TRAINER'] } });
|
|
await prisma.gymMembership.create({ data: { userId: tr.user.id, gymId, roles: ['MEMBER'] } });
|
|
await prisma.coaching.create({
|
|
data: {
|
|
trainerId: t.user.id,
|
|
userId: tr.user.id,
|
|
status: 'ACTIVE',
|
|
invitedBy: t.user.id,
|
|
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
|
},
|
|
});
|
|
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 };
|
|
exerciseId = (await createExercise()).id;
|
|
});
|
|
|
|
const templateBody = (title: string) => ({
|
|
title,
|
|
kind: 'TEMPLATE',
|
|
weeksCount: 2,
|
|
weeks: [
|
|
{
|
|
index: 0,
|
|
customName: 'Baza',
|
|
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 },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
{ 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, cardioBpm: 140, timeSec: 600, speed: 7.5 }] },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
],
|
|
});
|
|
|
|
async function createTemplateViaApi(token: string, title: string) {
|
|
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(templateBody(title));
|
|
expect(res.status).toBe(201);
|
|
return res.body.plan as { id: string; kind: string; status: string };
|
|
}
|
|
|
|
describe('creation', () => {
|
|
it('creates a TEMPLATE (status DRAFT, no start date) with kind returned', async () => {
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon ${rand()}`);
|
|
expect(tpl.kind).toBe('TEMPLATE');
|
|
expect(tpl.status).toBe('DRAFT');
|
|
});
|
|
|
|
it('rejects startDate for templates with 400', async () => {
|
|
const body = { ...templateBody(`Szablon start ${rand()}`), startDate: '2030-01-07' };
|
|
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${owner.token}`).send(body);
|
|
expect(res.status).toBe(400);
|
|
});
|
|
|
|
it('excludes templates from GET /plans', async () => {
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon listy ${rand()}`);
|
|
const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${owner.token}`);
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false);
|
|
});
|
|
|
|
it('lists templates in GET /plans/templates with counters and usedCount', async () => {
|
|
const title = `Szablon licznik ${rand()}`;
|
|
const tpl = await createTemplateViaApi(owner.token, title);
|
|
const res = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${owner.token}`);
|
|
expect(res.status).toBe(200);
|
|
const row = res.body.templates.find((t: { id: string }) => t.id === tpl.id);
|
|
expect(row).toMatchObject({ title, weeksCount: 2, daysCount: 3, exercisesCount: 3, usedCount: 0 });
|
|
});
|
|
|
|
it('templates library is private to the author', async () => {
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon prywatny ${rand()}`);
|
|
const res = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${stranger.token}`);
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.templates.some((t: { id: string }) => t.id === tpl.id)).toBe(false);
|
|
const detail = await app.get(`/api/v1/plans/templates/${tpl.id}`).set('Authorization', `Bearer ${stranger.token}`);
|
|
expect(detail.status).toBe(404);
|
|
});
|
|
|
|
it('hides templates behind GET /plans/:id for non-authors (even the trainee trainer)', async () => {
|
|
const tpl = await createTemplateViaApi(trainee.token, `Szablon podopiecznej ${rand()}`);
|
|
const asTrainer = await app
|
|
.get(`/api/v1/plans/${tpl.id}`)
|
|
.set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(asTrainer.status).toBe(404);
|
|
const asStranger = await app.get(`/api/v1/plans/${tpl.id}`).set('Authorization', `Bearer ${stranger.token}`);
|
|
expect(asStranger.status).toBe(404);
|
|
});
|
|
|
|
it('replaces the full template structure on PATCH without startDate/gym', async () => {
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon edycja ${rand()}`);
|
|
const edited = templateBody(`Szablon edycja v2 ${rand()}`);
|
|
edited.weeks[1].days = [];
|
|
const res = await app
|
|
.patch(`/api/v1/plans/${tpl.id}`)
|
|
.set('Authorization', `Bearer ${owner.token}`)
|
|
.send({ ...edited, title: edited.title });
|
|
expect(res.status).toBe(200);
|
|
const detail = await app.get(`/api/v1/plans/${tpl.id}`).set('Authorization', `Bearer ${owner.token}`);
|
|
expect(detail.status).toBe(200);
|
|
expect(detail.body.plan.title).toBe(edited.title);
|
|
expect(detail.body.plan.weeks[1].days).toHaveLength(0);
|
|
const withStart = await app
|
|
.patch(`/api/v1/plans/${tpl.id}`)
|
|
.set('Authorization', `Bearer ${owner.token}`)
|
|
.send({ ...edited, startDate: '2030-01-07' });
|
|
expect(withStart.status).toBe(400);
|
|
});
|
|
});
|
|
|
|
describe('lifecycle guards (TEMPLATE_NOT_PLAN)', () => {
|
|
let tplId: string;
|
|
beforeAll(async () => {
|
|
tplId = (await createTemplateViaApi(owner.token, `Szablon blokady ${rand()}`)).id;
|
|
});
|
|
|
|
const blocked = (path: string, send?: unknown) =>
|
|
app.post(`/api/v1/plans/${tplId}/${path}`).set('Authorization', `Bearer ${owner.token}`).send(send ?? {});
|
|
|
|
it('blocks activate with code TEMPLATE_NOT_PLAN', async () => {
|
|
const res = await blocked('activate', { startDate: '2030-01-07' });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN');
|
|
});
|
|
|
|
it('blocks abandon/complete/suspend', async () => {
|
|
for (const action of ['abandon', 'complete', 'suspend']) {
|
|
const res = await blocked(action);
|
|
expect(res.status, action).toBe(400);
|
|
expect(res.body.error.code, action).toBe('TEMPLATE_NOT_PLAN');
|
|
}
|
|
});
|
|
|
|
it('blocks share of a template', async () => {
|
|
const res = await blocked('share', { userId: trainee.id });
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN');
|
|
});
|
|
|
|
it('GET /plans/:id/volume rejects templates', async () => {
|
|
const res = await app.get(`/api/v1/plans/${tplId}/volume`).set('Authorization', `Bearer ${owner.token}`);
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN');
|
|
});
|
|
});
|
|
|
|
describe('clone (use template for myself)', () => {
|
|
it('clones 1:1 into a new DRAFT plan with sourceTemplateId and bumps usedCount', async () => {
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon klon ${rand()}`);
|
|
const res = await app.post(`/api/v1/plans/${tpl.id}/clone`).set('Authorization', `Bearer ${owner.token}`);
|
|
expect(res.status).toBe(201);
|
|
expect(res.body.plan).toMatchObject({ kind: 'PLAN', status: 'DRAFT', sourceTemplateId: tpl.id });
|
|
|
|
const detail = await app.get(`/api/v1/plans/${res.body.plan.id}`).set('Authorization', `Bearer ${owner.token}`);
|
|
expect(detail.status).toBe(200);
|
|
const src = await app.get(`/api/v1/plans/templates/${tpl.id}`).set('Authorization', `Bearer ${owner.token}`);
|
|
const srcWeeks = src.body.plan.weeks;
|
|
const cloneWeeks = detail.body.plan.weeks;
|
|
expect(cloneWeeks.map((w: { index: number; customName: string | null }) => [w.index, w.customName]))
|
|
.toEqual(srcWeeks.map((w: { index: number; customName: string | null }) => [w.index, w.customName]));
|
|
const flattenDays = (weeks: { days: { dayOfWeek: number; date: string | null; exercises: unknown[] }[] }[]) =>
|
|
weeks.flatMap((w) => w.days.map((d) => ({ dayOfWeek: d.dayOfWeek, date: d.date, n: d.exercises.length })));
|
|
expect(flattenDays(cloneWeeks)).toEqual(
|
|
flattenDays(srcWeeks).map((d) => ({ ...d, date: null })),
|
|
);
|
|
const cloneSet = cloneWeeks[0].days[0].exercises[0].sets[0];
|
|
expect(cloneSet).toMatchObject({ reps: 10, loadKg: 60, restSec: 90, rir: 2 });
|
|
const cardioSet = cloneWeeks[1].days[0].exercises[0].sets[0];
|
|
expect(cardioSet).toMatchObject({ cardioBpm: 140, timeSec: 600, speed: 7.5 });
|
|
|
|
const tplRes = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${owner.token}`);
|
|
expect(tplRes.body.templates.find((t: { id: string }) => t.id === tpl.id).usedCount).toBe(1);
|
|
});
|
|
|
|
it('rejects cloning a non-template with TEMPLATE_NOT_PLAN', async () => {
|
|
const planRes = await app
|
|
.post('/api/v1/plans')
|
|
.set('Authorization', `Bearer ${owner.token}`)
|
|
.send({ title: `Zwykly ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 5 }] }] }] }] });
|
|
const res = await app.post(`/api/v1/plans/${planRes.body.plan.id}/clone`).set('Authorization', `Bearer ${owner.token}`);
|
|
expect(res.status).toBe(400);
|
|
expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN');
|
|
});
|
|
|
|
it('rejects cloning another user template with 403 and missing with 404', async () => {
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon obcy ${rand()}`);
|
|
const res = await app.post(`/api/v1/plans/${tpl.id}/clone`).set('Authorization', `Bearer ${stranger.token}`);
|
|
expect(res.status).toBe(403);
|
|
const missing = await app.post('/api/v1/plans/no-such-template/clone').set('Authorization', `Bearer ${stranger.token}`);
|
|
expect(missing.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
describe('save plan as template (owner or creator)', () => {
|
|
it('owner saves own plan as template', async () => {
|
|
const planRes = await app
|
|
.post('/api/v1/plans')
|
|
.set('Authorization', `Bearer ${trainee.token}`)
|
|
.send({ title: `Plan Oli ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 5 }] }] }] }] });
|
|
const res = await app
|
|
.post(`/api/v1/plans/${planRes.body.plan.id}/as-template`)
|
|
.set('Authorization', `Bearer ${trainee.token}`);
|
|
expect(res.status).toBe(201);
|
|
expect(res.body.plan.kind).toBe('TEMPLATE');
|
|
});
|
|
|
|
it('trainer (creator) saves their trainee plan into their own library', async () => {
|
|
const created = await app
|
|
.post(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
|
.set('Authorization', `Bearer ${trainer.token}`)
|
|
.send({ title: `Plan trenera ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 2, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 6 }] }] }] }] });
|
|
expect(created.status).toBe(201);
|
|
const res = await app
|
|
.post(`/api/v1/plans/${created.body.plan.id}/as-template`)
|
|
.set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(res.status).toBe(201);
|
|
const tpl = res.body.plan;
|
|
const lib = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(lib.body.templates.some((t: { id: string }) => t.id === tpl.id)).toBe(true);
|
|
// szablon należy do trenera, nie do podopiecznej
|
|
const traineeLib = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${trainee.token}`);
|
|
expect(traineeLib.body.templates.some((t: { id: string }) => t.id === tpl.id)).toBe(false);
|
|
});
|
|
|
|
it('rejects a stranger with 403 and a template source with TEMPLATE_NOT_PLAN', async () => {
|
|
const planRes = await app
|
|
.post('/api/v1/plans')
|
|
.set('Authorization', `Bearer ${owner.token}`)
|
|
.send({ title: `Plan blokady ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 5 }] }] }] }] });
|
|
const forbiddenRes = await app
|
|
.post(`/api/v1/plans/${planRes.body.plan.id}/as-template`)
|
|
.set('Authorization', `Bearer ${stranger.token}`);
|
|
expect(forbiddenRes.status).toBe(403);
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon ponowny ${rand()}`);
|
|
const again = await app
|
|
.post(`/api/v1/plans/${tpl.id}/as-template`)
|
|
.set('Authorization', `Bearer ${owner.token}`);
|
|
expect(again.status).toBe(400);
|
|
expect(again.body.error.code).toBe('TEMPLATE_NOT_PLAN');
|
|
});
|
|
});
|
|
|
|
describe('from-template for trainee (trainer flow)', () => {
|
|
it('clones the trainer template as a trainee-owned DRAFT plan with notification', async () => {
|
|
const tplRes = await app
|
|
.post('/api/v1/plans')
|
|
.set('Authorization', `Bearer ${trainer.token}`)
|
|
.send(templateBody(`Szablon trenera ${rand()}`));
|
|
const tplId = tplRes.body.plan.id;
|
|
const res = await app
|
|
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/from-template/${tplId}`)
|
|
.set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(res.status).toBe(201);
|
|
const planId = res.body.plan.id;
|
|
const row = await prisma.trainingPlan.findUnique({ where: { id: planId } });
|
|
expect(row).toMatchObject({ userId: trainee.id, creatorId: trainer.id, kind: 'PLAN', status: 'DRAFT', sourceTemplateId: tplId });
|
|
const notif = await prisma.notification.findFirst({
|
|
where: {
|
|
userId: trainee.id,
|
|
type: 'PLAN_READY',
|
|
payload: { path: ['planId'], equals: planId },
|
|
},
|
|
});
|
|
expect(notif).toBeTruthy();
|
|
const traineeList = await app.get('/api/v1/plans').set('Authorization', `Bearer ${trainee.token}`);
|
|
expect(traineeList.body.plans.some((p: { id: string }) => p.id === planId)).toBe(true);
|
|
});
|
|
|
|
it('rejects templates not owned by the trainer with 403', async () => {
|
|
const tpl = await createTemplateViaApi(owner.token, `Szablon nie mój ${rand()}`);
|
|
const res = await app
|
|
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/from-template/${tpl.id}`)
|
|
.set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(res.status).toBe(403);
|
|
});
|
|
|
|
it('excludes templates from the trainee plan list (trainer route)', async () => {
|
|
const tpl = await seedTemplateDirect(trainee.id, `Szablon seed ${rand()}`);
|
|
const res = await app
|
|
.get(`/api/v1/trainer/trainees/${trainee.id}/plans`)
|
|
.set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('template usage list (derived visibility)', () => {
|
|
it('shows only own and active-trainee derivations; usedCount is the total', async () => {
|
|
const tpl = await seedTemplateDirect(trainer.id, `Szablon uzycia ${rand()}`);
|
|
// własne pochodne
|
|
const ownDerived = await seedDerivedPlan(trainer.id, tpl.id);
|
|
// podopieczny w ACTIVE coaching
|
|
const traineeDerived = await seedDerivedPlan(trainee.id, tpl.id);
|
|
// obcy — widoczność zablokowana, licznik pełny
|
|
const strangerDerived = await seedDerivedPlan(stranger.id, tpl.id);
|
|
|
|
const res = await app
|
|
.get(`/api/v1/plans/templates/${tpl.id}`)
|
|
.set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(res.status).toBe(200);
|
|
expect(res.body.usedCount).toBe(3);
|
|
const ids = res.body.derived.map((d: { id: string }) => d.id);
|
|
expect(ids).toContain(ownDerived.id);
|
|
expect(ids).toContain(traineeDerived.id);
|
|
expect(ids).not.toContain(strangerDerived.id);
|
|
const traineeRow = res.body.derived.find((d: { id: string }) => d.id === traineeDerived.id);
|
|
expect(traineeRow).toMatchObject({ ownerId: trainee.id, status: 'DRAFT' });
|
|
expect(traineeRow.ownerName).toContain('Anna');
|
|
// struktura szablonu zwracana w pełnym kształcie
|
|
expect(res.body.plan.weeks.length).toBeGreaterThan(0);
|
|
});
|
|
});
|
|
|
|
describe('exclusions from stats/dashboard/shares', () => {
|
|
it('templates do not count in dashboard completed plans or user stats', async () => {
|
|
const statsUser = await createUserWithToken();
|
|
const before = await app.get('/api/v1/me/stats').set('Authorization', `Bearer ${statsUser.token}`);
|
|
await seedPlan({ userId: statsUser.user.id, status: 'COMPLETED' });
|
|
// szablon w stanie COMPLETED (normalnie niemożliwy — sprawdzamy filtr kind)
|
|
const tpl = await seedTemplateDirect(statsUser.user.id, `Szablon COMPLETED ${rand()}`, 'COMPLETED');
|
|
const after = await app.get('/api/v1/me/stats').set('Authorization', `Bearer ${statsUser.token}`);
|
|
expect(after.body.plans.completed).toBe(before.body.plans.completed + 1);
|
|
const dash = await app.get('/api/v1/dashboard').set('Authorization', `Bearer ${statsUser.token}`);
|
|
expect(dash.body.history.completedPlans).toBe(1);
|
|
expect(dash.body.activePlan).toBeNull();
|
|
await prisma.trainingPlan.delete({ where: { id: tpl.id } });
|
|
});
|
|
|
|
it('share of a template (seeded legacy row) stays out of shared-with-me and shared-by-me', async () => {
|
|
const tpl = await seedTemplateDirect(owner.id, `Szablon share ${rand()}`);
|
|
await prisma.planShare.create({ data: { planId: tpl.id, sharedById: owner.id, sharedWithId: trainee.id } });
|
|
const withMe = await app.get('/api/v1/plans/shared-with-me').set('Authorization', `Bearer ${trainee.token}`);
|
|
expect(withMe.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false);
|
|
const byMe = await app.get('/api/v1/plans/shared-by-me').set('Authorization', `Bearer ${owner.token}`);
|
|
expect(byMe.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false);
|
|
});
|
|
|
|
it('shared-by-me lists plans shared by the user with recipients', async () => {
|
|
const plan = await seedPlan({ userId: owner.id, title: `Plan shared ${rand()}` });
|
|
await prisma.planShare.create({ data: { planId: plan.id, sharedById: owner.id, sharedWithId: trainee.id } });
|
|
const res = await app.get('/api/v1/plans/shared-by-me').set('Authorization', `Bearer ${owner.token}`);
|
|
expect(res.status).toBe(200);
|
|
const row = res.body.plans.find((p: { id: string }) => p.id === plan.id);
|
|
expect(row).toBeTruthy();
|
|
expect(row.sharedWith).toMatchObject({ id: trainee.id });
|
|
});
|
|
});
|
|
|
|
describe('GET /plans/:id/volume (shared core with trainee report)', () => {
|
|
it('returns the same per-muscle numbers as the trainer report', async () => {
|
|
// Dedykowana partia i fokus — bez kolizji z równoległymi plikami testów.
|
|
const muscle = `vol-muscle-${rand()}`;
|
|
const volExercise = await createExercise();
|
|
await prisma.exercise.update({ where: { id: volExercise.id }, data: { primaryMuscle: muscle } });
|
|
await prisma.focusArea.create({
|
|
data: { name: `Focus ${rand()}`, muscle, description: null, setsMin: 8, setsMax: 20 },
|
|
});
|
|
const volUser = await createUser({ firstName: 'Wiktoria' });
|
|
const volToken = (await loginViaApi(volUser.user.email, PASSWORD)).token;
|
|
const active = await seedPlan({
|
|
userId: volUser.user.id,
|
|
status: 'ACTIVE',
|
|
startDate: mondayThisWeek(),
|
|
weeks: [
|
|
{
|
|
index: 0,
|
|
days: [
|
|
{
|
|
dayOfWeek: 1,
|
|
status: 'COMPLETED',
|
|
date: localDate(0),
|
|
exercises: [
|
|
{ exerciseId: volExercise.id, order: 0, sets: [{ index: 0, reps: 10 }, { index: 1, reps: 8 }, { index: 2, reps: 8 }] },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
{ index: 1, days: [{ dayOfWeek: 1, status: 'PLANNED', date: localDate(7) }] },
|
|
],
|
|
});
|
|
const day = active.weeks[0].days[0];
|
|
const planEx = day.exercises[0];
|
|
await seedSession(day.id, {
|
|
status: 'COMPLETED',
|
|
exercises: [
|
|
{
|
|
exerciseId: volExercise.id,
|
|
planExerciseId: planEx.id,
|
|
order: 0,
|
|
sets: [
|
|
{ planSetId: planEx.sets[0].id, reps: 10 },
|
|
{ planSetId: planEx.sets[1].id, reps: 8 },
|
|
{ planSetId: null, reps: 6 },
|
|
],
|
|
},
|
|
],
|
|
});
|
|
// wykonanie części planu + seria ponad plan — porównanie obu tras
|
|
await prisma.coaching.create({
|
|
data: {
|
|
trainerId: trainer.id,
|
|
userId: volUser.user.id,
|
|
status: 'ACTIVE',
|
|
invitedBy: trainer.id,
|
|
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
|
},
|
|
});
|
|
const report = await app
|
|
.get(`/api/v1/trainer/trainees/${volUser.user.id}/report`)
|
|
.set('Authorization', `Bearer ${trainer.token}`);
|
|
expect(report.status).toBe(200);
|
|
const volume = await app
|
|
.get(`/api/v1/plans/${active.id}/volume`)
|
|
.set('Authorization', `Bearer ${volToken}`);
|
|
expect(volume.status).toBe(200);
|
|
expect(volume.body.plan).toMatchObject({ id: active.id });
|
|
expect(volume.body.muscles).toEqual(report.body.muscles);
|
|
const chest = volume.body.muscles.find((m: { muscle: string }) => m.muscle === muscle);
|
|
expect(chest.planned.sets).toBe(3);
|
|
expect(chest.actual.sets).toBe(2);
|
|
expect(chest.extra.sets).toBe(1);
|
|
// zakres tygodniowy przeskalowany do 2 tygodni planu
|
|
expect(chest.recommendedRange).toEqual({ setsMin: 16, setsMax: 40 });
|
|
});
|
|
|
|
it('volume is owner-only', async () => {
|
|
const plan = await seedPlan({ userId: owner.id, title: `Plan volume ${rand()}` });
|
|
const res = await app.get(`/api/v1/plans/${plan.id}/volume`).set('Authorization', `Bearer ${stranger.token}`);
|
|
expect(res.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
describe('listPlans hero fields (currentWeek / nextDay)', () => {
|
|
it('nextDay = first PLANNED day today or later; currentWeek = nearest unresolved dated day', async () => {
|
|
const heroUser = await createUserWithToken();
|
|
const today = new Date();
|
|
today.setHours(0, 0, 0, 0);
|
|
const at = (offsetDays: number) => {
|
|
const d = new Date(today);
|
|
d.setDate(d.getDate() + offsetDays);
|
|
return d;
|
|
};
|
|
await seedPlan({
|
|
userId: heroUser.user.id,
|
|
status: 'ACTIVE',
|
|
startDate: at(-2),
|
|
weeks: [
|
|
{
|
|
index: 0,
|
|
days: [
|
|
{ dayOfWeek: 1, status: 'COMPLETED', date: at(-2) },
|
|
{ dayOfWeek: 3, status: 'PLANNED', date: at(1), exercises: [{ exerciseId, order: 0 }] },
|
|
],
|
|
},
|
|
{
|
|
index: 1,
|
|
days: [{ dayOfWeek: 1, status: 'PLANNED', date: at(8), exercises: [{ exerciseId, order: 0 }, { exerciseId, order: 1 }] }],
|
|
},
|
|
],
|
|
});
|
|
const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${heroUser.token}`);
|
|
const plan = res.body.plans[0];
|
|
expect(plan.currentWeek).toBe(0);
|
|
expect(plan.nextDay).toBeTruthy();
|
|
expect(new Date(plan.nextDay.date).getTime()).toBe(at(1).getTime());
|
|
expect(plan.nextDay.dayOfWeek).toBe(3);
|
|
expect(plan.nextDay.exerciseCount).toBe(1);
|
|
});
|
|
|
|
it('PLANNED today counts as nextDay', async () => {
|
|
const todayUser = await createUserWithToken();
|
|
const today = new Date();
|
|
today.setHours(0, 0, 0, 0);
|
|
await seedPlan({
|
|
userId: todayUser.user.id,
|
|
status: 'ACTIVE',
|
|
startDate: today,
|
|
weeks: [{ index: 0, days: [{ dayOfWeek: 1, status: 'PLANNED', date: today }] }],
|
|
});
|
|
const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${todayUser.token}`);
|
|
const plan = res.body.plans[0];
|
|
expect(plan.currentWeek).toBe(0);
|
|
expect(new Date(plan.nextDay.date).getTime()).toBe(today.getTime());
|
|
});
|
|
|
|
it('all days resolved -> currentWeek null, nextDay null', async () => {
|
|
const doneUser = await createUserWithToken();
|
|
await seedPlan({
|
|
userId: doneUser.user.id,
|
|
status: 'ACTIVE',
|
|
startDate: daysAgo(21),
|
|
weeks: [
|
|
{
|
|
index: 0,
|
|
days: [
|
|
{ dayOfWeek: 1, status: 'COMPLETED', date: daysAgo(21) },
|
|
{ dayOfWeek: 3, status: 'SKIPPED', date: daysAgo(19) },
|
|
],
|
|
},
|
|
],
|
|
});
|
|
const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${doneUser.token}`);
|
|
expect(res.body.plans[0]).toMatchObject({ currentWeek: null, nextDay: null });
|
|
});
|
|
|
|
it('draft without dated days -> null/null', async () => {
|
|
const draftUser = await createUserWithToken();
|
|
await seedPlan({ userId: draftUser.user.id, weeks: [{ index: 0, days: [{ dayOfWeek: 1 }] }] });
|
|
const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${draftUser.token}`);
|
|
expect(res.body.plans[0]).toMatchObject({ currentWeek: null, nextDay: null });
|
|
});
|
|
});
|
|
});
|
|
|
|
async function seedTemplateDirect(userId: string, title: string, status?: 'DRAFT' | 'COMPLETED') {
|
|
const exercise = await createExercise();
|
|
return prisma.trainingPlan.create({
|
|
data: {
|
|
title,
|
|
userId,
|
|
creatorId: userId,
|
|
status: status ?? 'DRAFT',
|
|
kind: 'TEMPLATE',
|
|
weeksCount: 1,
|
|
weeks: {
|
|
create: [
|
|
{
|
|
index: 0,
|
|
days: {
|
|
create: [
|
|
{
|
|
dayOfWeek: 1,
|
|
exercises: {
|
|
create: [
|
|
{ exerciseId: exercise.id, order: 0, sets: { create: [{ index: 0, reps: 8 }] } },
|
|
],
|
|
},
|
|
},
|
|
],
|
|
},
|
|
},
|
|
],
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
async function seedDerivedPlan(userId: string, templateId: string) {
|
|
return prisma.trainingPlan.create({
|
|
data: {
|
|
title: `Pochodna ${rand()}`,
|
|
userId,
|
|
creatorId: userId,
|
|
status: 'DRAFT',
|
|
kind: 'PLAN',
|
|
sourceTemplateId: templateId,
|
|
weeksCount: 1,
|
|
weeks: { create: [{ index: 0, days: { create: [{ dayOfWeek: 1 }] } }] },
|
|
},
|
|
});
|
|
}
|