import { describe, it, expect, beforeAll } from 'vitest'; import { prisma } from '../../src/lib/prisma.js'; import { buildApp, createExercise, createMembership, createUserWithToken, rand, seedPlan, seedSession, } from '../helpers.js'; describe('comments — under executed exercises', () => { let app: ReturnType; let trainer: { id: string; token: string }; let trainee: { id: string; token: string }; let gymId: string; let traineeSessionId: string; let traineeExerciseId: string; let traineeInProgressSessionId: string; let traineeAbandonedSessionId: string; let traineeAbandonedExerciseId: string; let traineeCommentId: string; let traineeExerciseName: string; let mySessionId: string; let myExerciseId: string; beforeAll(async () => { app = buildApp(); const t = await createUserWithToken({ firstName: 'Tomasz' }); const tr = await createUserWithToken({ firstName: 'Anna' }); const gym = await prisma.gym.create({ data: { name: `Cmt Gym ${rand()}` } }); gymId = gym.id; await createMembership(t.user.id, gymId, ['TRAINER']); await createMembership(tr.user.id, gymId, ['MEMBER']); trainer = { id: t.user.id, token: t.token }; trainee = { id: tr.user.id, token: tr.token }; // ACTIVE relation. const invite = await app .post('/api/v1/trainer/invitations') .set('Authorization', `Bearer ${trainer.token}`) .send({ userId: trainee.id }); expect(invite.status).toBe(201); const accept = await app .post(`/api/v1/trainer/invitations/${invite.body.coaching.id}/accept`) .set('Authorization', `Bearer ${trainee.token}`); expect(accept.status).toBe(200); // Trainee: COMPLETED session + IN_PROGRESS session. const exercise = await createExercise(); traineeExerciseName = exercise.name; const plan = await seedPlan({ userId: trainee.id, weeks: [ { index: 0, days: [ { dayOfWeek: 1, exercises: [ { exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10, loadKg: 60 }] }, ], }, ], }, ], }); const day = plan.weeks[0].days[0]; const done = await seedSession(day.id, { status: 'COMPLETED', exercises: [ { exerciseId: exercise.id, planExerciseId: day.exercises[0].id, order: 0, sets: [{ planSetId: day.exercises[0].sets[0].id, reps: 10 }], }, ], }); traineeSessionId = done.id; traineeExerciseId = done.exercises[0].id; const ongoing = await seedSession(day.id, { status: 'IN_PROGRESS' }); traineeInProgressSessionId = ongoing.id; const abandoned = await seedSession(day.id, { status: 'ABANDONED', exercises: [ { exerciseId: exercise.id, planExerciseId: day.exercises[0].id, order: 0, sets: [{ planSetId: day.exercises[0].sets[0].id, reps: 4 }], }, ], }); traineeAbandonedSessionId = abandoned.id; traineeAbandonedExerciseId = abandoned.exercises[0].id; // Trainer's own completed session (for /me/comments). const tExercise = await createExercise(); const tPlan = await seedPlan({ userId: trainer.id, weeks: [ { index: 0, days: [ { dayOfWeek: 3, exercises: [{ exerciseId: tExercise.id, order: 0, sets: [{ index: 0, reps: 5, loadKg: 20 }] }], }, ], }, ], }); const tDay = tPlan.weeks[0].days[0]; const tDone = await seedSession(tDay.id, { status: 'COMPLETED', exercises: [ { exerciseId: tExercise.id, planExerciseId: tDay.exercises[0].id, order: 0, sets: [{ planSetId: tDay.exercises[0].sets[0].id, reps: 5 }], }, ], }); mySessionId = tDone.id; myExerciseId = tDone.exercises[0].id; }); describe('POST /trainer/trainees/:userId/comments', () => { it('creates a trainer comment anchored to the trainee session + exercise', async () => { const res = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'Świetna forma!', sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId }); expect(res.status).toBe(201); expect(res.body.comment).toMatchObject({ authorId: trainer.id, targetUserId: trainee.id, sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId, body: 'Świetna forma!', }); traineeCommentId = res.body.comment.id; }); it('rejects an IN_PROGRESS session with 400', async () => { const res = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'za wcześnie', sessionId: traineeInProgressSessionId }); expect(res.status).toBe(400); expect(res.body.error.code).toBe('SESSION_IN_PROGRESS'); }); it('creates a trainer comment on an ABANDONED session (with feed notification)', async () => { const before = await app .get('/api/v1/me/feed/unread-count') .set('Authorization', `Bearer ${trainee.token}`); expect(before.status).toBe(200); const res = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'Nota do porzuconego treningu', sessionId: traineeAbandonedSessionId, sessionExerciseId: traineeAbandonedExerciseId, }); expect(res.status).toBe(201); expect(res.body.comment).toMatchObject({ authorId: trainer.id, targetUserId: trainee.id, sessionId: traineeAbandonedSessionId, sessionExerciseId: traineeAbandonedExerciseId, }); const note = await prisma.notification.findFirst({ where: { userId: trainee.id, type: 'TRAINER_COMMENT' }, orderBy: { createdAt: 'desc' }, }); expect(note).toBeTruthy(); expect(note!.payload).toMatchObject({ sessionId: traineeAbandonedSessionId }); const feed = await app.get('/api/v1/me/feed').set('Authorization', `Bearer ${trainee.token}`); expect(feed.status).toBe(200); const item = feed.body.items.find((i: { id: string }) => i.id === note!.id); expect(item).toMatchObject({ source: 'notification', type: 'TRAINER_COMMENT', read: false, payload: { sessionId: traineeAbandonedSessionId }, }); const after = await app .get('/api/v1/me/feed/unread-count') .set('Authorization', `Bearer ${trainee.token}`); expect(after.status).toBe(200); expect(after.body.unreadCount).toBe(before.body.unreadCount + 1); // The deeplink (/profile/history?session=...) must land on a session that // is really returned by the trainee's history. const history = await app .get('/api/v1/me/history') .set('Authorization', `Bearer ${trainee.token}`); expect(history.status).toBe(200); const session = history.body.sessions.find((s: { id: string }) => s.id === traineeAbandonedSessionId); expect(session).toBeTruthy(); const exercise = session.exercises.find( (e: { id: string }) => e.id === traineeAbandonedExerciseId, ); expect(exercise.comments).toEqual([ expect.objectContaining({ body: 'Nota do porzuconego treningu', authorName: 'Tomasz' }), ]); }); it('rejects a session of another user with 404', async () => { const res = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'obca sesja', sessionId: mySessionId }); expect(res.status).toBe(404); }); it('rejects an exercise from a different session with 400', async () => { const res = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'obce ćwiczenie', sessionId: traineeSessionId, sessionExerciseId: myExerciseId }); expect(res.status).toBe(400); }); it('rejects a non-trainee with 404', async () => { const stranger = await createUserWithToken({ firstName: 'Zuza' }); const res = await app .post(`/api/v1/trainer/trainees/${stranger.user.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'nie jest podopiecznym' }); expect(res.status).toBe(404); }); it('rejects a user without the TRAINER role with 403', async () => { const res = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainee.token}`) .send({ body: 'nie jestem trenerem' }); expect(res.status).toBe(403); }); }); describe('comments in history (both sides)', () => { it('shows the trainer comment in /trainer/trainees/:id/history', async () => { const res = await app .get(`/api/v1/trainer/trainees/${trainee.id}/history`) .set('Authorization', `Bearer ${trainer.token}`); expect(res.status).toBe(200); const session = res.body.sessions.find((s: { id: string }) => s.id === traineeSessionId); expect(session).toBeTruthy(); const exercise = session.exercises.find((e: { id: string }) => e.id === traineeExerciseId); // Autor (trener) zawsze widzi własny komentarz jako przeczytany. expect(exercise.comments).toEqual([ expect.objectContaining({ id: traineeCommentId, authorName: 'Tomasz', read: true }), ]); }); it('shows the same comment in the trainee /me/history', async () => { const res = await app.get('/api/v1/me/history').set('Authorization', `Bearer ${trainee.token}`); expect(res.status).toBe(200); const session = res.body.sessions.find((s: { id: string }) => s.id === traineeSessionId); const exercise = session.exercises.find((e: { id: string }) => e.id === traineeExerciseId); // Dla adresata komentarz trenera jest nieprzeczytany (brak wiersza CommentRead). expect(exercise.comments).toEqual([ expect.objectContaining({ id: traineeCommentId, authorName: 'Tomasz', read: false }), ]); }); }); describe('TRAINER_COMMENT notifications (feed)', () => { let noteCommentId: string; let notificationId: string; it('notifies the trainee with a TRAINER_COMMENT entry after a trainer comment', async () => { const before = await app .get('/api/v1/me/feed/unread-count') .set('Authorization', `Bearer ${trainee.token}`); expect(before.status).toBe(200); const res = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'Zwróć uwagę na kolana', sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId }); expect(res.status).toBe(201); noteCommentId = res.body.comment.id; const note = await prisma.notification.findFirst({ where: { userId: trainee.id, type: 'TRAINER_COMMENT' }, orderBy: { createdAt: 'desc' }, }); expect(note).toBeTruthy(); notificationId = note!.id; expect(note!.title).toBe(`Trener Tomasz: komentarz przy ćwiczeniu ${traineeExerciseName}`); expect(note!.payload).toMatchObject({ sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId, exerciseName: traineeExerciseName, commentId: noteCommentId, authorName: 'Tomasz', preview: 'Zwróć uwagę na kolana', }); const feed = await app .get('/api/v1/me/feed') .set('Authorization', `Bearer ${trainee.token}`); expect(feed.status).toBe(200); const item = feed.body.items.find((i: { id: string }) => i.id === notificationId); expect(item).toMatchObject({ source: 'notification', type: 'TRAINER_COMMENT', read: false, payload: { sessionId: traineeSessionId }, }); const after = await app .get('/api/v1/me/feed/unread-count') .set('Authorization', `Bearer ${trainee.token}`); expect(after.status).toBe(200); expect(after.body.unreadCount).toBe(before.body.unreadCount + 1); }); it('keeps the notification after the trainer deletes the comment', async () => { const del = await app .delete(`/api/v1/trainer/trainees/${trainee.id}/comments/${noteCommentId}`) .set('Authorization', `Bearer ${trainer.token}`); expect(del.status).toBe(204); const note = await prisma.notification.findUnique({ where: { id: notificationId } }); expect(note).toBeTruthy(); }); it('does not notify the trainee for their own comment (addMyComment)', async () => { const count = await prisma.notification.count({ where: { userId: trainee.id, type: 'TRAINER_COMMENT' }, }); const res = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainee.token}`) .send({ body: 'własna notatka', sessionId: traineeSessionId }); expect(res.status).toBe(201); const after = await prisma.notification.count({ where: { userId: trainee.id, type: 'TRAINER_COMMENT' }, }); expect(after).toBe(count); }); }); describe('USER_COMMENT notifications (feed symmetry) + read marking', () => { let traineeNoteCommentId: string; it('notifies the active coach when the trainee comments on their own session', async () => { const before = await app .get('/api/v1/me/feed/unread-count') .set('Authorization', `Bearer ${trainer.token}`); expect(before.status).toBe(200); const res = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainee.token}`) .send({ body: 'Barki mnie bolą po wyciskaniu', sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId, }); expect(res.status).toBe(201); traineeNoteCommentId = res.body.comment.id; const note = await prisma.notification.findFirst({ where: { userId: trainer.id, type: 'USER_COMMENT' }, orderBy: { createdAt: 'desc' }, }); expect(note).toBeTruthy(); expect(note!.title).toBe(`Anna: komentarz przy ćwiczeniu ${traineeExerciseName}`); expect(note!.payload).toMatchObject({ sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId, exerciseName: traineeExerciseName, commentId: traineeNoteCommentId, traineeId: trainee.id, authorName: 'Anna', preview: 'Barki mnie bolą po wyciskaniu', }); const feed = await app .get('/api/v1/me/feed') .set('Authorization', `Bearer ${trainer.token}`); const item = feed.body.items.find((i: { id: string }) => i.id === note!.id); expect(item).toMatchObject({ source: 'notification', type: 'USER_COMMENT', read: false }); const after = await app .get('/api/v1/me/feed/unread-count') .set('Authorization', `Bearer ${trainer.token}`); expect(after.body.unreadCount).toBe(before.body.unreadCount + 1); }); it('coach marks the trainee comment read; flag flips in trainee history', async () => { const before = await app .get(`/api/v1/trainer/trainees/${trainee.id}/history`) .set('Authorization', `Bearer ${trainer.token}`); const exBefore = before.body.sessions .find((s: { id: string }) => s.id === traineeSessionId) .exercises.find((e: { id: string }) => e.id === traineeExerciseId); expect(exBefore.comments.find((c: { id: string }) => c.id === traineeNoteCommentId).read).toBe( false, ); const mark = await app .post('/api/v1/me/comments/read') .set('Authorization', `Bearer ${trainer.token}`) .send({ commentIds: [traineeNoteCommentId] }); expect(mark.status).toBe(200); const after = await app .get(`/api/v1/trainer/trainees/${trainee.id}/history`) .set('Authorization', `Bearer ${trainer.token}`); const exAfter = after.body.sessions .find((s: { id: string }) => s.id === traineeSessionId) .exercises.find((e: { id: string }) => e.id === traineeExerciseId); expect(exAfter.comments.find((c: { id: string }) => c.id === traineeNoteCommentId).read).toBe( true, ); // Wiersz CommentRead należy do widza (trenera), nie do autora. const rows = await prisma.commentRead.findMany({ where: { commentId: traineeNoteCommentId }, }); expect(rows).toHaveLength(1); expect(rows[0]).toMatchObject({ commentId: traineeNoteCommentId, userId: trainer.id }); }); it('trainee marks the trainer comment read; unknown ids are ignored (idempotent)', async () => { const mark = await app .post('/api/v1/me/comments/read') .set('Authorization', `Bearer ${trainee.token}`) .send({ commentIds: [traineeCommentId, traineeCommentId, 'nieistniejacy-id'] }); expect(mark.status).toBe(200); const hist = await app.get('/api/v1/me/history').set('Authorization', `Bearer ${trainee.token}`); const exercise = hist.body.sessions .find((s: { id: string }) => s.id === traineeSessionId) .exercises.find((e: { id: string }) => e.id === traineeExerciseId); expect(exercise.comments.find((c: { id: string }) => c.id === traineeCommentId).read).toBe( true, ); }); it('never writes read rows for the author or for non-participants', async () => { // Własny komentarz: autor widzi go jako przeczytany bez wiersza CommentRead. const own = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'własna notatka trenera', sessionId: mySessionId, sessionExerciseId: myExerciseId }); expect(own.status).toBe(201); const ownMark = await app .post('/api/v1/me/comments/read') .set('Authorization', `Bearer ${trainer.token}`) .send({ commentIds: [own.body.comment.id] }); expect(ownMark.status).toBe(200); expect( await prisma.commentRead.count({ where: { commentId: own.body.comment.id, userId: trainer.id }, }), ).toBe(0); const ownHist = await app .get('/api/v1/me/history') .set('Authorization', `Bearer ${trainer.token}`); const ownExercise = ownHist.body.sessions .find((s: { id: string }) => s.id === mySessionId) .exercises.find((e: { id: string }) => e.id === myExerciseId); expect(ownExercise.comments.find((c: { id: string }) => c.id === own.body.comment.id).read).toBe( true, ); // Postronny: podopieczny nie oznaczy komentarza trenera w sesji trenera. const outsider = await app .post('/api/v1/me/comments/read') .set('Authorization', `Bearer ${trainee.token}`) .send({ commentIds: [own.body.comment.id] }); expect(outsider.status).toBe(200); expect(await prisma.commentRead.count({ where: { commentId: own.body.comment.id } })).toBe( 0, ); }); it('no coach (no ACTIVE coaching) = no USER_COMMENT notification', async () => { const solo = await createUserWithToken({ firstName: 'Solo' }); const soloExercise = await createExercise(); const soloPlan = await seedPlan({ userId: solo.user.id, weeks: [ { index: 0, days: [ { dayOfWeek: 2, exercises: [ { exerciseId: soloExercise.id, order: 0, sets: [{ index: 0, reps: 8, loadKg: 30 }] }, ], }, ], }, ], }); const soloDay = soloPlan.weeks[0].days[0]; const soloSession = await seedSession(soloDay.id, { status: 'COMPLETED', exercises: [ { exerciseId: soloExercise.id, planExerciseId: soloDay.exercises[0].id, order: 0, sets: [{ planSetId: soloDay.exercises[0].sets[0].id, reps: 8 }], }, ], }); const before = await prisma.notification.count({ where: { type: 'USER_COMMENT' } }); const res = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${solo.token}`) .send({ body: 'bez trenera', sessionId: soloSession.id }); expect(res.status).toBe(201); expect(await prisma.notification.count({ where: { type: 'USER_COMMENT' } })).toBe(before); }); }); describe('POST /me/comments', () => { it('creates a comment on my own session + exercise', async () => { const res = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'Mój własny notatka', sessionId: mySessionId, sessionExerciseId: myExerciseId }); expect(res.status).toBe(201); expect(res.body.comment).toMatchObject({ authorId: trainer.id, targetUserId: trainer.id, sessionId: mySessionId, sessionExerciseId: myExerciseId, }); }); it('rejects a session of another user with 404', async () => { const res = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'obca sesja', sessionId: traineeSessionId }); expect(res.status).toBe(404); }); it('rejects a missing sessionId with 400', async () => { const res = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'bez sesji' }); expect(res.status).toBe(400); }); it('accepts a comment on my own ABANDONED session and does not notify the author', async () => { const count = await prisma.notification.count({ where: { userId: trainee.id, type: 'TRAINER_COMMENT' }, }); const res = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainee.token}`) .send({ body: 'własna notatka do porzuconego', sessionId: traineeAbandonedSessionId }); expect(res.status).toBe(201); expect(res.body.comment).toMatchObject({ authorId: trainee.id, targetUserId: trainee.id, sessionId: traineeAbandonedSessionId, }); const after = await prisma.notification.count({ where: { userId: trainee.id, type: 'TRAINER_COMMENT' }, }); expect(after).toBe(count); }); }); describe('DELETE comments', () => { it('deletes the trainer comment (author only)', async () => { const res = await app .delete(`/api/v1/trainer/trainees/${trainee.id}/comments/${traineeCommentId}`) .set('Authorization', `Bearer ${trainer.token}`); expect(res.status).toBe(204); }); it('rejects deletion of a comment authored by the trainee with 404', async () => { const created = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainee.token}`) .send({ body: 'własny komentarz podopiecznego', sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId }); expect(created.status).toBe(201); const res = await app .delete(`/api/v1/trainer/trainees/${trainee.id}/comments/${created.body.comment.id}`) .set('Authorization', `Bearer ${trainer.token}`); expect(res.status).toBe(404); }); it('deletes my own comment via /me/comments/:id', async () => { const created = await app .post('/api/v1/me/comments') .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'do usunięcia', sessionId: mySessionId, sessionExerciseId: myExerciseId }); const res = await app .delete(`/api/v1/me/comments/${created.body.comment.id}`) .set('Authorization', `Bearer ${trainer.token}`); expect(res.status).toBe(204); }); it('rejects deleting someone else comment via /me/comments/:id with 404', async () => { const created = await app .post(`/api/v1/trainer/trainees/${trainee.id}/comments`) .set('Authorization', `Bearer ${trainer.token}`) .send({ body: 'komentarz trenera', sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId }); const res = await app .delete(`/me/comments/${created.body.comment.id}`) .set('Authorization', `Bearer ${trainee.token}`); expect(res.status).toBe(404); }); }); });