1463 lines
52 KiB
TypeScript
1463 lines
52 KiB
TypeScript
import { describe, it, expect, vi } from 'vitest';
|
||
import {
|
||
abandonPlan,
|
||
acceptSkippedDay,
|
||
activatePlan,
|
||
assertPlanOwner,
|
||
completePlan,
|
||
createPlan,
|
||
deletePlan,
|
||
getMyTrainers,
|
||
getPlan,
|
||
listPlans,
|
||
listSharedWithMe,
|
||
movePlanDay,
|
||
reopenPlan,
|
||
resumePlan,
|
||
sharePlan,
|
||
suspendPlan,
|
||
unsharePlan,
|
||
updatePlan,
|
||
} from '../../src/services/plans.js';
|
||
|
||
function mockPrisma() {
|
||
const tx = {
|
||
planWeek: { deleteMany: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
|
||
trainingPlan: { update: vi.fn(), findFirst: vi.fn() },
|
||
planDay: { update: vi.fn(), updateMany: vi.fn(), create: vi.fn(), delete: vi.fn() },
|
||
planExercise: { create: vi.fn(), update: vi.fn(), delete: vi.fn() },
|
||
planSet: { createMany: vi.fn(), update: vi.fn(), delete: vi.fn() },
|
||
planEdit: { create: vi.fn() },
|
||
dayMove: { create: vi.fn() },
|
||
};
|
||
const prisma = {
|
||
trainingPlan: {
|
||
findUnique: vi.fn(),
|
||
findFirst: vi.fn(),
|
||
findMany: vi.fn(),
|
||
create: vi.fn(),
|
||
update: vi.fn(),
|
||
delete: vi.fn(),
|
||
},
|
||
trainingSession: { count: vi.fn() },
|
||
exercise: { findMany: vi.fn() },
|
||
coaching: { findUnique: vi.fn(), findMany: vi.fn() },
|
||
planWeek: { findMany: vi.fn() },
|
||
planDay: {
|
||
count: vi.fn(),
|
||
findFirst: vi.fn(),
|
||
findMany: vi.fn(),
|
||
findUnique: vi.fn(),
|
||
update: vi.fn(),
|
||
},
|
||
dayMove: { create: vi.fn() },
|
||
planShare: {
|
||
findUnique: vi.fn(),
|
||
create: vi.fn(),
|
||
deleteMany: vi.fn(),
|
||
findMany: vi.fn(),
|
||
},
|
||
notification: {
|
||
create: vi.fn(async (args: { data: unknown }) => ({ id: 'n1', ...args.data })),
|
||
},
|
||
$transaction: vi.fn(async (cb: (tx: typeof tx) => Promise<void>) => cb(tx)),
|
||
};
|
||
return { prisma, tx };
|
||
}
|
||
|
||
const draftPlan = { id: 'p1', userId: 'u1', status: 'DRAFT' };
|
||
|
||
// Poniedziałek o przesunięcie o N tygodni (0 = bieżący tydzień) w formacie YYYY-MM-DD.
|
||
function mondayIso(offsetWeeks: number): string {
|
||
const d = new Date();
|
||
d.setDate(d.getDate() - ((d.getDay() + 6) % 7) + offsetWeeks * 7);
|
||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||
}
|
||
|
||
describe('ownership', () => {
|
||
it('getPlan: 404 when the plan belongs to another user', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'other' });
|
||
await expect(getPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Plan not found',
|
||
});
|
||
});
|
||
|
||
it('getPlan: 404 when the plan does not exist', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(null);
|
||
await expect(getPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({ status: 404 });
|
||
});
|
||
});
|
||
|
||
describe('draft-only rules', () => {
|
||
it('updatePlan: rejects a closed (completed) plan with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });
|
||
await expect(
|
||
updatePlan(prisma, 'p1', 'u1', { title: 't', weeksCount: 1, weeks: [] }),
|
||
).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Only a draft or an active plan can be edited',
|
||
});
|
||
});
|
||
|
||
it('deletePlan: deletes a plan of any status', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
...draftPlan,
|
||
status: 'ACTIVE',
|
||
title: 'W trakcie',
|
||
});
|
||
await expect(deletePlan(prisma, 'p1', 'u1')).resolves.toEqual({
|
||
ok: true,
|
||
title: 'W trakcie',
|
||
status: 'ACTIVE',
|
||
});
|
||
expect(prisma.trainingPlan.delete).toHaveBeenCalledWith({ where: { id: 'p1' } });
|
||
});
|
||
|
||
it('abandonPlan: rejects an already closed plan with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ABANDONED' });
|
||
await expect(abandonPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
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',
|
||
});
|
||
});
|
||
|
||
it('completePlan: rejects an already closed plan with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });
|
||
await expect(completePlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
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',
|
||
});
|
||
});
|
||
|
||
it('completePlan: rejects an active plan with pending training days with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' });
|
||
prisma.planDay.count.mockResolvedValue(1);
|
||
await expect(completePlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Plan has pending training days — it can only be abandoned',
|
||
});
|
||
expect(prisma.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('completePlan: completes an active plan once no day is planned (skipped days allowed)', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' });
|
||
prisma.planDay.count.mockResolvedValue(0);
|
||
await expect(completePlan(prisma, 'p1', 'u1')).resolves.toEqual({ ok: true });
|
||
expect(prisma.trainingPlan.update).toHaveBeenCalledWith({
|
||
where: { id: 'p1' },
|
||
data: { status: 'COMPLETED' },
|
||
});
|
||
});
|
||
|
||
it('reopenPlan: rejects a draft plan with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
await expect(reopenPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Only a completed or abandoned plan can be reopened',
|
||
});
|
||
});
|
||
|
||
it('reopenPlan: rejects an active plan with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' });
|
||
await expect(reopenPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Only a completed or abandoned plan can be reopened',
|
||
});
|
||
});
|
||
|
||
it('reopenPlan: rejects reopening a plan owned by another user with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });
|
||
await expect(reopenPlan(prisma, 'p1', 'trainer1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Plan not found',
|
||
});
|
||
expect(prisma.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('reopenPlan: rejects when the owner has another active plan with 409', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });
|
||
prisma.trainingPlan.findFirst.mockResolvedValue({ id: 'p2', status: 'ACTIVE' });
|
||
await expect(reopenPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 409,
|
||
message: 'User already has an active plan',
|
||
});
|
||
expect(prisma.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('reopenPlan: reopens a completed plan', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'COMPLETED' });
|
||
prisma.trainingPlan.findFirst.mockResolvedValue(null);
|
||
await expect(reopenPlan(prisma, 'p1', 'u1')).resolves.toEqual({ ok: true });
|
||
expect(prisma.trainingPlan.update).toHaveBeenCalledWith({
|
||
where: { id: 'p1' },
|
||
data: { status: 'ACTIVE' },
|
||
});
|
||
});
|
||
});
|
||
|
||
/* ---------------------------------------------------------------------------
|
||
* Zawieszenie / wznowienie planu (pauza bez utraty zaplanowanych dni)
|
||
* ------------------------------------------------------------------------- */
|
||
|
||
/** Północ lokalna przesunięta o N dni od dziś. */
|
||
function localDay(offsetDays: number): Date {
|
||
const d = new Date();
|
||
d.setHours(0, 0, 0, 0);
|
||
d.setDate(d.getDate() + offsetDays);
|
||
return d;
|
||
}
|
||
|
||
describe('suspend / resume of a plan', () => {
|
||
it('suspendPlan: rejects a draft plan with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
await expect(suspendPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Only an active plan can be suspended',
|
||
});
|
||
});
|
||
|
||
it('suspendPlan: refuses to suspend while a training is in progress with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' });
|
||
prisma.trainingSession.count.mockResolvedValue(1);
|
||
await expect(suspendPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'A training is in progress — finish or abandon it before suspending the plan',
|
||
});
|
||
expect(prisma.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('suspendPlan: suspends an active plan', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
...draftPlan,
|
||
status: 'ACTIVE',
|
||
title: 'W trakcie',
|
||
});
|
||
prisma.trainingSession.count.mockResolvedValue(0);
|
||
await expect(suspendPlan(prisma, 'p1', 'u1')).resolves.toEqual({
|
||
ok: true,
|
||
title: 'W trakcie',
|
||
});
|
||
expect(prisma.trainingPlan.update).toHaveBeenCalledWith({
|
||
where: { id: 'p1' },
|
||
data: { status: 'SUSPENDED' },
|
||
});
|
||
});
|
||
|
||
it('resumePlan: rejects a non-suspended plan with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'ACTIVE' });
|
||
await expect(resumePlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Only a suspended plan can be resumed',
|
||
});
|
||
});
|
||
|
||
it('resumePlan: rejects reopening a plan owned by another user with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'SUSPENDED' });
|
||
await expect(resumePlan(prisma, 'p1', 'trainer1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Plan not found',
|
||
});
|
||
});
|
||
|
||
it('resumePlan: rejects when the owner has another active plan with 409', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, status: 'SUSPENDED' });
|
||
prisma.trainingPlan.findFirst.mockResolvedValue({ id: 'p2', status: 'ACTIVE' });
|
||
await expect(resumePlan(prisma, 'p1', 'u1')).rejects.toMatchObject({
|
||
status: 409,
|
||
message: 'User already has an active plan',
|
||
});
|
||
expect(prisma.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('resumePlan: keeps today/future planned days and shifts past ones by whole weeks, logging moves', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
...draftPlan,
|
||
status: 'SUSPENDED',
|
||
title: 'Wstrzymany',
|
||
startDate: localDay(-20),
|
||
});
|
||
prisma.trainingPlan.findFirst.mockResolvedValue(null);
|
||
// dni wg dat: miniony (−6), dziś (0) i przyszły (+1) — przesunięty −6 wpada
|
||
// na +1 (ten sam dzień tygodnia), więc skoczy o kolejny tydzień na +8
|
||
prisma.planDay.findMany.mockResolvedValue([
|
||
{ id: 'd-past', date: localDay(-6) },
|
||
{ id: 'd-today', date: localDay(0) },
|
||
{ id: 'd-future', date: localDay(1) },
|
||
]);
|
||
tx.trainingPlan.findFirst.mockResolvedValue(null);
|
||
|
||
await expect(resumePlan(prisma, 'p1', 'u1')).resolves.toEqual({
|
||
ok: true,
|
||
title: 'Wstrzymany',
|
||
movedDays: 1,
|
||
});
|
||
// tylko minione dni PLANNED są przesuwane (COMPLETED/SKIPPED spoza zapytania)
|
||
expect(prisma.planDay.findMany).toHaveBeenCalledWith({
|
||
where: { week: { planId: 'p1' }, removedAt: null, status: 'PLANNED' },
|
||
select: { id: true, date: true },
|
||
orderBy: { date: 'asc' },
|
||
});
|
||
expect(tx.dayMove.create).toHaveBeenCalledTimes(1);
|
||
expect(tx.dayMove.create).toHaveBeenCalledWith({
|
||
data: {
|
||
dayId: 'd-past',
|
||
fromDate: localDay(-6),
|
||
toDate: localDay(8),
|
||
reason: 'wznowienie planu',
|
||
},
|
||
});
|
||
expect(tx.planDay.update).toHaveBeenCalledTimes(1);
|
||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||
where: { id: 'd-past' },
|
||
data: { date: localDay(8) },
|
||
});
|
||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||
where: { id: 'p1' },
|
||
data: { status: 'ACTIVE' },
|
||
});
|
||
});
|
||
});
|
||
|
||
/** Dzień w formie wczytanej z bazy (edycja planu ACTIVE rozlicza się na takich wierszach). */
|
||
function loadedActiveWeek(
|
||
over: { dayStatus?: string; sessions?: { id: string; status: string }[] } = {},
|
||
) {
|
||
return [
|
||
{
|
||
id: 'w0',
|
||
index: 0,
|
||
customName: null,
|
||
days: [
|
||
{
|
||
id: 'd1',
|
||
dayOfWeek: 1,
|
||
status: over.dayStatus ?? 'PLANNED',
|
||
sessions: over.sessions ?? [],
|
||
exercises: [
|
||
{
|
||
id: 'e1',
|
||
exerciseId: 'x1',
|
||
order: 0,
|
||
sets: [
|
||
{
|
||
id: 's1',
|
||
index: 0,
|
||
reps: 10,
|
||
loadKg: 20,
|
||
restSec: 90,
|
||
rir: 2,
|
||
cardioBpm: null,
|
||
timeSec: null,
|
||
speed: null,
|
||
},
|
||
],
|
||
},
|
||
],
|
||
},
|
||
],
|
||
},
|
||
];
|
||
}
|
||
|
||
/** Taki sam payload jak `loadedActiveWeek` (front wysyła serie bez pól kardio — muszą zostać). */
|
||
function sameWeekPayload() {
|
||
return [
|
||
{
|
||
index: 0,
|
||
days: [
|
||
{
|
||
id: 'd1',
|
||
dayOfWeek: 1,
|
||
exercises: [
|
||
{
|
||
id: 'e1',
|
||
exerciseId: 'x1',
|
||
order: 0,
|
||
sets: [{ id: 's1', index: 0, reps: 10, loadKg: 20, restSec: 90, rir: 2 }],
|
||
},
|
||
],
|
||
},
|
||
],
|
||
},
|
||
];
|
||
}
|
||
|
||
describe('editing an active plan', () => {
|
||
const activeRow = {
|
||
id: 'p1',
|
||
userId: 'u1',
|
||
status: 'ACTIVE',
|
||
title: 't',
|
||
startDate: new Date(2030, 0, 7),
|
||
gymId: null,
|
||
};
|
||
|
||
function activeMocks(
|
||
over: { dayStatus?: string; sessions?: { id: string; status: string }[] } = {},
|
||
) {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(activeRow);
|
||
prisma.planWeek.findMany.mockResolvedValue(loadedActiveWeek(over));
|
||
return { prisma, tx };
|
||
}
|
||
|
||
it('records the edit without a change note (opcjonalna — pusta notatka)', async () => {
|
||
const { prisma, tx } = activeMocks();
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
|
||
await updatePlan(prisma, 'p1', 'u1', {
|
||
title: 'Nowa nazwa',
|
||
weeksCount: 1,
|
||
weeks: sameWeekPayload(),
|
||
});
|
||
expect(tx.planEdit.create).toHaveBeenCalledWith({
|
||
data: expect.objectContaining({ planId: 'p1', actorId: 'u1', note: '' }),
|
||
});
|
||
});
|
||
|
||
it('records the note and a change summary in the plan edit history', async () => {
|
||
const { prisma, tx } = activeMocks();
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }, { id: 'x2' }]);
|
||
const weeks = sameWeekPayload();
|
||
weeks[0].days[0].exercises.push({ exerciseId: 'x2', order: 1, sets: [{ index: 0, reps: 12 }] });
|
||
await updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks,
|
||
changeNote: 'Dodane ćwiczenie — korekta planu',
|
||
});
|
||
expect(tx.planExercise.create).toHaveBeenCalledTimes(1);
|
||
expect(tx.planEdit.create).toHaveBeenCalledWith({
|
||
data: expect.objectContaining({
|
||
planId: 'p1',
|
||
actorId: 'u1',
|
||
note: 'Dodane ćwiczenie — korekta planu',
|
||
summary: expect.objectContaining({ exercisesAdded: 1, setsAdded: 1 }),
|
||
}),
|
||
});
|
||
// właściciel edytuje swój plan — bez powiadomienia do feedu
|
||
expect(prisma.notification.create).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('notifies the owner when a trainer edits the active plan', async () => {
|
||
const { prisma, tx } = activeMocks();
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }, { id: 'x2' }]);
|
||
const weeks = sameWeekPayload();
|
||
weeks[0].days[0].exercises.push({ exerciseId: 'x2', order: 1, sets: [{ index: 0, reps: 12 }] });
|
||
await updatePlan(prisma, 'p1', 'trainer-9', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks,
|
||
changeNote: 'Korekta planu przez trenera',
|
||
});
|
||
expect(tx.planEdit.create).toHaveBeenCalledTimes(1);
|
||
expect(prisma.notification.create).toHaveBeenCalledWith({
|
||
data: {
|
||
userId: 'u1',
|
||
type: 'PLAN_EDITED',
|
||
title: 'Trener zmienił Twój plan: t — Korekta planu przez trenera',
|
||
payload: { planId: 'p1', planTitle: 't', note: 'Korekta planu przez trenera' },
|
||
},
|
||
});
|
||
});
|
||
|
||
it('no notification when the trainer saves the active plan without changes', async () => {
|
||
const { prisma } = activeMocks();
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
|
||
await updatePlan(prisma, 'p1', 'trainer-9', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: sameWeekPayload(),
|
||
});
|
||
expect(prisma.notification.create).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('keeps the untouched plan as is — no edit entry without a real change', async () => {
|
||
const { prisma, tx } = activeMocks();
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
|
||
await expect(
|
||
updatePlan(prisma, 'p1', 'u1', { title: 't', weeksCount: 1, weeks: sameWeekPayload() }),
|
||
).resolves.toEqual({ ok: true, edited: true });
|
||
expect(tx.planEdit.create).not.toHaveBeenCalled();
|
||
expect(tx.planExercise.delete).not.toHaveBeenCalled();
|
||
expect(tx.planDay.delete).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('keeps untouched cardio fields of a set the client does not send', async () => {
|
||
const { prisma, tx } = activeMocks();
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
|
||
await updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [
|
||
{
|
||
index: 0,
|
||
days: [
|
||
{
|
||
id: 'd1',
|
||
dayOfWeek: 1,
|
||
exercises: [
|
||
{ id: 'e1', exerciseId: 'x1', order: 0, sets: [{ id: 's1', index: 0, reps: 8 }] },
|
||
],
|
||
},
|
||
],
|
||
},
|
||
],
|
||
changeNote: 'Zmiana liczby powtorzen',
|
||
});
|
||
expect(tx.planSet.update).toHaveBeenCalledWith({
|
||
where: { id: 's1' },
|
||
data: {
|
||
reps: 8,
|
||
loadKg: 20,
|
||
restSec: 90,
|
||
rir: 2,
|
||
cardioBpm: null,
|
||
timeSec: null,
|
||
speed: null,
|
||
},
|
||
});
|
||
});
|
||
|
||
it('refuses to remove a day that has training history', async () => {
|
||
const { prisma } = activeMocks({ dayStatus: 'COMPLETED' });
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
await expect(
|
||
updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [{ index: 0, days: [] }],
|
||
changeNote: 'Usuwanie dnia',
|
||
}),
|
||
).rejects.toMatchObject({
|
||
status: 400,
|
||
code: 'PLAN_DAY_HAS_HISTORY',
|
||
message: /has training history/,
|
||
details: { weekIndex: 0, dayOfWeek: 1 },
|
||
});
|
||
});
|
||
|
||
it('force-removeDays soft-removes a day with history instead of deleting it', async () => {
|
||
const { prisma, tx } = activeMocks({ dayStatus: 'COMPLETED' });
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
await updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [{ index: 0, days: [] }],
|
||
changeNote: 'Silowe usuniecie dnia z historia',
|
||
forceRemoveDays: true,
|
||
});
|
||
expect(tx.planDay.delete).not.toHaveBeenCalled();
|
||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||
where: { id: 'd1' },
|
||
data: { removedAt: expect.any(Date) },
|
||
});
|
||
expect(tx.planEdit.create).toHaveBeenCalledWith({
|
||
data: expect.objectContaining({
|
||
note: 'Silowe usuniecie dnia z historia',
|
||
summary: expect.objectContaining({ daysForceRemoved: 1, daysRemoved: 0 }),
|
||
}),
|
||
});
|
||
});
|
||
|
||
it('force-removeDays soft-removes history days of a dropped week and keeps them attached to a surviving week', async () => {
|
||
const { prisma, tx } = activeMocks();
|
||
prisma.planWeek.findMany.mockResolvedValue([
|
||
...loadedActiveWeek(),
|
||
{
|
||
id: 'w1',
|
||
index: 1,
|
||
customName: null,
|
||
days: [
|
||
{
|
||
id: 'd2',
|
||
dayOfWeek: 3,
|
||
status: 'COMPLETED',
|
||
sessions: [{ id: 'ses1', status: 'COMPLETED' }],
|
||
exercises: [],
|
||
},
|
||
],
|
||
},
|
||
]);
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
|
||
await updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: sameWeekPayload(),
|
||
changeNote: 'Zmniejszenie liczby tygodni',
|
||
forceRemoveDays: true,
|
||
});
|
||
expect(tx.planDay.updateMany).toHaveBeenCalledWith({
|
||
where: { id: { in: ['d2'] } },
|
||
data: { removedAt: expect.any(Date), weekId: 'w0' },
|
||
});
|
||
expect(tx.planWeek.delete).toHaveBeenCalledWith({ where: { id: 'w1' } });
|
||
});
|
||
|
||
it('refuses to change the start date of an active plan', async () => {
|
||
const { prisma } = activeMocks();
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
|
||
await expect(
|
||
updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: sameWeekPayload(),
|
||
startDate: mondayIso(2),
|
||
}),
|
||
).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'An active plan cannot change its start date',
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('moving a training day', () => {
|
||
const startDate = new Date();
|
||
startDate.setDate(startDate.getDate() - 30);
|
||
const activeRow = {
|
||
id: 'p1',
|
||
userId: 'u1',
|
||
status: 'ACTIVE',
|
||
title: 't',
|
||
startDate,
|
||
gymId: null,
|
||
};
|
||
|
||
function isoIn(days: number): string {
|
||
const d = new Date();
|
||
d.setDate(d.getDate() + days);
|
||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||
}
|
||
function day(over: Record<string, unknown> = {}) {
|
||
return { id: 'd1', dayOfWeek: 1, status: 'PLANNED', date: new Date(), sessions: [], ...over };
|
||
}
|
||
function moveMocks(dayRow: ReturnType<typeof day>, occupants: unknown[] = []) {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(activeRow);
|
||
prisma.planDay.findFirst.mockResolvedValue(dayRow);
|
||
prisma.planDay.findMany.mockResolvedValue(occupants);
|
||
prisma.planDay.findUnique.mockResolvedValue({
|
||
id: 'd1',
|
||
date: new Date(),
|
||
status: 'PLANNED',
|
||
dayOfWeek: 1,
|
||
});
|
||
return { prisma, tx };
|
||
}
|
||
|
||
it('rejects a plan that is not active with 400', async () => {
|
||
const { prisma } = moveMocks(day());
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...activeRow, status: 'DRAFT' });
|
||
await expect(movePlanDay(prisma, 'p1', 'd1', 'u1', { date: isoIn(1) })).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Only active plans have movable training days',
|
||
});
|
||
});
|
||
|
||
it('rejects a completed day with 400', async () => {
|
||
const { prisma } = moveMocks(day({ status: 'COMPLETED' }));
|
||
await expect(movePlanDay(prisma, 'p1', 'd1', 'u1', { date: isoIn(1) })).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'A completed day cannot be moved',
|
||
});
|
||
});
|
||
|
||
it('rejects a day with a training in progress with 400', async () => {
|
||
const { prisma } = moveMocks(day({ sessions: [{ id: 's1', status: 'IN_PROGRESS' }] }));
|
||
await expect(movePlanDay(prisma, 'p1', 'd1', 'u1', { date: isoIn(1) })).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'A day with a training in progress cannot be moved',
|
||
});
|
||
});
|
||
|
||
it('rejects a target date in the past with 400', async () => {
|
||
const { prisma } = moveMocks(day());
|
||
await expect(movePlanDay(prisma, 'p1', 'd1', 'u1', { date: isoIn(-3) })).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Target date cannot be in the past',
|
||
});
|
||
});
|
||
|
||
it('rejects moving onto a date that already has a planned training with 409', async () => {
|
||
const { prisma, tx } = moveMocks(day(), [{ id: 'd2', date: new Date(), sessions: [] }]);
|
||
await expect(movePlanDay(prisma, 'p1', 'd1', 'u1', { date: isoIn(0) })).rejects.toMatchObject({
|
||
status: 409,
|
||
message: 'Another training is already planned on that date',
|
||
});
|
||
expect(tx.dayMove.create).not.toHaveBeenCalled();
|
||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('postpones a day, logs the move and revives a skipped one', async () => {
|
||
const skipped = day({
|
||
status: 'SKIPPED',
|
||
skippedAt: new Date(),
|
||
date: new Date(Date.now() - 5 * 86400000),
|
||
});
|
||
const { prisma, tx } = moveMocks(skipped);
|
||
await movePlanDay(prisma, 'p1', 'd1', 'u1', { date: isoIn(2), reason: 'kontuzja' });
|
||
expect(tx.dayMove.create).toHaveBeenCalledWith({
|
||
data: expect.objectContaining({ dayId: 'd1', reason: 'kontuzja' }),
|
||
});
|
||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||
where: { id: 'd1' },
|
||
data: expect.objectContaining({
|
||
status: 'PLANNED',
|
||
skippedAt: null,
|
||
// decyzja wyzerowana: jeśli przesunięty dzień znowu minie, dialog zapyta ponownie
|
||
skipResolvedAt: null,
|
||
}),
|
||
});
|
||
});
|
||
|
||
it('swaps the dates of two days when swapWithDayId is sent', async () => {
|
||
const target = new Date();
|
||
target.setDate(target.getDate() + 1);
|
||
const { prisma, tx } = moveMocks(day(), [{ id: 'd2', date: target, sessions: [] }]);
|
||
const result = await movePlanDay(prisma, 'p1', 'd1', 'u1', {
|
||
date: isoIn(1),
|
||
swapWithDayId: 'd2',
|
||
reason: 'zamiana dni',
|
||
});
|
||
expect(result.swappedWith).toBe('d2');
|
||
expect(tx.dayMove.create).toHaveBeenCalledTimes(2);
|
||
expect(tx.planDay.update).toHaveBeenCalledTimes(2);
|
||
});
|
||
});
|
||
|
||
describe('accepting a skipped day', () => {
|
||
const startDate = new Date();
|
||
startDate.setDate(startDate.getDate() - 30);
|
||
const activeRow = {
|
||
id: 'p1',
|
||
userId: 'u1',
|
||
status: 'ACTIVE',
|
||
title: 't',
|
||
startDate,
|
||
gymId: null,
|
||
};
|
||
|
||
function acceptMocks(dayRow: Record<string, unknown> | null) {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(activeRow);
|
||
prisma.planDay.findFirst.mockResolvedValue(dayRow);
|
||
prisma.planDay.update.mockResolvedValue(dayRow);
|
||
return prisma;
|
||
}
|
||
|
||
it('accepts an unresolved skipped day and stamps skipResolvedAt', async () => {
|
||
const prisma = acceptMocks({
|
||
id: 'd1',
|
||
status: 'SKIPPED',
|
||
skippedAt: new Date(),
|
||
skipResolvedAt: null,
|
||
});
|
||
await acceptSkippedDay(prisma, 'p1', 'd1', 'u1');
|
||
expect(prisma.planDay.update).toHaveBeenCalledTimes(1);
|
||
expect(prisma.planDay.update).toHaveBeenCalledWith({
|
||
where: { id: 'd1' },
|
||
data: { skipResolvedAt: expect.any(Date) },
|
||
});
|
||
});
|
||
|
||
it('is idempotent: an already-resolved day returns without a second write', async () => {
|
||
const prisma = acceptMocks({
|
||
id: 'd1',
|
||
status: 'SKIPPED',
|
||
skippedAt: new Date(),
|
||
skipResolvedAt: new Date(),
|
||
});
|
||
const result = await acceptSkippedDay(prisma, 'p1', 'd1', 'u1');
|
||
expect(prisma.planDay.update).not.toHaveBeenCalled();
|
||
expect(result.day).toMatchObject({ id: 'd1', status: 'SKIPPED' });
|
||
});
|
||
|
||
it('rejects a planned day with 400', async () => {
|
||
const prisma = acceptMocks({ id: 'd1', status: 'PLANNED', skipResolvedAt: null });
|
||
await expect(acceptSkippedDay(prisma, 'p1', 'd1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Only a skipped training day can be accepted',
|
||
});
|
||
expect(prisma.planDay.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('rejects a day from another plan with 404', async () => {
|
||
const prisma = acceptMocks(null);
|
||
await expect(acceptSkippedDay(prisma, 'p1', 'dX', 'u1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Training day not found',
|
||
});
|
||
});
|
||
|
||
it('rejects a foreign plan with 404 (owner only, no existence leak)', async () => {
|
||
const prisma = acceptMocks({ id: 'd1', status: 'SKIPPED', skipResolvedAt: null });
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...activeRow, userId: 'someone-else' });
|
||
await expect(acceptSkippedDay(prisma, 'p1', 'd1', 'u1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Plan not found',
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('createPlan', () => {
|
||
it('rejects an unknown exerciseId with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.exercise.findMany.mockResolvedValue([{ id: 'pz1' }]);
|
||
const data = {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [
|
||
{
|
||
index: 0,
|
||
days: [
|
||
{
|
||
dayOfWeek: 1,
|
||
exercises: [
|
||
{ exerciseId: 'pz1', order: 0, sets: [{ index: 0 }] },
|
||
{ exerciseId: 'pz-missing', order: 1, sets: [{ index: 0 }] },
|
||
],
|
||
},
|
||
],
|
||
},
|
||
],
|
||
};
|
||
await expect(createPlan(prisma, 'u1', data)).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Unknown exerciseId in plan',
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('activatePlan', () => {
|
||
it('rejects a non-Monday start date with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
// 2026-08-25 is a Tuesday
|
||
await expect(activatePlan(prisma, 'p1', 'u1', '2026-08-25')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Start date must be a Monday',
|
||
});
|
||
});
|
||
|
||
it('rejects an invalid start date with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
await expect(activatePlan(prisma, 'p1', 'u1', 'not-a-date')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Invalid start date',
|
||
});
|
||
});
|
||
|
||
it('rejects when the user already has an active plan with 409', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
prisma.trainingPlan.findFirst.mockResolvedValue({ id: 'other-active' });
|
||
await expect(activatePlan(prisma, 'p1', 'u1', mondayIso(1))).rejects.toMatchObject({
|
||
status: 409,
|
||
message: 'User already has an active plan',
|
||
});
|
||
});
|
||
|
||
it('rejects a past-week start date with 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
await expect(activatePlan(prisma, 'p1', 'u1', mondayIso(-1))).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Start date cannot be in the past',
|
||
});
|
||
});
|
||
|
||
it('rejects with 409 when another plan becomes active inside the transaction (race)', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
// Pre-check poza transakcją nic nie widzi…
|
||
prisma.trainingPlan.findFirst.mockResolvedValue(null);
|
||
prisma.planWeek.findMany.mockResolvedValue([]);
|
||
// …ale wewnątrz transakcji inny plan właściciela jest już ACTIVE.
|
||
tx.trainingPlan.findFirst.mockResolvedValue({ id: 'other-active' });
|
||
await expect(activatePlan(prisma, 'p1', 'u1', mondayIso(1))).rejects.toMatchObject({
|
||
status: 409,
|
||
message: 'User already has an active plan',
|
||
});
|
||
expect(tx.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('computes day dates from the Monday and activates the plan', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
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: 1, days: [{ id: 'd3', dayOfWeek: 1 }] },
|
||
]);
|
||
tx.trainingPlan.findFirst.mockResolvedValue(null);
|
||
tx.planDay.update.mockResolvedValue({});
|
||
tx.trainingPlan.update.mockResolvedValue({});
|
||
|
||
const start = mondayIso(1);
|
||
const [y, m, d] = start.split('-').map(Number);
|
||
const plus = (n: number) => new Date(y, m - 1, d + n);
|
||
|
||
await activatePlan(prisma, 'p1', 'u1', start);
|
||
|
||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||
where: { id: 'd1' },
|
||
data: { date: plus(0) },
|
||
});
|
||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||
where: { id: 'd2' },
|
||
data: { date: plus(2) },
|
||
});
|
||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||
where: { id: 'd3' },
|
||
data: { date: plus(7) },
|
||
});
|
||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||
where: { id: 'p1' },
|
||
data: { status: 'ACTIVE', startDate: plus(0) },
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('listPlans', () => {
|
||
it('returns the user plans ordered by createdAt desc, with creator and progress', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findMany.mockResolvedValue([
|
||
{
|
||
id: 'p1',
|
||
weeks: [{ days: [{ status: 'COMPLETED' }, { status: 'PLANNED' }] }],
|
||
},
|
||
]);
|
||
const result = await listPlans(prisma, 'u1');
|
||
expect(prisma.trainingPlan.findMany).toHaveBeenCalledWith({
|
||
where: { userId: 'u1', kind: 'PLAN' },
|
||
orderBy: { createdAt: 'desc' },
|
||
include: {
|
||
creator: { select: { id: true, firstName: true, lastName: true } },
|
||
gym: { select: { id: true, name: true } },
|
||
weeks: {
|
||
select: {
|
||
index: true,
|
||
days: {
|
||
where: { removedAt: null },
|
||
select: {
|
||
status: true,
|
||
date: true,
|
||
dayOfWeek: true,
|
||
_count: { select: { exercises: true } },
|
||
},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
});
|
||
expect(result).toEqual({
|
||
plans: [
|
||
{
|
||
id: 'p1',
|
||
progress: { completed: 1, total: 2, percent: 50 },
|
||
currentWeek: null,
|
||
nextDay: null,
|
||
},
|
||
],
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('assertPlanAccess (via getPlan)', () => {
|
||
it('allows the owner (trainee) to read the plan', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1', shares: [] });
|
||
await expect(getPlan(prisma, 'p1', 'u1')).resolves.toMatchObject({
|
||
plan: { id: 'p1', canManage: true },
|
||
});
|
||
});
|
||
|
||
it('allows a trainer with an ACTIVE coaching relation to read the plan', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
...draftPlan,
|
||
userId: 'trainee-1',
|
||
shares: [],
|
||
});
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||
const result = await getPlan(prisma, 'p1', 'trainer-1');
|
||
expect(result.plan).toMatchObject({ id: 'p1', canManage: true });
|
||
// trener nie dostaje listy odbiorców share'u
|
||
expect(result.plan.shares).toBeUndefined();
|
||
});
|
||
|
||
it('rejects a trainer with a PENDING relation with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'PENDING' });
|
||
await expect(getPlan(prisma, 'p1', 'trainer-1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Plan not found',
|
||
});
|
||
});
|
||
|
||
it('rejects a trainer with an ARCHIVED relation with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ARCHIVED' });
|
||
await expect(getPlan(prisma, 'p1', 'trainer-1')).rejects.toMatchObject({ status: 404 });
|
||
});
|
||
|
||
it('allows a share recipient to read the plan (read-only)', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
...draftPlan,
|
||
userId: 'trainee-1',
|
||
shares: [],
|
||
});
|
||
prisma.coaching.findUnique.mockResolvedValue(null);
|
||
prisma.planShare.findUnique.mockResolvedValue({ id: 'share-1' });
|
||
const result = await getPlan(prisma, 'p1', 'recipient-1');
|
||
expect(result.plan).toMatchObject({ id: 'p1', canManage: false });
|
||
expect(result.plan.shares).toBeUndefined();
|
||
});
|
||
|
||
it('rejects an unrelated user (no coaching relation, no share) with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||
prisma.coaching.findUnique.mockResolvedValue(null);
|
||
prisma.planShare.findUnique.mockResolvedValue(null);
|
||
await expect(getPlan(prisma, 'p1', 'stranger')).rejects.toMatchObject({ status: 404 });
|
||
});
|
||
|
||
it('rejects a missing plan with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(null);
|
||
await expect(getPlan(prisma, 'p1', 'u1')).rejects.toMatchObject({ status: 404 });
|
||
});
|
||
});
|
||
|
||
describe('assertPlanOwner', () => {
|
||
it('allows the owner', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||
await expect(assertPlanOwner(prisma, 'p1', 'u1')).resolves.toMatchObject({ id: 'p1' });
|
||
});
|
||
|
||
it('rejects a non-owner (even a trainer) with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||
await expect(assertPlanOwner(prisma, 'p1', 'trainer-1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Plan not found',
|
||
});
|
||
});
|
||
|
||
it('rejects a missing plan with 404', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(null);
|
||
await expect(assertPlanOwner(prisma, 'p1', 'u1')).rejects.toMatchObject({ status: 404 });
|
||
});
|
||
});
|
||
|
||
describe('createPlan creatorId', () => {
|
||
it('sets creatorId to the given creator (trainer) when provided', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
prisma.trainingPlan.create.mockResolvedValue({ id: 'p1' });
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
id: 'p1',
|
||
title: 't',
|
||
status: 'DRAFT',
|
||
weeksCount: 1,
|
||
startDate: null,
|
||
});
|
||
await createPlan(prisma, 'trainee-1', { title: 't', weeksCount: 1, weeks: [] }, 'trainer-1');
|
||
expect(prisma.notification.create).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
data: expect.objectContaining({ userId: 'trainee-1', type: 'PLAN_READY' }),
|
||
}),
|
||
);
|
||
expect(prisma.trainingPlan.create).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
data: expect.objectContaining({ userId: 'trainee-1', creatorId: 'trainer-1' }),
|
||
}),
|
||
);
|
||
});
|
||
|
||
it('defaults creatorId to the owner when not provided', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
prisma.trainingPlan.create.mockResolvedValue({ id: 'p1' });
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
id: 'p1',
|
||
title: 't',
|
||
status: 'DRAFT',
|
||
weeksCount: 1,
|
||
startDate: null,
|
||
});
|
||
await createPlan(prisma, 'u1', { title: 't', weeksCount: 1, weeks: [] });
|
||
expect(prisma.trainingPlan.create).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
data: expect.objectContaining({ userId: 'u1', creatorId: 'u1' }),
|
||
}),
|
||
);
|
||
});
|
||
});
|
||
|
||
describe('createPlan (startDate = planowany start, bez autoaktywacji)', () => {
|
||
it('tworzy DRAFT z zapisanym startem; daty dni liczone dopiero przy aktywacji', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
prisma.trainingPlan.create.mockResolvedValue({ id: 'p1' });
|
||
const start = mondayIso(1);
|
||
const [y, m, d] = start.split('-').map(Number);
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||
id: 'p1',
|
||
title: 't',
|
||
status: 'DRAFT',
|
||
weeksCount: 1,
|
||
startDate: new Date(y, m - 1, d),
|
||
});
|
||
const result = await createPlan(prisma, 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [],
|
||
startDate: start,
|
||
});
|
||
expect(result).toMatchObject({ plan: { id: 'p1', status: 'DRAFT' } });
|
||
expect(result).not.toHaveProperty('activationSkipped');
|
||
// planowany start zapisany w wierszu planu
|
||
expect(prisma.trainingPlan.create).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
data: expect.objectContaining({ startDate: new Date(y, m - 1, d) }),
|
||
}),
|
||
);
|
||
// brak ścieżki aktywacji: brak dat dni i brak sprawdzania aktywnego planu
|
||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||
expect(tx.trainingPlan.findFirst).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('z dniem wypadającym przed dzisiaj względem startu: 400 PLAN_DAY_IN_PAST (przed zapisem)', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
// poniedziałek bieżącego tygodnia: dni przed dzisiaj wypadałyby w przeszłości
|
||
const dowToday = ((new Date().getDay() + 6) % 7) + 1; // 1=Pn .. 7=Nd
|
||
if (dowToday <= 1) return; // w poniedziałek ten tydzień nie ma minionych dni
|
||
await expect(
|
||
createPlan(prisma, 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [{ index: 0, days: [{ dayOfWeek: dowToday - 1, exercises: [] }] }],
|
||
startDate: mondayIso(0),
|
||
}),
|
||
).rejects.toMatchObject({ status: 400, code: 'PLAN_DAY_IN_PAST' });
|
||
// fail-fast: plan nie został utworzony
|
||
expect(prisma.trainingPlan.create).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('updatePlan (startDate = planowany start szkicu, bez autoaktywacji)', () => {
|
||
it('bez startDate: aktualizuje strukturę, start wyzerowany, plan pozostaje DRAFT', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
tx.trainingPlan.update.mockResolvedValue({});
|
||
await updatePlan(prisma, 'p1', 'u1', { title: 't', weeksCount: 1, weeks: [] });
|
||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||
where: { id: 'p1' },
|
||
data: expect.objectContaining({ title: 't', startDate: null }),
|
||
});
|
||
// bez aktywacji — brak wyliczania dat
|
||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('z startDate: zapisuje planowany start bez aktywacji (brak dat dni)', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
tx.trainingPlan.update.mockResolvedValue({});
|
||
|
||
const start = mondayIso(1);
|
||
const [y, m, d] = start.split('-').map(Number);
|
||
const result = await updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [],
|
||
startDate: start,
|
||
});
|
||
expect(result).toEqual({ ok: true });
|
||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||
where: { id: 'p1' },
|
||
data: expect.objectContaining({ title: 't', startDate: new Date(y, m - 1, d) }),
|
||
});
|
||
// NIGDY nie aktywujemy: brak dat dni i brak sprawdzania aktywnego planu
|
||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||
expect(tx.trainingPlan.findFirst).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('z startDate nie-poniedziałkiem: 400 (fail-fast, przed aktualizacją)', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
// 2026-08-25 to wtorek
|
||
await expect(
|
||
updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [],
|
||
startDate: '2026-08-25',
|
||
}),
|
||
).rejects.toMatchObject({ status: 400, message: 'Start date must be a Monday' });
|
||
// struktura nie została dotknięta
|
||
expect(tx.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it('z startDate w minionym tygodniu: 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
await expect(
|
||
updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [],
|
||
startDate: mondayIso(-1),
|
||
}),
|
||
).rejects.toMatchObject({ status: 400, message: 'Start date cannot be in the past' });
|
||
});
|
||
|
||
it('z startDate: dni przed dzisiaj względem startu → 400 PLAN_DAY_IN_PAST (przed zapisem)', async () => {
|
||
const { prisma, tx } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||
prisma.exercise.findMany.mockResolvedValue([]);
|
||
const dowToday = ((new Date().getDay() + 6) % 7) + 1;
|
||
if (dowToday <= 1) return;
|
||
await expect(
|
||
updatePlan(prisma, 'p1', 'u1', {
|
||
title: 't',
|
||
weeksCount: 1,
|
||
weeks: [{ index: 0, days: [{ dayOfWeek: dowToday - 1, exercises: [] }] }],
|
||
startDate: mondayIso(0),
|
||
}),
|
||
).rejects.toMatchObject({ status: 400, code: 'PLAN_DAY_IN_PAST' });
|
||
expect(tx.trainingPlan.update).not.toHaveBeenCalled();
|
||
});
|
||
});
|
||
|
||
describe('sharePlan', () => {
|
||
const ownerPlan = { ...draftPlan, userId: 'u1' };
|
||
|
||
it('właściciel udostępnia plan podopiecznemu (ACTIVE coaching)', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||
// u1 = trener, trainee-1 = podopieczny (właściciel → assertPlanAccess bez coachingu)
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||
prisma.planShare.create.mockResolvedValue({ id: 'share-1' });
|
||
const result = await sharePlan(prisma, 'p1', 'u1', 'trainee-1');
|
||
expect(prisma.planShare.create).toHaveBeenCalledWith({
|
||
data: { planId: 'p1', sharedById: 'u1', sharedWithId: 'trainee-1' },
|
||
});
|
||
expect(result).toEqual({ share: { id: 'share-1' } });
|
||
expect(prisma.notification.create).toHaveBeenCalledWith(
|
||
expect.objectContaining({
|
||
data: expect.objectContaining({ userId: 'trainee-1', type: 'PLAN_SHARED' }),
|
||
}),
|
||
);
|
||
});
|
||
|
||
it('właściciel udostępnia plan swojemu trenerowi (odwrotny kierunek coachingu)', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||
prisma.coaching.findUnique
|
||
.mockResolvedValueOnce(null) // u1 jako trener? nie…
|
||
.mockResolvedValueOnce({ status: 'ACTIVE' }); // …ale trainer-1 jest trenerem u1
|
||
prisma.planShare.create.mockResolvedValue({ id: 'share-2' });
|
||
await sharePlan(prisma, 'p1', 'u1', 'trainer-1');
|
||
expect(prisma.planShare.create).toHaveBeenCalledWith({
|
||
data: { planId: 'p1', sharedById: 'u1', sharedWithId: 'trainer-1' },
|
||
});
|
||
});
|
||
|
||
it('nie-właściciel (trener): 403', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||
await expect(sharePlan(prisma, 'p1', 'trainer-1', 'u1')).rejects.toMatchObject({
|
||
status: 403,
|
||
message: 'Only the plan owner can share the plan',
|
||
});
|
||
});
|
||
|
||
it('udostępnienie samemu sobie: 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||
await expect(sharePlan(prisma, 'p1', 'u1', 'u1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'Cannot share a plan with yourself',
|
||
});
|
||
});
|
||
|
||
it('brak aktywnego coachingu: 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||
prisma.coaching.findUnique.mockResolvedValue(null);
|
||
await expect(sharePlan(prisma, 'p1', 'u1', 'stranger')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'No active coaching relation with this user',
|
||
});
|
||
});
|
||
|
||
it('PENDING coaching: 400', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'PENDING' });
|
||
await expect(sharePlan(prisma, 'p1', 'u1', 'trainee-1')).rejects.toMatchObject({
|
||
status: 400,
|
||
message: 'No active coaching relation with this user',
|
||
});
|
||
});
|
||
|
||
it('duplikat: 409', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||
prisma.planShare.create.mockRejectedValue(
|
||
Object.assign(new Error('Unique constraint failed'), { code: 'P2002' }),
|
||
);
|
||
await expect(sharePlan(prisma, 'p1', 'u1', 'trainee-1')).rejects.toMatchObject({
|
||
status: 409,
|
||
message: 'Plan is already shared with this user',
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('unsharePlan', () => {
|
||
it('właściciel cofa udostępnienie', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||
prisma.planShare.deleteMany.mockResolvedValue({ count: 1 });
|
||
const result = await unsharePlan(prisma, 'p1', 'u1', 'trainee-1');
|
||
expect(prisma.planShare.deleteMany).toHaveBeenCalledWith({
|
||
where: { planId: 'p1', sharedWithId: 'trainee-1' },
|
||
});
|
||
expect(result).toEqual({ ok: true });
|
||
});
|
||
|
||
it('nie-właściciel: 403', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||
await expect(unsharePlan(prisma, 'p1', 'trainer-1', 'u1')).rejects.toMatchObject({
|
||
status: 403,
|
||
});
|
||
});
|
||
|
||
it("brak share'a: 404", async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||
prisma.planShare.deleteMany.mockResolvedValue({ count: 0 });
|
||
await expect(unsharePlan(prisma, 'p1', 'u1', 'trainee-1')).rejects.toMatchObject({
|
||
status: 404,
|
||
message: 'Plan is not shared with this user',
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('listSharedWithMe', () => {
|
||
it('zwraca udostępnione plany z imieniem udostępniającego i postępem', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.planShare.findMany.mockResolvedValue([
|
||
{
|
||
sharedBy: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener' },
|
||
plan: {
|
||
id: 'p1',
|
||
title: 'Plan trenera',
|
||
status: 'ACTIVE',
|
||
weeksCount: 4,
|
||
startDate: null,
|
||
gym: null,
|
||
weeks: [{ days: [{ status: 'COMPLETED' }, { status: 'PLANNED' }] }],
|
||
},
|
||
},
|
||
]);
|
||
const result = await listSharedWithMe(prisma, 'u1');
|
||
expect(result).toEqual({
|
||
plans: [
|
||
{
|
||
id: 'p1',
|
||
title: 'Plan trenera',
|
||
status: 'ACTIVE',
|
||
weeksCount: 4,
|
||
startDate: null,
|
||
gym: null,
|
||
sharedBy: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener' },
|
||
progress: { completed: 1, total: 2, percent: 50 },
|
||
},
|
||
],
|
||
});
|
||
});
|
||
});
|
||
|
||
describe('getMyTrainers', () => {
|
||
it('zwraca trenerów z AKTYWNYM coachingiem (ja = podopieczny)', async () => {
|
||
const { prisma } = mockPrisma();
|
||
prisma.coaching.findMany.mockResolvedValue([
|
||
{ trainer: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener', nickname: null } },
|
||
]);
|
||
const result = await getMyTrainers(prisma, 'u1');
|
||
expect(prisma.coaching.findMany).toHaveBeenCalledWith({
|
||
where: { userId: 'u1', status: 'ACTIVE' },
|
||
include: {
|
||
trainer: { select: { id: true, firstName: true, lastName: true, nickname: true } },
|
||
},
|
||
orderBy: { createdAt: 'asc' },
|
||
});
|
||
expect(result).toEqual({
|
||
trainers: [{ id: 'trainer-1', firstName: 'Marek', lastName: 'Trener', nickname: null }],
|
||
});
|
||
});
|
||
});
|