Files
FitOS/api/test/unit/services-sessions.test.ts

839 lines
29 KiB
TypeScript

import { describe, it, expect, vi } from 'vitest';
import {
abandonSession,
addExercise,
addSet,
completeSession,
deleteSet,
getActiveSession,
reopenSession,
startSession,
updateExercise,
} from '../../src/services/sessions.js';
function mockPrisma() {
const prisma: any = {
planDay: { findUnique: vi.fn(), findMany: vi.fn(), update: vi.fn(), updateMany: vi.fn() },
trainingPlan: { findMany: vi.fn() },
trainingSession: {
findUnique: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
},
sessionExercise: {
findUnique: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
createMany: vi.fn(),
update: vi.fn(),
aggregate: vi.fn(),
},
sessionSet: {
findUnique: vi.fn(),
findMany: vi.fn(),
count: vi.fn(),
create: vi.fn(),
createMany: vi.fn(),
update: vi.fn(),
aggregate: vi.fn(),
},
exercise: { findUnique: vi.fn() },
$executeRaw: vi.fn().mockResolvedValue(1),
$transaction: vi.fn(),
};
// transakcja interaktywna: callback dostaje ten sam obiekt (tx === prisma w mocku)
prisma.$transaction.mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) =>
cb(prisma),
);
return prisma;
}
/** Wiersz sesji widoczny dla blokady SELECT ... FOR UPDATE w inSessionTransaction. */
function mockSessionRow(prisma: any, status: 'IN_PROGRESS' | 'COMPLETED' | 'ABANDONED') {
prisma.trainingSession.findUnique.mockResolvedValue({ id: 's1', status });
}
const ownedDay = {
id: 'd1',
status: 'PLANNED',
week: { planId: 'p1', plan: { userId: 'u1', status: 'ACTIVE', title: 'Plan A' } },
exercises: [
{ id: 'pe1', exerciseId: 'pz1', order: 0, sets: [{ id: 'ps1', index: 0 }] },
{ id: 'pe2', exerciseId: 'pz2', order: 1, sets: [] },
],
};
describe('startSession', () => {
it('404 when the day belongs to another user', async () => {
const prisma = mockPrisma();
prisma.planDay.findUnique.mockResolvedValue({
...ownedDay,
week: { plan: { userId: 'other' } },
});
await expect(startSession(prisma, 'd1', 'u1')).rejects.toMatchObject({
status: 404,
message: 'Day not found',
});
});
it('400 when the day is not in planned state', async () => {
const prisma = mockPrisma();
prisma.planDay.findUnique.mockResolvedValue({ ...ownedDay, status: 'COMPLETED' });
await expect(startSession(prisma, 'd1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Day is not in planned state',
});
});
it('400 when the plan behind the day is not ACTIVE', async () => {
const prisma = mockPrisma();
prisma.planDay.findUnique.mockResolvedValue({
...ownedDay,
week: { plan: { userId: 'u1', status: 'DRAFT' } },
});
await expect(startSession(prisma, 'd1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Training plan is not active',
});
});
it('409 when the user already has an active session', async () => {
const prisma = mockPrisma();
prisma.planDay.findUnique.mockResolvedValue(ownedDay);
prisma.trainingSession.findFirst.mockResolvedValue({ id: 's-active' });
await expect(startSession(prisma, 'd1', 'u1')).rejects.toMatchObject({
status: 409,
message: 'You already have an active session',
});
});
it('creates a session with exercises and planned sets in one transaction', async () => {
const prisma = mockPrisma();
prisma.planDay.findUnique.mockResolvedValue(ownedDay);
prisma.trainingSession.findFirst.mockResolvedValue(null);
prisma.trainingSession.create.mockResolvedValue({ id: 's1', status: 'IN_PROGRESS' });
const result = await startSession(prisma, 'd1', 'u1');
expect(result).toEqual({
sessionId: 's1',
status: 'IN_PROGRESS',
dayId: 'd1',
planId: 'p1',
planTitle: 'Plan A',
});
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
// blokada doradcza per użytkownik serializuje równoległe starty
expect(prisma.$executeRaw).toHaveBeenCalled();
// całe drzewo (ćwiczenia + serie) tworzone jednym zagnieżdżonym create
expect(prisma.trainingSession.create).toHaveBeenCalledWith({
data: {
dayId: 'd1',
exercises: {
create: [
{
exerciseId: 'pz1',
planExerciseId: 'pe1',
order: 0,
sets: { create: [{ planSetId: 'ps1', index: 0 }] },
},
{ exerciseId: 'pz2', planExerciseId: 'pe2', order: 1, sets: { create: [] } },
],
},
},
select: { id: true, status: true },
});
});
it('409 when a concurrent start won the race (second in-transaction check)', async () => {
const prisma = mockPrisma();
prisma.planDay.findUnique.mockResolvedValue(ownedDay);
// wyścig: szybka ścieżka przechodzi, sprawdzienie w transakcji już widzi aktywną sesję
prisma.trainingSession.findFirst
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: 's-active' });
await expect(startSession(prisma, 'd1', 'u1')).rejects.toMatchObject({
status: 409,
message: 'You already have an active session',
});
expect(prisma.trainingSession.create).not.toHaveBeenCalled();
});
});
describe('getActiveSession', () => {
it('returns the active session with day and plan context', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findFirst.mockResolvedValue({
id: 's1',
dayId: 'd1',
startedAt: '2026-08-24T07:00:00.000Z',
day: { id: 'd1', date: '2026-08-24', dayOfWeek: 1, week: { plan: { title: 'Plan A' } } },
});
await expect(getActiveSession(prisma, 'u1')).resolves.toEqual({
session: {
id: 's1',
dayId: 'd1',
dayDate: '2026-08-24',
dayOfWeek: 1,
planTitle: 'Plan A',
startedAt: '2026-08-24T07:00:00.000Z',
},
});
expect(prisma.trainingSession.findFirst).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ status: 'IN_PROGRESS' }) }),
);
});
it('returns a null session when none is active', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findFirst.mockResolvedValue(null);
await expect(getActiveSession(prisma, 'u1')).resolves.toEqual({ session: null });
});
});
describe('completeSession', () => {
const ownedInProgress = {
id: 's1',
status: 'IN_PROGRESS',
dayId: 'd1',
day: { week: { planId: 'p1', plan: { userId: 'u1', title: 'Plan A' } } },
};
it('400 when the session is not in progress', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue({
...ownedInProgress,
status: 'COMPLETED',
});
await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Session is not in progress',
});
});
it('400 when some planned (norm) sets are still pending', async () => {
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: 'st2', planSetId: 'ps2', 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,
message: 'All planned sets must be recorded before completing the session (2 remaining)',
});
});
it('400 when an extra (bonus) set is still pending (niechlujny koniec zablokowany)', async () => {
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: 'st2', planSetId: 'ps2', reps: 8, removed: false },
{ id: 'st3', planSetId: null, reps: null, removed: false },
],
},
]);
await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Extra sets must be recorded or removed before completing the session (1 remaining)',
});
expect(prisma.trainingSession.updateMany).not.toHaveBeenCalled();
});
it('completes the session when all norm sets are recorded (bonusy zapisane/usuniete = OK)', async () => {
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: 'st2', planSetId: 'ps2', reps: 8, removed: false },
{ id: 'st3', planSetId: null, reps: 12, removed: false },
{ id: 'st4', planSetId: null, reps: null, removed: true },
],
},
]);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
prisma.planDay.updateMany.mockResolvedValue({ count: 1 });
// bez wiersza endedAt w mocku findUnique — podsumowanie niekrytyczne = null
await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({
ok: true,
summary: null,
dayId: 'd1',
planId: 'p1',
planTitle: 'Plan A',
});
// warunkowe updateMany: sesja tylko IN_PROGRESS, dzień tylko PLANNED
expect(prisma.trainingSession.updateMany).toHaveBeenCalledWith({
where: { id: 's1', status: 'IN_PROGRESS' },
data: { status: 'COMPLETED', endedAt: expect.any(Date) },
});
expect(prisma.planDay.updateMany).toHaveBeenCalledWith({
where: { id: 'd1', status: 'PLANNED' },
data: { status: 'COMPLETED', completedAt: expect.any(Date) },
});
});
it('refuses to revive an expired (skipped) day as completed', async () => {
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 }],
},
]);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
// dzień wygasł w schedulerze (SKIPPED) — warunkowe updateMany nic nie trafia
prisma.planDay.updateMany.mockResolvedValue({ count: 0 });
await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 409,
message: 'Training day is no longer planned',
});
});
it('conflicts when the session was concurrently closed', async () => {
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 }],
},
]);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 0 });
await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 409,
message: 'Session is no longer in progress',
});
});
it('ignores removed sets when counting pending norm sets', async () => {
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: 'st2', planSetId: 'ps2', reps: null, removed: true },
],
},
]);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
prisma.planDay.updateMany.mockResolvedValue({ count: 1 });
await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({
ok: true,
summary: null,
dayId: 'd1',
planId: 'p1',
planTitle: 'Plan A',
});
});
it('buduje podsumowanie celebracyjne: liczby sesji + killstreak z centylem + średnie tonażu', async () => {
const prisma = mockPrisma();
const effDay = (daysAgo: number) => ({
date: new Date(Date.now() - daysAgo * 86_400_000),
status: 'COMPLETED' as const,
sessions: [
{
exercises: [
{
hidden: false,
removed: false,
planExercise: { sets: [{ id: 'ps1' }] },
sets: [{ planSetId: 'ps1', reps: 10 }],
},
],
},
],
});
// findUnique: (1) getSessionOwned, (2) blokada w tx, (3) wiersz do podsumowania
prisma.trainingSession.findUnique
.mockResolvedValueOnce(ownedInProgress)
.mockResolvedValueOnce(ownedInProgress)
.mockResolvedValue({
startedAt: new Date('2026-08-24T07:00:00.000Z'),
endedAt: new Date('2026-08-24T08:10:00.000Z'),
exercises: [
{
removed: false,
sets: [
{ planSetId: 'ps1', reps: 10, planSet: { loadKg: 60 } },
{ planSetId: 'ps2', reps: 8, planSet: { loadKg: 62.5 } },
{ planSetId: null, reps: 12, planSet: null }, // bonus bez obciążenia — poza tonażem
],
},
],
});
prisma.sessionExercise.findMany.mockResolvedValue([
{
id: 'se1',
removed: false,
sets: [
{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false },
{ id: 'st2', planSetId: 'ps2', reps: 8, removed: false },
{ id: 'st3', planSetId: null, reps: 12, removed: false },
],
},
]);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
prisma.planDay.updateMany.mockResolvedValue({ count: 1 });
// planDay.findMany: (1) getKillstreakStats — 2 skuteczne dni u1, (2) getAllKillstreaks — próbka
prisma.planDay.findMany.mockResolvedValueOnce([effDay(2), effDay(1)]).mockResolvedValueOnce([
{ ...effDay(2), week: { plan: { userId: 'u1' } } }, // własny wiersz — wypada z próbki centyla
{ ...effDay(2), week: { plan: { userId: 'u2' } } }, // passa 1 — pobita
{
week: { plan: { userId: 'u3' } },
date: new Date(Date.now() - 86_400_000),
status: 'SKIPPED',
sessions: [],
}, // zero — poza próbką
]);
prisma.trainingPlan.findMany.mockResolvedValue([
{ userId: 'u1' },
{ userId: 'u2' },
{ userId: 'u3' },
]);
// trainingSession.findMany: (1) średnia własna 30 dni, (2) średnia globalna 30 dni
prisma.trainingSession.findMany
.mockResolvedValueOnce([
{
id: 's-old',
exercises: [{ removed: false, sets: [{ planSet: { loadKg: 50 }, reps: 10 }] }],
},
])
.mockResolvedValue(
Array.from({ length: 12 }, (_, i) => ({
id: `g${i}`,
exercises: [{ removed: false, sets: [{ planSet: { loadKg: 100 }, reps: 5 }] }],
})),
);
await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({
ok: true,
summary: {
durationSec: 4200,
exercises: 1,
sets: 3,
bonusSets: 1,
reps: 30,
tonnageKg: 1100,
killstreak: { current: 2, best: 2, newRecord: true, sampleSize: 1, beatCount: 1 },
volume: { ownAvgKg: 500, ownAvgSessions: 1, globalAvgKg: 500, globalSample: 12 },
},
dayId: 'd1',
planId: 'p1',
planTitle: 'Plan A',
});
});
});
describe('abandonSession', () => {
const ownedInProgress = {
id: 's1',
status: 'IN_PROGRESS',
dayId: 'd1',
day: { week: { planId: 'p1', plan: { userId: 'u1', title: 'Plan A' } } },
};
it('400 when the session is not in progress', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue({
...ownedInProgress,
status: 'ABANDONED',
});
await expect(abandonSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Session is not in progress',
});
});
it('abandons the session and marks the day skipped (the training cannot be executed again)', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
prisma.planDay.updateMany.mockResolvedValue({ count: 1 });
const result = await abandonSession(prisma, 's1', 'u1');
expect(result).toEqual({ ok: true, dayId: 'd1', planId: 'p1', planTitle: 'Plan A' });
expect(prisma.trainingSession.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: 's1', status: 'IN_PROGRESS' },
data: expect.objectContaining({ status: 'ABANDONED' }),
}),
);
// 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', date: { lt: expect.any(Date) } },
data: expect.objectContaining({ status: 'SKIPPED' }),
}),
);
});
it('tolerates an already-expired day when abandoning (day guard counts 0 rows)', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
prisma.planDay.updateMany.mockResolvedValue({ count: 0 });
await expect(abandonSession(prisma, 's1', 'u1')).resolves.toEqual({
ok: true,
dayId: 'd1',
planId: 'p1',
planTitle: 'Plan A',
});
});
});
describe('reopenSession', () => {
const ownedCompleted = {
id: 's1',
status: 'COMPLETED',
dayId: 'd1',
day: { week: { planId: 'p1', plan: { userId: 'u1', title: 'Plan A' } } },
};
it('400 when the session is not completed', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue({
...ownedCompleted,
status: 'ABANDONED',
});
await expect(reopenSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Only a completed session can be reopened',
});
});
it('409 when the user already has another active session', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue(ownedCompleted);
prisma.trainingSession.findFirst.mockResolvedValue({ id: 's2' });
await expect(reopenSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 409,
message: 'You already have an active session',
});
expect(prisma.$transaction).not.toHaveBeenCalled();
});
it('reopens the session and returns the day to planned (start reset to now)', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue(ownedCompleted);
prisma.trainingSession.findFirst.mockResolvedValue(null);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
prisma.planDay.updateMany.mockResolvedValue({ count: 1 });
await expect(reopenSession(prisma, 's1', 'u1')).resolves.toEqual({
sessionId: 's1',
status: 'IN_PROGRESS',
dayId: 'd1',
planId: 'p1',
planTitle: 'Plan A',
});
// stary endedAt/usunięty, startedAt = teraz — inaczej reguła 24h zbiłaby wznowienie
expect(prisma.trainingSession.updateMany).toHaveBeenCalledWith({
where: { id: 's1', status: 'COMPLETED' },
data: { status: 'IN_PROGRESS', startedAt: expect.any(Date), endedAt: null },
});
expect(prisma.planDay.updateMany).toHaveBeenCalledWith({
where: { id: 'd1', status: 'COMPLETED' },
data: { status: 'PLANNED', completedAt: null },
});
});
it('409 when the day is no longer completed (e.g. concurrently expired)', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue(ownedCompleted);
prisma.trainingSession.findFirst.mockResolvedValue(null);
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
prisma.planDay.updateMany.mockResolvedValue({ count: 0 });
await expect(reopenSession(prisma, 's1', 'u1')).rejects.toMatchObject({
status: 409,
message: 'Training day is no longer completed',
});
});
});
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' } } } },
});
mockSessionRow(prisma, 'IN_PROGRESS');
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' } } } },
});
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.update.mockResolvedValue({ id: 'se1' });
await expect(updateExercise(prisma, 'se1', 'u1', { hidden: true })).resolves.toEqual({
ok: true,
});
});
});
describe('addSet', () => {
const ownedExercise = {
id: 'se1',
sessionId: 's1',
session: {
id: 's1',
status: 'IN_PROGRESS',
day: { week: { plan: { userId: 'u1' } } },
},
};
it('400 when the session is not in progress', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'COMPLETED');
prisma.sessionExercise.findUnique.mockResolvedValue({
...ownedExercise,
session: { id: 's1', status: 'COMPLETED', day: { week: { plan: { userId: 'u1' } } } },
});
await expect(addSet(prisma, 'se1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Session is not in progress',
});
});
it('400 when planned (norm) sets of this exercise are still pending', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.count.mockResolvedValueOnce(1);
await expect(addSet(prisma, 'se1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'All planned sets of this exercise must be recorded before adding an extra set',
});
});
it('400 when an extra set is already in progress', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.count.mockResolvedValueOnce(0).mockResolvedValueOnce(1);
await expect(addSet(prisma, 'se1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'An extra set is already in progress',
});
});
it('adds an extra set when all norm sets are done and no extra is pending', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.count.mockResolvedValueOnce(0).mockResolvedValueOnce(0);
prisma.sessionSet.aggregate.mockResolvedValue({ _max: { index: 1 } });
prisma.sessionSet.create.mockResolvedValue({ id: 'st3', index: 2 });
const result = await addSet(prisma, 'se1', 'u1');
expect(result).toEqual({ setId: 'st3', index: 2 });
expect(prisma.sessionSet.create).toHaveBeenCalledWith({
data: { exerciseId: 'se1', index: 2 },
});
});
it('dodaje serie tylko po normie tego cwiczenia — liczy normy per cwiczenie, a nie per sesja', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.count.mockResolvedValueOnce(0).mockResolvedValueOnce(0);
prisma.sessionSet.aggregate.mockResolvedValue({ _max: { index: 0 } });
prisma.sessionSet.create.mockResolvedValue({ id: 'st2', index: 1 });
await expect(addSet(prisma, 'se1', 'u1')).resolves.toEqual({ setId: 'st2', index: 1 });
// zapytanie o normy musi byc zawezone do cwiczenia (se1), nie do calej sesji
expect(prisma.sessionSet.count).toHaveBeenNthCalledWith(1, {
where: {
exerciseId: 'se1',
planSetId: { not: null },
reps: null,
removed: false,
},
});
// limit bonusu jest liczony dla tego cwiczenia (nie dla sesji)
expect(prisma.sessionSet.count).toHaveBeenNthCalledWith(2, {
where: {
exerciseId: 'se1',
planSetId: null,
reps: null,
removed: false,
},
});
});
});
describe('deleteSet', () => {
const ownedSet = {
id: 'st1',
planSetId: null,
exercise: {
session: {
id: 's1',
status: 'IN_PROGRESS',
day: { week: { plan: { userId: 'u1' } } },
},
},
};
it('404 when the set belongs to another user', async () => {
const prisma = mockPrisma();
prisma.sessionSet.findUnique.mockResolvedValue({
...ownedSet,
exercise: {
session: { id: 's1', status: 'IN_PROGRESS', day: { week: { plan: { userId: 'other' } } } },
},
});
await expect(deleteSet(prisma, 'st1', 'u1')).rejects.toMatchObject({
status: 404,
message: 'Set not found',
});
});
it('400 when the set is a planned (norm) set', async () => {
const prisma = mockPrisma();
prisma.sessionSet.findUnique.mockResolvedValue({ ...ownedSet, planSetId: 'ps1' });
await expect(deleteSet(prisma, 'st1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Only extra sets can be removed',
});
});
it('400 when the session is not in progress', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'COMPLETED');
prisma.sessionSet.findUnique.mockResolvedValue({
...ownedSet,
exercise: {
session: { id: 's1', status: 'COMPLETED', day: { week: { plan: { userId: 'u1' } } } },
},
});
await expect(deleteSet(prisma, 'st1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'Session is not in progress',
});
});
it('soft-removes an extra set', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionSet.findUnique.mockResolvedValue(ownedSet);
prisma.sessionSet.update.mockResolvedValue({ id: 'st1', removed: true });
const result = await deleteSet(prisma, 'st1', 'u1');
expect(result).toEqual({ ok: true });
expect(prisma.sessionSet.update).toHaveBeenCalledWith({
where: { id: 'st1' },
data: { removed: true },
});
});
});
describe('addExercise', () => {
it('appends after the highest existing order', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.trainingSession.findUnique.mockResolvedValue({
id: 's1',
status: 'IN_PROGRESS',
day: { week: { plan: { userId: 'u1' } } },
});
prisma.exercise.findUnique.mockResolvedValue({ id: 'pz9' });
prisma.sessionExercise.aggregate.mockResolvedValue({ _max: { order: 3 } });
prisma.sessionExercise.create.mockResolvedValue({ id: 'se9', order: 4 });
const result = await addExercise(prisma, 's1', 'u1', 'pz9');
expect(result).toEqual({ exerciseId: 'se9', order: 4 });
expect(prisma.sessionExercise.create).toHaveBeenCalledWith({
data: { sessionId: 's1', exerciseId: 'pz9', order: 4 },
});
});
it('400 when the session is not in progress', async () => {
const prisma = mockPrisma();
prisma.trainingSession.findUnique.mockResolvedValue({
id: 's1',
status: 'COMPLETED',
day: { week: { plan: { userId: 'u1' } } },
});
await expect(addExercise(prisma, 's1', 'u1', 'pz9')).rejects.toMatchObject({
status: 400,
message: 'Session is not in progress',
});
});
});