Plany: PATCH z startDate (aktywacja przy zapisie) i udostepnianie planow trener-podopieczny (PlanShare, sekcja Udostepnione mi, widok read-only)
This commit is contained in:
@@ -1,6 +1,16 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import { prisma } from '../../src/lib/prisma.js';
|
||||
import { buildApp, createUser, createExercise, loginViaApi, rand, registerViaApi, seedPlan, PASSWORD } from '../helpers.js';
|
||||
import {
|
||||
buildApp,
|
||||
createUser,
|
||||
createUserWithToken,
|
||||
createExercise,
|
||||
loginViaApi,
|
||||
rand,
|
||||
registerViaApi,
|
||||
seedPlan,
|
||||
PASSWORD,
|
||||
} from '../helpers.js';
|
||||
|
||||
// Daty dynamiczne: tydzień startu musi być bieżący lub przyszły (nie miniony).
|
||||
function mondayIso(offsetWeeks: number): string {
|
||||
@@ -629,3 +639,260 @@ describe('plans: trainer-created plan (creator + owner access)', () => {
|
||||
expect(res.body.error.message).toBe('Plan owner is not a member of the gym');
|
||||
});
|
||||
});
|
||||
|
||||
describe('plans: sharing (PlanShare)', () => {
|
||||
let app: ReturnType<typeof buildApp>;
|
||||
let trainer: { user: { id: string }; token: string };
|
||||
let trainee: { user: { id: string }; token: string };
|
||||
let stranger: { user: { id: string }; token: string };
|
||||
let exerciseId: string;
|
||||
let planId: string;
|
||||
|
||||
const body = (title: string) => ({
|
||||
title,
|
||||
weeksCount: 1,
|
||||
weeks: [
|
||||
{
|
||||
index: 0,
|
||||
days: [
|
||||
{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
app = buildApp();
|
||||
trainer = await createUserWithToken({ firstName: 'ShareTrainer' });
|
||||
trainee = await createUserWithToken({ firstName: 'ShareTrainee' });
|
||||
stranger = await createUserWithToken({ firstName: 'ShareStranger' });
|
||||
// ACTIVE coaching: trainer -> trainee
|
||||
await prisma.coaching.create({
|
||||
data: {
|
||||
trainerId: trainer.user.id,
|
||||
userId: trainee.user.id,
|
||||
invitedBy: trainer.user.id,
|
||||
status: 'ACTIVE',
|
||||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
const ex = await createExercise();
|
||||
exerciseId = ex.id;
|
||||
// plan należy do podopiecznego (właściciel = podopieczny)
|
||||
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${trainee.token}`).send(body('Plan do udostępnienia'));
|
||||
expect(res.status).toBe(201);
|
||||
planId = res.body.plan.id;
|
||||
});
|
||||
|
||||
it('non-owner (trainer) cannot share the plan (403)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainer.token}`)
|
||||
.send({ userId: trainee.user.id });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error.message).toBe('Only the plan owner can share the plan');
|
||||
});
|
||||
|
||||
it('owner cannot share the plan with themselves (400)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: trainee.user.id });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('Cannot share a plan with yourself');
|
||||
});
|
||||
|
||||
it('owner cannot share with a user without an active coaching relation (400)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: stranger.user.id });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('No active coaching relation with this user');
|
||||
});
|
||||
|
||||
it('owner shares the plan with the trainer (201)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: trainer.user.id });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.share).toMatchObject({ id: expect.any(String) });
|
||||
});
|
||||
|
||||
it('duplicate share is rejected with 409', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: trainer.user.id });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error.message).toBe('Plan is already shared with this user');
|
||||
});
|
||||
|
||||
it('the owner sees the recipients in the plan detail', async () => {
|
||||
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.plan.shares).toEqual([
|
||||
{ userId: trainer.user.id, user: { id: trainer.user.id, firstName: 'ShareTrainer', lastName: null } },
|
||||
]);
|
||||
expect(res.body.plan.canManage).toBe(true);
|
||||
});
|
||||
|
||||
it('the recipient sees the plan in /plans/shared-with-me', async () => {
|
||||
const res = await app.get('/api/v1/plans/shared-with-me').set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
const found = res.body.plans.find((p: { id: string }) => p.id === planId);
|
||||
expect(found).toBeTruthy();
|
||||
expect(found.sharedBy).toMatchObject({ id: trainee.user.id, firstName: 'ShareTrainee' });
|
||||
expect(found.progress).toEqual({ completed: 0, total: 1, percent: 0 });
|
||||
});
|
||||
|
||||
it('the trainee sees the trainer in /me/trainers', async () => {
|
||||
const res = await app.get('/api/v1/me/trainers').set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.trainers).toEqual([
|
||||
{ id: trainer.user.id, firstName: 'ShareTrainer', lastName: null, nickname: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('the trainer (ACTIVE coaching) still manages the plan via the owner route? NO — owner route is owner-only (404)', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${trainer.token}`)
|
||||
.send(body('Trener edytuje'));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('the share survives the coaching ending: recipient keeps read-only access', async () => {
|
||||
await prisma.coaching.updateMany({
|
||||
where: { trainerId: trainer.user.id, userId: trainee.user.id },
|
||||
data: { status: 'ARCHIVED' },
|
||||
});
|
||||
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.plan.canManage).toBe(false);
|
||||
expect(res.body.plan.shares).toBeUndefined();
|
||||
});
|
||||
|
||||
it('a stranger gets 404 for the shared plan', async () => {
|
||||
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${stranger.token}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('the owner revokes the share (204) and the recipient loses access', async () => {
|
||||
const res = await app
|
||||
.delete(`/api/v1/plans/${planId}/share/${trainer.user.id}`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(204);
|
||||
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(detail.status).toBe(404);
|
||||
|
||||
const list = await app.get('/api/v1/plans/shared-with-me').set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(list.body.plans.find((p: { id: string }) => p.id === planId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('revoking a missing share is 404', async () => {
|
||||
const res = await app
|
||||
.delete(`/api/v1/plans/${planId}/share/${trainer.user.id}`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('plans: PATCH with startDate (update + activate)', () => {
|
||||
let app: ReturnType<typeof buildApp>;
|
||||
let token: string;
|
||||
let userId: string;
|
||||
let exerciseId: string;
|
||||
let planId: string;
|
||||
|
||||
const body = (title: string, weeksCount = 1) => ({
|
||||
title,
|
||||
weeksCount,
|
||||
weeks: [
|
||||
{
|
||||
index: 0,
|
||||
days: [
|
||||
{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
app = buildApp();
|
||||
const reg = await createUserWithToken();
|
||||
token = reg.token;
|
||||
userId = reg.user.id;
|
||||
const ex = await createExercise();
|
||||
exerciseId = ex.id;
|
||||
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body('Draft do aktywacji'));
|
||||
expect(res.status).toBe(201);
|
||||
planId = res.body.plan.id;
|
||||
});
|
||||
|
||||
it('PATCH without startDate keeps the plan DRAFT', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send(body('Draft v2'));
|
||||
expect(res.status).toBe(200);
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
expect(detail.body.plan.status).toBe('DRAFT');
|
||||
expect(detail.body.plan.startDate).toBeNull();
|
||||
});
|
||||
|
||||
it('PATCH with a non-Monday startDate is rejected with 400', async () => {
|
||||
const [y, m, d] = mondayIso(1).split('-').map(Number);
|
||||
const tuesday = new Date(y, m - 1, d + 1);
|
||||
const tuesdayIso = `${tuesday.getFullYear()}-${String(tuesday.getMonth() + 1).padStart(2, '0')}-${String(tuesday.getDate()).padStart(2, '0')}`;
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Wtorek'), startDate: tuesdayIso });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('Start date must be a Monday');
|
||||
});
|
||||
|
||||
it('PATCH with a past-week startDate is rejected with 400', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Miniony'), startDate: mondayIso(-1) });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('Start date cannot be in the past');
|
||||
});
|
||||
|
||||
it('PATCH with startDate updates the structure and activates the plan', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Aktywowany'), startDate: mondayIso(1) });
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
expect(detail.body.plan.status).toBe('ACTIVE');
|
||||
expect(detail.body.plan.title).toBe('Aktywowany');
|
||||
expect(detail.body.plan.startDate).not.toBeNull();
|
||||
const localDate = (iso: string) => {
|
||||
const d = new Date(iso);
|
||||
return [d.getFullYear(), d.getMonth() + 1, d.getDate()];
|
||||
};
|
||||
const [sy, sm, sd] = mondayIso(1).split('-').map(Number);
|
||||
const day1 = detail.body.plan.weeks.find((w: { index: number }) => w.index === 0).days.find(
|
||||
(d: { dayOfWeek: number }) => d.dayOfWeek === 1,
|
||||
);
|
||||
expect(localDate(day1.date)).toEqual([sy, sm, sd]);
|
||||
});
|
||||
|
||||
it('PATCH with startDate while another plan is active is rejected with 409', async () => {
|
||||
const created = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body('Konflikt'));
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${created.body.plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Konflikt'), startDate: mondayIso(2) });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error.message).toBe('User already has an active plan');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,11 +2,16 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
abandonPlan,
|
||||
activatePlan,
|
||||
assertPlanOwner,
|
||||
completePlan,
|
||||
createPlan,
|
||||
deletePlan,
|
||||
getMyTrainers,
|
||||
getPlan,
|
||||
listPlans,
|
||||
listSharedWithMe,
|
||||
sharePlan,
|
||||
unsharePlan,
|
||||
updatePlan,
|
||||
} from '../../src/services/plans.js';
|
||||
|
||||
@@ -26,8 +31,14 @@ function mockPrisma() {
|
||||
delete: vi.fn(),
|
||||
},
|
||||
exercise: { findMany: vi.fn() },
|
||||
coaching: { findUnique: vi.fn() },
|
||||
coaching: { findUnique: vi.fn(), findMany: vi.fn() },
|
||||
planWeek: { findMany: vi.fn() },
|
||||
planShare: {
|
||||
findUnique: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(async (cb: (tx: typeof tx) => Promise<void>) => cb(tx)),
|
||||
};
|
||||
return { prisma, tx };
|
||||
@@ -244,15 +255,24 @@ describe('listPlans', () => {
|
||||
describe('assertPlanAccess (via getPlan)', () => {
|
||||
it('allows the owner (trainee) to read the plan', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||||
await expect(getPlan(prisma, 'p1', 'u1')).resolves.toMatchObject({ plan: { id: 'p1' } });
|
||||
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' });
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||||
...draftPlan,
|
||||
userId: 'trainee-1',
|
||||
shares: [],
|
||||
});
|
||||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||||
await expect(getPlan(prisma, 'p1', 'trainer-1')).resolves.toMatchObject({ plan: { id: 'p1' } });
|
||||
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 () => {
|
||||
@@ -272,10 +292,25 @@ describe('assertPlanAccess (via getPlan)', () => {
|
||||
await expect(getPlan(prisma, 'p1', 'trainer-1')).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it('rejects an unrelated user (no coaching relation) with 404', async () => {
|
||||
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 });
|
||||
});
|
||||
|
||||
@@ -286,6 +321,29 @@ describe('assertPlanAccess (via getPlan)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -325,3 +383,264 @@ describe('createPlan creatorId', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updatePlan (startDate = aktualizacja + aktywacja)', () => {
|
||||
it('bez startDate: aktualizuje strukturę, 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' }),
|
||||
});
|
||||
// bez aktywacji — brak wyliczania dat
|
||||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('z startDate: aktualizuje strukturę i aktywuje plan (daty wyliczone)', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
prisma.trainingPlan.findFirst.mockResolvedValue(null);
|
||||
prisma.planWeek.findMany.mockResolvedValue([
|
||||
{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }] },
|
||||
]);
|
||||
tx.trainingPlan.update.mockResolvedValue({});
|
||||
tx.planDay.update.mockResolvedValue({});
|
||||
|
||||
const start = mondayIso(1);
|
||||
const [y, m, d] = start.split('-').map(Number);
|
||||
await updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: start,
|
||||
});
|
||||
// aktywacja: daty dni + status ACTIVE
|
||||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||||
where: { id: 'd1' },
|
||||
data: { date: new Date(y, m - 1, d) },
|
||||
});
|
||||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||||
where: { id: 'p1' },
|
||||
data: { status: 'ACTIVE', startDate: new Date(y, m - 1, d) },
|
||||
});
|
||||
});
|
||||
|
||||
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 gdy właściciel ma już aktywny plan: 409', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
prisma.trainingPlan.findFirst.mockResolvedValue({ id: 'other-active' });
|
||||
await expect(
|
||||
updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: mondayIso(1),
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 409, message: 'User already has an active plan' });
|
||||
});
|
||||
});
|
||||
|
||||
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' } });
|
||||
});
|
||||
|
||||
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 }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user