Plany i sesje: porzucenie/konczenie tylko z ACTIVE, przyszle dni bez skip, usuwanie tylko cwiczen dodanych do sesji

This commit is contained in:
tisachi
2026-10-11 16:34:47 +02:00
parent 42798939a5
commit cfac9dadd0
10 changed files with 415 additions and 86 deletions

View File

@@ -387,8 +387,8 @@ async function applyStartDate(
export async function abandonPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status === 'COMPLETED' || plan.status === 'ABANDONED')
throw badRequest('Plan is already closed');
// Tylko aktywny plan można porzucić — DRAFT kończy się przez edycję/usunięcie.
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be abandoned');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'ABANDONED' },
@@ -398,8 +398,8 @@ export async function abandonPlan(prisma: PrismaClient, planId: string, userId:
export async function completePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status === 'COMPLETED' || plan.status === 'ABANDONED')
throw badRequest('Plan is already closed');
// Tylko aktywny plan można ukończyć — DRAFT nie zaczął się jeszcze realizować.
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be completed');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'COMPLETED' },

View File

@@ -42,9 +42,15 @@ export function startScheduler(prisma: PrismaClient): void {
data: { status: 'ABANDONED', endedAt: now },
});
// Porzucona sesja nie może pozwalać na ponowne wykonanie dnia —
// dokładnie tak samo jak przy ręcznym porzuceniu sesji.
// dokładnie tak samo jak przy ręcznym porzuceniu sesji. Dni z przyszłą
// datą zostają PLANNED (sesja startowana wczoraj nie skreśla jutra).
const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
await prisma.planDay.updateMany({
where: { id: { in: [...new Set(stale.map((s) => s.dayId))] }, status: 'PLANNED' },
where: {
id: { in: [...new Set(stale.map((s) => s.dayId))] },
status: 'PLANNED',
date: { lt: startOfTomorrow },
},
data: { status: 'SKIPPED', skippedAt: now },
});
logger.info({ count: stale.length }, 'Auto-abandoned sessions (24h)');

View File

@@ -200,6 +200,11 @@ export async function updateExercise(
) {
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
if (exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
// Ćwiczenie z planu można ukryć, ale nie usunąć — usuwanie nie może „wybaczać"
// nieodpisanych serii planowych; kasować wolno tylko ćwiczenia dodane do sesji.
if (data.removed === true && exercise.planExerciseId != null) {
throw badRequest('Only exercises added to the session can be removed');
}
await prisma.sessionExercise.update({
where: { id: exercise.id },
data,
@@ -322,6 +327,9 @@ export async function abandonSession(prisma: PrismaClient, sessionId: string, us
const session = await getSessionOwned(prisma, sessionId, userId);
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
const now = new Date();
// Dzień w przyszłości nie zostaje „skipnięty" przez porzuconą sesję — wraca do
// PLANNED i da się go wykonać normalnie; SKIPPED tylko dla dni, które nadszedł czas.
const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
await prisma.$transaction(async (tx) => {
const s = await tx.trainingSession.updateMany({
where: { id: session.id, status: 'IN_PROGRESS' },
@@ -331,7 +339,7 @@ export async function abandonSession(prisma: PrismaClient, sessionId: string, us
// Dzień oznaczamy jako pominięty tylko gdy wciąż jest zaplanowany
// (mógł już wygasnąć w schedulerze — wtedy nie nadpisujemy).
await tx.planDay.updateMany({
where: { id: session.dayId, status: 'PLANNED' },
where: { id: session.dayId, status: 'PLANNED', date: { lt: startOfTomorrow } },
data: { status: 'SKIPPED', skippedAt: now },
});
});

View File

@@ -610,17 +610,27 @@ export const openapi: Record<string, unknown> = {
'/plans/{id}/abandon': {
post: {
tags: ['Plans'],
summary: 'Abandon plan',
summary: 'Abandon plan (only from ACTIVE status)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
200: { description: 'OK' },
400: { description: 'Only an active plan can be abandoned' },
404: { description: 'Plan not found' },
},
},
},
'/plans/{id}/complete': {
post: {
tags: ['Plans'],
summary: 'Manually archive plan',
summary: 'Manually archive plan (only from ACTIVE status)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
200: { description: 'OK' },
400: { description: 'Only an active plan can be completed' },
404: { description: 'Plan not found' },
},
},
},
'/plans/{id}/share': {
@@ -670,9 +680,16 @@ export const openapi: Record<string, unknown> = {
'/days/{dayId}/sessions': {
post: {
tags: ['Sessions'],
summary: 'Start session for a planned day (one active session per user)',
summary:
'Start session for a planned day (requires ACTIVE plan, one active session per user)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'dayId', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
201: { description: 'Session started' },
400: { description: 'Training plan is not active / Day is not in planned state' },
404: { description: 'Day not found' },
409: { description: 'You already have an active session' },
},
},
},
'/sessions/{id}': {
@@ -706,7 +723,8 @@ export const openapi: Record<string, unknown> = {
'/sessions/exercises/{id}': {
patch: {
tags: ['Sessions'],
summary: 'Hide or remove exercise (data kept for restore)',
summary:
'Hide or remove exercise (data kept for restore); removing allowed only for exercises added to the session',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
@@ -719,6 +737,11 @@ export const openapi: Record<string, unknown> = {
},
},
},
responses: {
200: { description: 'OK' },
400: { description: 'Only exercises added to the session can be removed' },
404: { description: 'Session exercise not found' },
},
},
},
'/sessions/exercises/{id}/sets': {

View File

@@ -337,16 +337,47 @@ describe('plans routes', () => {
.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');
expect(again.body.error.message).toBe('Only an active plan can be abandoned');
});
it('completes a draft plan and refuses to close it twice', async () => {
it('rejects abandoning a draft plan with 400', async () => {
const app = buildApp();
const created = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send(planBody('Draft abandon'));
const res = await app
.post(`/api/v1/plans/${created.body.plan.id}/abandon`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Only an active plan can be abandoned');
});
it('rejects completing a draft plan with 400', async () => {
const app = buildApp();
const created = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send(planBody('Draft complete'));
const res = await app
.post(`/api/v1/plans/${created.body.plan.id}/complete`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Only an active plan can be completed');
});
it('completes an active plan and refuses to close it twice', async () => {
const app = buildApp();
const created = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send(planBody('To complete'));
const id = created.body.plan.id;
const activated = await app
.post(`/api/v1/plans/${id}/activate`)
.set('Authorization', `Bearer ${token}`)
.send({ startDate: MONDAY });
expect(activated.status).toBe(200);
const res = await app
.post(`/api/v1/plans/${id}/complete`)
.set('Authorization', `Bearer ${token}`);

View File

@@ -1,5 +1,14 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { buildApp, createUser, createExercise, loginViaApi, registerViaApi, seedPlan, seedSession, PASSWORD } from '../helpers.js';
import {
buildApp,
createUser,
createExercise,
loginViaApi,
registerViaApi,
seedPlan,
seedSession,
PASSWORD,
} from '../helpers.js';
describe('sessions routes', () => {
let token: string;
@@ -53,12 +62,16 @@ describe('sessions routes', () => {
it('starts a session for a planned day and initializes exercises + sets from the plan', async () => {
const app = buildApp();
const res = await app.post(`/api/v1/days/${dayId}/sessions`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/days/${dayId}/sessions`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(201);
const sessionId = res.body.sessionId;
expect(sessionId).toBeTruthy();
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
expect(detail.status).toBe(200);
const session = detail.body.session;
expect(session.status).toBe('IN_PROGRESS');
@@ -66,7 +79,9 @@ describe('sessions routes', () => {
const ex = session.exercises[0];
expect(ex.planExerciseId).toBe(planExerciseId);
expect(ex.sets).toHaveLength(2);
expect(ex.sets.map((s: { planSetId: string }) => s.planSetId).sort()).toEqual([...planSetIds].sort());
expect(ex.sets.map((s: { planSetId: string }) => s.planSetId).sort()).toEqual(
[...planSetIds].sort(),
);
expect(ex.sets.every((s: { reps: number | null }) => s.reps === null)).toBe(true);
});
@@ -89,14 +104,18 @@ describe('sessions routes', () => {
it('rejects a second active session for the same day with 409', async () => {
const app = buildApp();
const res = await app.post(`/api/v1/days/${dayId}/sessions`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/days/${dayId}/sessions`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(409);
expect(res.body.error.message).toBe('You already have an active session');
});
it('rejects starting another day while a session is active with 409', async () => {
const app = buildApp();
const res = await app.post(`/api/v1/days/${day2Id}/sessions`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/days/${day2Id}/sessions`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(409);
expect(res.body.error.message).toBe('You already have an active session');
});
@@ -118,7 +137,9 @@ describe('sessions routes', () => {
it('returns a null active session for a user without sessions', async () => {
const app = buildApp();
const res = await app.get('/api/v1/me/active-session').set('Authorization', `Bearer ${otherToken}`);
const res = await app
.get('/api/v1/me/active-session')
.set('Authorization', `Bearer ${otherToken}`);
expect(res.status).toBe(200);
expect(res.body.session).toBeNull();
});
@@ -177,8 +198,12 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const addedExercise = detail.body.session.exercises.find((e: { planExerciseId: string | null }) => !e.planExerciseId);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const addedExercise = detail.body.session.exercises.find(
(e: { planExerciseId: string | null }) => !e.planExerciseId,
);
const hide = await app
.patch(`/api/v1/sessions/exercises/${addedExercise.id}`)
@@ -193,34 +218,69 @@ describe('sessions routes', () => {
expect(remove.status).toBe(200);
});
it('rejects removing a planned (from-plan) exercise with 400 — only hidden is allowed', async () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const planned = detail.body.session.exercises.find(
(e: { planExerciseId: string | null }) => e.planExerciseId,
);
const remove = await app
.patch(`/api/v1/sessions/exercises/${planned.id}`)
.set('Authorization', `Bearer ${token}`)
.send({ removed: true });
expect(remove.status).toBe(400);
expect(remove.body.error.message).toBe('Only exercises added to the session can be removed');
const hide = await app
.patch(`/api/v1/sessions/exercises/${planned.id}`)
.set('Authorization', `Bearer ${token}`)
.send({ hidden: true });
expect(hide.status).toBe(200);
});
it('rejects adding an extra set before the norm is done with 400', async () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const ex = detail.body.session.exercises[0];
const res = await app
.post(`/api/v1/sessions/exercises/${ex.id}/sets`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('All planned sets must be recorded before adding an extra set');
expect(res.body.error.message).toBe(
'All planned sets must be recorded before adding an extra set',
);
});
it('rejects completing the session while norm sets are pending with 400', async () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const res = await app.post(`/api/v1/sessions/${sessionId}/complete`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/sessions/${sessionId}/complete`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('All planned sets must be recorded before completing the session (2 remaining)');
expect(res.body.error.message).toBe(
'All planned sets must be recorded before completing the session (2 remaining)',
);
});
it('records the norm sets and adds an extra set once the norm is done', async () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const ex = detail.body.session.exercises[0];
for (const set of ex.sets) {
@@ -244,7 +304,9 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const ex = detail.body.session.exercises[0];
const res = await app
@@ -258,7 +320,9 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const ex = detail.body.session.exercises[0];
const extra = ex.sets.find((s: { planSetId: string | null }) => s.planSetId == null);
expect(extra).toBeTruthy();
@@ -270,7 +334,9 @@ describe('sessions routes', () => {
expect(res.body).toEqual({ ok: true });
// the removed set no longer appears in the session detail
const after = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const after = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const afterEx = after.body.session.exercises[0];
expect(afterEx.sets.some((s: { id: string }) => s.id === extra.id)).toBe(false);
});
@@ -279,7 +345,9 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const ex = detail.body.session.exercises[0];
const norm = ex.sets.find((s: { planSetId: string | null }) => s.planSetId != null);
@@ -294,7 +362,9 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const set = detail.body.session.exercises[0].sets[0];
const res = await app
@@ -309,7 +379,9 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const set = detail.body.session.exercises[0].sets[0];
const res = await app
.patch(`/api/v1/sessions/sets/${set.id}`)
@@ -322,7 +394,9 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const detail = await app.get(`/api/v1/sessions/${sessionId}`).set('Authorization', `Bearer ${token}`);
const detail = await app
.get(`/api/v1/sessions/${sessionId}`)
.set('Authorization', `Bearer ${token}`);
const set = detail.body.session.exercises[0].sets[0];
const res = await app
.patch(`/api/v1/sessions/sets/${set.id}`)
@@ -336,7 +410,9 @@ describe('sessions routes', () => {
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const res = await app.post(`/api/v1/sessions/${sessionId}/complete`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/sessions/${sessionId}/complete`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
const day = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
@@ -347,24 +423,32 @@ describe('sessions routes', () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);
const sessionId = session.body.day.sessions[0].id;
const res = await app.post(`/api/v1/sessions/${sessionId}/complete`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/sessions/${sessionId}/complete`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
it('rejects starting a session on a non-planned day with 400', async () => {
const app = buildApp();
const res = await app.post(`/api/v1/days/${dayId}/sessions`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/days/${dayId}/sessions`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Day is not in planned state');
});
it('abandons a session and marks the day skipped', async () => {
const app = buildApp();
const start = await app.post(`/api/v1/days/${day2Id}/sessions`).set('Authorization', `Bearer ${token}`);
const start = await app
.post(`/api/v1/days/${day2Id}/sessions`)
.set('Authorization', `Bearer ${token}`);
expect(start.status).toBe(201);
const sessionId = start.body.sessionId;
const res = await app.post(`/api/v1/sessions/${sessionId}/abandon`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/sessions/${sessionId}/abandon`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
const day = await app.get(`/api/v1/days/${day2Id}`).set('Authorization', `Bearer ${token}`);
@@ -374,7 +458,9 @@ describe('sessions routes', () => {
it('rejects starting a new session on a day with an abandoned session with 400', async () => {
const app = buildApp();
const res = await app.post(`/api/v1/days/${day2Id}/sessions`).set('Authorization', `Bearer ${token}`);
const res = await app
.post(`/api/v1/days/${day2Id}/sessions`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Day is not in planned state');
});

View File

@@ -1,6 +1,15 @@
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';
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({
@@ -44,7 +53,9 @@ describe('trainer — invitations and trainees', () => {
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}`);
const res = await app
.get('/api/v1/trainer/trainees')
.set('Authorization', `Bearer ${plain.token}`);
expect(res.status).toBe(403);
});
@@ -110,14 +121,20 @@ describe('trainer — invitations and trainees', () => {
});
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}`);
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);
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}`);
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,
@@ -273,9 +290,13 @@ describe('trainer — invitations and trainees', () => {
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}`);
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);
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);
@@ -289,14 +310,18 @@ describe('trainer — invitations and trainees', () => {
.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);
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();
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 () => {
@@ -333,7 +358,9 @@ describe('trainer — invitations and trainees', () => {
});
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' } });
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
@@ -368,15 +395,21 @@ describe('trainer — invitations and trainees', () => {
},
});
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);
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' }]);
expect(detail.body.socialMedia).toEqual([
{ platform: 'TIKTOK', url: 'https://tiktok.com/@annafit' },
]);
});
it('archives the relation and removes the trainee from the list', async () => {
@@ -384,8 +417,12 @@ describe('trainer — invitations and trainees', () => {
.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();
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 () => {
@@ -618,7 +655,9 @@ describe('trainer — managing a trainee plan', () => {
days: [
{
dayOfWeek: 1,
exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10, loadKg: 60, restSec: 90 }] }],
exercises: [
{ exerciseId, order: 0, sets: [{ index: 0, reps: 10, loadKg: 60, restSec: 90 }] },
],
},
],
},
@@ -690,7 +729,9 @@ describe('trainer — managing a trainee plan', () => {
});
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}`);
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}`)
@@ -763,11 +804,29 @@ describe('trainer — managing a trainee plan', () => {
expect(stored!.status).toBe('ABANDONED');
});
it('completes a draft plan', async () => {
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);
const res = await app
.post(`/api/v1/trainer/trainees/${trainee.id}/plans/${created.body.plan.id}/complete`)
.set('Authorization', `Bearer ${trainer.token}`);
@@ -801,7 +860,11 @@ describe('trainer — managing a trainee plan', () => {
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 }] },
{
exerciseId: ex.id,
order: 0,
sets: [{ index: 0, reps: 10, loadKg: 60, restSec: 90 }],
},
],
},
],
@@ -813,7 +876,9 @@ describe('trainer — managing a trainee plan', () => {
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 }] }],
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`)
@@ -922,7 +987,9 @@ describe('trainer — trainee 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')}`);
expect(res.body.month).toBe(
`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`,
);
});
it('rejects an invalid month format with 400', async () => {

View File

@@ -54,7 +54,10 @@ describe('scheduler', () => {
});
it('auto-abandons in-progress sessions older than 24h and skips their days', async () => {
sessionFindMany.mockResolvedValue([{ id: 's1', dayId: 'd1' }, { id: 's2', dayId: 'd2' }]);
sessionFindMany.mockResolvedValue([
{ id: 's1', dayId: 'd1' },
{ id: 's2', dayId: 'd2' },
]);
await tickOnce();
const cutoff = new Date(NOW.getTime() - 24 * 60 * 60 * 1000);
expect(sessionFindMany).toHaveBeenCalledWith({
@@ -65,9 +68,14 @@ describe('scheduler', () => {
where: { id: { in: ['s1', 's2'] } },
data: { status: 'ABANDONED', endedAt: expect.any(Date) },
});
// dzień porzuconej sesji nie może zostać ponownie wykonany (jak przy ręcznym abandon)
// dzień porzuconej sesji nie może zostać ponownie wykonany (jak przy ręcznym abandon),
// ale dni z przyszłą datą zostają PLANNED — stąd filtr po dacie
expect(planDayUpdateMany).toHaveBeenLastCalledWith({
where: { id: { in: ['d1', 'd2'] }, status: 'PLANNED' },
where: {
id: { in: ['d1', 'd2'] },
status: 'PLANNED',
date: { lt: new Date(2026, 7, 23) },
},
data: { status: 'SKIPPED', skippedAt: expect.any(Date) },
});
});

View File

@@ -21,7 +21,7 @@ function mockPrisma() {
trainingPlan: { update: vi.fn(), findFirst: vi.fn() },
planDay: { update: vi.fn() },
};
const prisma = {
const prisma = {
trainingPlan: {
findUnique: vi.fn(),
findFirst: vi.fn(),
@@ -93,7 +93,16 @@ describe('draft-only rules', () => {
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ABANDONED' });
await expect(abandonPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Plan is already closed',
message: 'Only an active plan can be abandoned',
});
});
it('abandonPlan: rejects a draft plan with 400', async () => {
const { prisma } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
await expect(abandonPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Only an active plan can be abandoned',
});
});
@@ -102,7 +111,16 @@ describe('draft-only rules', () => {
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });
await expect(completePlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Plan is already closed',
message: 'Only an active plan can be completed',
});
});
it('completePlan: rejects a draft plan with 400', async () => {
const { prisma } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
await expect(completePlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Only an active plan can be completed',
});
});
});
@@ -195,7 +213,13 @@ describe('activatePlan', () => {
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
prisma.trainingPlan.findFirst.mockResolvedValue(null);
prisma.planWeek.findMany.mockResolvedValue([
{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }, { id: 'd2', dayOfWeek: 3 }] },
{
index: 0,
days: [
{ id: 'd1', dayOfWeek: 1 },
{ id: 'd2', dayOfWeek: 3 },
],
},
{ index: 1, days: [{ id: 'd3', dayOfWeek: 1 }] },
]);
tx.trainingPlan.findFirst.mockResolvedValue(null);
@@ -432,9 +456,7 @@ describe('updatePlan (startDate = aktualizacja + aktywacja)', () => {
const { prisma, tx } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
prisma.exercise.findMany.mockResolvedValue([]);
prisma.planWeek.findMany.mockResolvedValue([
{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }] },
]);
prisma.planWeek.findMany.mockResolvedValue([{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }] }]);
tx.trainingPlan.update.mockResolvedValue({});
tx.planDay.update.mockResolvedValue({});
@@ -492,9 +514,7 @@ describe('updatePlan (startDate = aktualizacja + aktywacja)', () => {
const { prisma, tx } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
prisma.exercise.findMany.mockResolvedValue([]);
prisma.planWeek.findMany.mockResolvedValue([
{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }] },
]);
prisma.planWeek.findMany.mockResolvedValue([{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }] }]);
tx.trainingPlan.update.mockResolvedValue({});
// W transakcji aktywacji właściciel ma już aktywny plan → konflikt.
tx.trainingPlan.findFirst.mockResolvedValue({ id: 'other-active' });
@@ -617,7 +637,7 @@ describe('unsharePlan', () => {
});
});
it('brak share\'a: 404', async () => {
it("brak share'a: 404", async () => {
const { prisma } = mockPrisma();
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
prisma.planShare.deleteMany.mockResolvedValue({ count: 0 });

View File

@@ -1,5 +1,14 @@
import { describe, it, expect, vi } from 'vitest';
import { abandonSession, addExercise, addSet, completeSession, deleteSet, getActiveSession, startSession } from '../../src/services/sessions.js';
import {
abandonSession,
addExercise,
addSet,
completeSession,
deleteSet,
getActiveSession,
startSession,
updateExercise,
} from '../../src/services/sessions.js';
function mockPrisma() {
const prisma: any = {
@@ -181,7 +190,10 @@ describe('completeSession', () => {
it('400 when the session is not in progress', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue({ ...ownedInProgress, status: 'COMPLETED' });
prisma.trainingSession.findUnique.mockResolvedValue({
...ownedInProgress,
status: 'COMPLETED',
});
await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Session is not in progress',
@@ -200,7 +212,11 @@ describe('completeSession', () => {
{ id: 'st2', planSetId: 'ps2', reps: null, removed: false },
],
},
{ id: 'se2', removed: false, sets: [{ id: 'st3', planSetId: 'ps3', reps: null, removed: false }] },
{
id: 'se2',
removed: false,
sets: [{ id: 'st3', planSetId: 'ps3', reps: null, removed: false }],
},
]);
await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 400,
@@ -241,7 +257,11 @@ describe('completeSession', () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress);
prisma.sessionExercise.findMany.mockResolvedValue([
{ id: 'se1', removed: false, sets: [{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false }] },
{
id: 'se1',
removed: false,
sets: [{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false }],
},
]);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
// dzień wygasł w schedulerze (SKIPPED) — warunkowe updateMany nic nie trafia
@@ -257,7 +277,11 @@ describe('completeSession', () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress);
prisma.sessionExercise.findMany.mockResolvedValue([
{ id: 'se1', removed: false, sets: [{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false }] },
{
id: 'se1',
removed: false,
sets: [{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false }],
},
]);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 0 });
@@ -297,7 +321,10 @@ describe('abandonSession', () => {
it('400 when the session is not in progress', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue({ ...ownedInProgress, status: 'ABANDONED' });
prisma.trainingSession.findUnique.mockResolvedValue({
...ownedInProgress,
status: 'ABANDONED',
});
await expect(abandonSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Session is not in progress',
@@ -319,10 +346,10 @@ describe('abandonSession', () => {
data: expect.objectContaining({ status: 'ABANDONED' }),
}),
);
// dzień oznaczany tylko gdy wciąż PLANNED (nie nadpisuje wygasłego)
// dzień oznaczany tylko gdy wciąż PLANNED i już nadszedł jego czas (przyszły zostaje PLANNED)
expect(prisma.planDay.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: 'd1', status: 'PLANNED' },
where: { id: 'd1', status: 'PLANNED', date: { lt: expect.any(Date) } },
data: expect.objectContaining({ status: 'SKIPPED' }),
}),
);
@@ -338,6 +365,52 @@ describe('abandonSession', () => {
});
});
describe('updateExercise', () => {
it('400 when removing an exercise that comes from the plan', async () => {
const prisma = mockPrisma();
prisma.sessionExercise.findUnique.mockResolvedValue({
id: 'se1',
planExerciseId: 'pe1',
session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'u1' } } } },
});
await expect(updateExercise(prisma, 'se1', 'u1', { removed: true })).rejects.toMatchObject({
status: 400,
message: 'Only exercises added to the session can be removed',
});
expect(prisma.sessionExercise.update).not.toHaveBeenCalled();
});
it('allows removing an exercise added to the session', async () => {
const prisma = mockPrisma();
prisma.sessionExercise.findUnique.mockResolvedValue({
id: 'se1',
planExerciseId: null,
session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'u1' } } } },
});
prisma.sessionExercise.update.mockResolvedValue({ id: 'se1' });
await expect(updateExercise(prisma, 'se1', 'u1', { removed: true })).resolves.toEqual({
ok: true,
});
expect(prisma.sessionExercise.update).toHaveBeenCalledWith({
where: { id: 'se1' },
data: { removed: true },
});
});
it('allows hiding a planned exercise (hidden does not exempt planned sets)', async () => {
const prisma = mockPrisma();
prisma.sessionExercise.findUnique.mockResolvedValue({
id: 'se1',
planExerciseId: 'pe1',
session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'u1' } } } },
});
prisma.sessionExercise.update.mockResolvedValue({ id: 'se1' });
await expect(updateExercise(prisma, 'se1', 'u1', { hidden: true })).resolves.toEqual({
ok: true,
});
});
});
describe('addSet', () => {
const ownedExercise = {
id: 'se1',
@@ -422,7 +495,9 @@ describe('deleteSet', () => {
const prisma = mockPrisma();
prisma.sessionSet.findUnique.mockResolvedValue({
...ownedSet,
exercise: { session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'other' } } } } },
exercise: {
session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'other' } } } },
},
});
await expect(deleteSet(prisma, 'st1', 'u1')).rejects.toMatchObject({
status: 404,
@@ -443,7 +518,9 @@ describe('deleteSet', () => {
const prisma = mockPrisma();
prisma.sessionSet.findUnique.mockResolvedValue({
...ownedSet,
exercise: { session: { id: 's1', status: 'COMPLETED', day: { week: { plan: { userId: 'u1' } } } } },
exercise: {
session: { id: 's1', status: 'COMPLETED', day: { week: { plan: { userId: 'u1' } } } },
},
});
await expect(deleteSet(prisma, 'st1', 'u1')).rejects.toMatchObject({
status: 400,
@@ -459,7 +536,10 @@ describe('deleteSet', () => {
const result = await deleteSet(prisma, 'st1', 'u1');
expect(result).toEqual({ ok: true });
expect(prisma.sessionSet.update).toHaveBeenCalledWith({ where: { id: 'st1' }, data: { removed: true } });
expect(prisma.sessionSet.update).toHaveBeenCalledWith({
where: { id: 'st1' },
data: { removed: true },
});
});
});