Api+App: komentarze usera - statusy przeczytania i typ USER_COMMENT (feed, profil, panel trenera)

This commit is contained in:
tisachi
2026-11-09 03:39:29 +01:00
parent 08e0c4080e
commit 7a9f438cc7
25 changed files with 801 additions and 88 deletions

View File

@@ -0,0 +1,20 @@
-- AlterEnum
ALTER TYPE "NotificationType" ADD VALUE 'USER_COMMENT';
-- CreateTable
CREATE TABLE "CommentRead" (
"commentId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "CommentRead_pkey" PRIMARY KEY ("commentId","userId")
);
-- CreateIndex
CREATE INDEX "CommentRead_userId_idx" ON "CommentRead"("userId");
-- AddForeignKey
ALTER TABLE "CommentRead" ADD CONSTRAINT "CommentRead_commentId_fkey" FOREIGN KEY ("commentId") REFERENCES "Comment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CommentRead" ADD CONSTRAINT "CommentRead_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -157,6 +157,7 @@ model User {
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
commentReads CommentRead[]
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
@@ -230,10 +231,25 @@ model Comment {
author User @relation("CommentAuthor", fields: [authorId], references: [id], onDelete: Cascade)
target User @relation("CommentTarget", fields: [targetUserId], references: [id], onDelete: Cascade)
sessionExercise SessionExercise? @relation(fields: [sessionExerciseId], references: [id], onDelete: SetNull)
reads CommentRead[]
@@index([targetUserId, createdAt])
}
/// Oznaczenie przeczytania komentarza per widz (wzór ConversationRead) — do
/// licznika nieprzeczytanych w historii. Autor nigdy nie potrzebuje wiersza.
model CommentRead {
commentId String
userId String
createdAt DateTime @default(now())
comment Comment @relation(fields: [commentId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@id([commentId, userId])
@@index([userId])
}
/// Wiadomość w wątku trener↔podopieczny (per Coaching).
model Message {
id String @id @default(cuid())
@@ -270,6 +286,7 @@ enum NotificationType {
PLAN_SHARED
GYM_DELETED
TRAINER_COMMENT
USER_COMMENT
}
/// Osobiste powiadomienie generowane przez system. `payload` jest self-contained

View File

@@ -18,7 +18,7 @@ import {
import { getFocusChain } from '../services/focusChain.js';
import { getMyTrainers } from '../services/plans.js';
import { getActiveSession } from '../services/sessions.js';
import { addMyComment, deleteMyComment } from '../services/comments.js';
import { addMyComment, deleteMyComment, markCommentsRead } from '../services/comments.js';
import { getExerciseProgress } from '../services/exerciseProgress.js';
import { getUserStats } from '../services/userStats.js';
import { logActivity } from '../services/audit.js';
@@ -98,6 +98,10 @@ const myCommentSchema = z.object({
sessionExerciseId: z.string().min(1).optional(),
});
const readCommentsSchema = z.object({
commentIds: z.array(z.string().min(1)).min(1).max(200),
});
/** Zakres statystyk osobistych: `all` = pełna historia (brak filtra czasowego). */
export const statsQuerySchema = z.object({
range: z.enum(['30', '90', '365', 'all']).default('90'),
@@ -349,6 +353,26 @@ export function createMeRoutes({ prisma }: AppDeps) {
}),
);
/**
* @openapi
* /me/comments/read:
* post:
* summary: Mark comments as read for the caller (CommentRead rows)
* description: Only comments the caller participates in (author, target, or authored by an active trainee). Idempotent; own comments are always read.
* tags: [Profile]
* responses:
* 200: { description: OK }
*/
router.post(
'/comments/read',
validate(readCommentsSchema),
asyncHandler(async (req, res) => {
const { commentIds } = req.body as z.infer<typeof readCommentsSchema>;
const result = await markCommentsRead(prisma, req.user!.id, commentIds);
res.json(result);
}),
);
/**
* @openapi
* /me/comments/{commentId}:

View File

@@ -1,4 +1,4 @@
import type { PrismaClient } from '@prisma/client';
import type { Prisma, PrismaClient } from '@prisma/client';
import { badRequest, notFound, sessionInProgress } from '../lib/errors.js';
import { assertActiveTrainee } from './trainer.js';
import { createNotification } from './feed.js';
@@ -9,10 +9,17 @@ export interface CommentInput {
sessionExerciseId?: string;
}
interface SessionAnchor {
session: { id: string };
/** Ćwiczenie z nazwą, gdy komentarz zakotwiczony przy ćwiczeniu. */
exercise: { name: string; nameEn: string | null } | null;
}
/**
* The anchor must be a COMPLETED or ABANDONED session of the owner (only an
* IN_PROGRESS session is blocked); the exercise (when given) must belong to
* that session and not be removed.
* that session and not be removed. Returns the exercise name for the
* notification payload.
*/
async function assertSessionAnchor(prisma: PrismaClient, ownerId: string, input: CommentInput) {
if (!input.sessionId) throw badRequest('sessionId is required');
@@ -23,12 +30,33 @@ async function assertSessionAnchor(prisma: PrismaClient, ownerId: string, input:
// A session of another user is indistinguishable from a missing one.
if (!session || session.day.week.plan.userId !== ownerId) throw notFound('Session not found');
if (session.status === 'IN_PROGRESS') throw sessionInProgress();
let exercise: SessionAnchor['exercise'] = null;
if (input.sessionExerciseId) {
const se = await prisma.sessionExercise.findFirst({
where: { id: input.sessionExerciseId, sessionId: session.id },
include: { exercise: { select: { name: true, nameEn: true } } },
});
if (!se || se.removed) throw badRequest('Exercise does not belong to this session');
exercise = se.exercise;
}
return { session, exercise };
}
function fullName(user: { firstName: string | null; lastName: string | null } | null): string {
return user ? [user.firstName, user.lastName].join(' ').trim() : '';
}
/** Tytuł wpisu feedu w formie bezosobowej (płeć autora nierozpoznawalna). */
function titleFor(actor: string, exerciseName: string | null): string {
const who = actor || 'Ktoś';
return exerciseName
? `${who}: komentarz przy ćwiczeniu ${exerciseName}`
: `${who}: komentarz do treningu`;
}
/** Zwięzły fragment treści komentarza do karty feedu (przeżywa usunięcie komentarza). */
function commentPreview(body: string): string {
return body.length > 140 ? `${body.slice(0, 140).trimEnd()}…` : body;
}
/** Trainer comment on the trainee (target = trainee, author = trainer). */
@@ -39,7 +67,7 @@ export async function addTraineeComment(
input: CommentInput,
) {
await assertActiveTrainee(prisma, trainerId, traineeId);
await assertSessionAnchor(prisma, traineeId, input);
const { session, exercise } = await assertSessionAnchor(prisma, traineeId, input);
const comment = await prisma.comment.create({
data: {
authorId: trainerId,
@@ -50,22 +78,26 @@ export async function addTraineeComment(
},
});
// Notification for the trainee ("Aktualności" feed). The payload is a
// self-contained snapshot (GYM_DELETED pattern) so it survives comment deletion.
// self-contained snapshot (GYM_DELETED pattern) so it survives comment
// deletion; sessionExerciseId + exerciseName let the deeplink open the
// exercise dialog with the comment directly.
const trainer = await prisma.user.findUnique({
where: { id: trainerId },
select: { firstName: true, lastName: true, nickname: true },
});
const trainerName =
(trainer ? [trainer.firstName, trainer.lastName].join(' ').trim() : '') ||
trainer?.nickname ||
'';
const trainerName = fullName(trainer) || trainer?.nickname || '';
await createNotification(prisma, {
userId: traineeId,
type: 'TRAINER_COMMENT',
title: trainerName
? `Trener ${trainerName} dodał komentarz do treningu`
: 'Trener dodał komentarz do treningu',
payload: { sessionId: input.sessionId ?? null, trainerName },
title: titleFor(trainerName ? `Trener ${trainerName}` : 'Trener', exercise?.name ?? null),
payload: {
sessionId: session.id,
sessionExerciseId: input.sessionExerciseId ?? null,
exerciseName: exercise?.name ?? null,
commentId: comment.id,
authorName: trainerName,
preview: commentPreview(input.body),
},
});
return { comment };
}
@@ -85,9 +117,13 @@ export async function deleteTraineeComment(
await prisma.comment.delete({ where: { id: comment.id } });
}
/** User comment on their own session (target = author = the user). */
/**
* User comment on their own session (target = author = the user). Each active
* coach of the user gets a USER_COMMENT notification so the trainer also sees
* new trainee comments in "Aktualności" (feed symmetry).
*/
export async function addMyComment(prisma: PrismaClient, userId: string, input: CommentInput) {
await assertSessionAnchor(prisma, userId, input);
const { session, exercise } = await assertSessionAnchor(prisma, userId, input);
const comment = await prisma.comment.create({
data: {
authorId: userId,
@@ -97,6 +133,32 @@ export async function addMyComment(prisma: PrismaClient, userId: string, input:
body: input.body,
},
});
const coaches = await prisma.coaching.findMany({
where: { userId, status: 'ACTIVE' },
select: { trainerId: true },
});
if (coaches.length > 0) {
const author = await prisma.user.findUnique({
where: { id: userId },
select: { firstName: true, lastName: true, nickname: true },
});
const authorName = fullName(author) || author?.nickname || '';
const title = titleFor(authorName, exercise?.name ?? null);
const payload: Prisma.InputJsonObject = {
sessionId: session.id,
sessionExerciseId: input.sessionExerciseId ?? null,
exerciseName: exercise?.name ?? null,
commentId: comment.id,
authorName,
traineeId: userId,
preview: commentPreview(input.body),
};
await Promise.all(
coaches.map(({ trainerId }) =>
createNotification(prisma, { userId: trainerId, type: 'USER_COMMENT', title, payload }),
),
);
}
return { comment };
}
@@ -108,3 +170,38 @@ export async function deleteMyComment(prisma: PrismaClient, userId: string, comm
if (!comment) throw notFound('Comment not found');
await prisma.comment.delete({ where: { id: comment.id } });
}
/**
* Marks comments as read for the viewer (CommentRead rows, wzór ConversationRead).
* Allowed only for comments the viewer participates in: authored by them,
* addressed to them, or authored by one of their active trainees. Rows for the
* viewer's own comments are never written (the author always sees them as read).
*/
export async function markCommentsRead(
prisma: PrismaClient,
viewerId: string,
commentIds: string[],
) {
if (commentIds.length === 0) return { ok: true };
const coachedIds = (
await prisma.coaching.findMany({
where: { trainerId: viewerId, status: 'ACTIVE' },
select: { userId: true },
})
).map((c) => c.userId);
const visible = await prisma.comment.findMany({
where: {
id: { in: commentIds },
authorId: { not: viewerId },
OR: [{ targetUserId: viewerId }, { authorId: { in: coachedIds } }],
},
select: { id: true },
});
if (visible.length > 0) {
await prisma.commentRead.createMany({
data: visible.map((c) => ({ commentId: c.id, userId: viewerId })),
skipDuplicates: true,
});
}
return { ok: true };
}

View File

@@ -303,7 +303,16 @@ export async function deleteCircumference(prisma: PrismaClient, userId: string,
};
}
export async function getHistory(prisma: PrismaClient, userId: string, month?: string) {
/**
* Historia sesji usera. `viewerId` (domyślnie sam user) rozstrzyga flagę `read`
* komentarzy per widz (CommentRead); komentarz autora jest zawsze „przeczytany".
*/
export async function getHistory(
prisma: PrismaClient,
userId: string,
month?: string,
viewerId: string = userId,
) {
// month = 'YYYY-MM' — sesje, których dzień treningowy leży w tym miesiącu
const where: Prisma.TrainingSessionWhereInput = {
day: { week: { plan: { userId } } },
@@ -357,6 +366,18 @@ export async function getHistory(prisma: PrismaClient, userId: string, month?: s
select: { value: true, date: true },
}),
]);
// Stan przeczytania komentarzy per widz (nieprzeczytane = brak wiersza CommentRead).
const commentIds = sessions.flatMap((s) =>
s.exercises.flatMap((e) => e.comments.map((c) => c.id)),
);
const readRows =
commentIds.length === 0
? []
: await prisma.commentRead.findMany({
where: { userId: viewerId, commentId: { in: commentIds } },
select: { commentId: true },
});
const readSet = new Set(readRows.map((r) => r.commentId));
return {
sessions: sessions.map((s) => {
const exercises = s.exercises.filter((e) => !e.hidden);
@@ -398,6 +419,7 @@ export async function getHistory(prisma: PrismaClient, userId: string, month?: s
authorName: [c.author.firstName, c.author.lastName].filter(Boolean).join(' ') || '—',
body: c.body,
createdAt: c.createdAt,
read: c.author.id === viewerId || readSet.has(c.id),
})),
sets: e.sets.map((st) => ({
index: st.index,

View File

@@ -467,7 +467,7 @@ export async function getTraineeDetail(prisma: PrismaClient, trainerId: string,
/** Trainee session history with plan vs. actual (restricted: training data only). */
export async function getTraineeHistory(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
return getHistory(prisma, userId);
return getHistory(prisma, userId, undefined, trainerId);
}
export type { MuscleReport };

View File

@@ -1004,7 +1004,7 @@ export const openapi: Record<string, unknown> = {
summary:
'Merged feed of personal notifications and gym/global announcements (cursor = createdAt)',
description:
'Announcement items carry author attribution: authorId, authorName, authorRole (ADMIN | OWNER | TRAINER; null for system-generated). Notification types: PLAN_READY, PLAN_EDITED (payload: planId, planTitle, note; deeplink /plans/:id), PLAN_SHARED, GYM_DELETED, TRAINER_COMMENT (payload: sessionId, trainerName; deeplink /profile/history).',
'Announcement items carry author attribution: authorId, authorName, authorRole (ADMIN | OWNER | TRAINER; null for system-generated). Notification types: PLAN_READY, PLAN_EDITED (payload: planId, planTitle, note; deeplink /plans/:id), PLAN_SHARED, GYM_DELETED, TRAINER_COMMENT (payload: sessionId, sessionExerciseId, exerciseName, commentId, authorName, preview; deeplink /profile/history?session=..&exercise=..) and USER_COMMENT (a trainee commented on their session; payload adds traineeId; deeplink /trainees/:traineeId?session=..&exercise=..).',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'limit', in: 'query', schema: { type: 'integer', default: 20 } },
@@ -1062,7 +1062,7 @@ export const openapi: Record<string, unknown> = {
tags: ['Profile'],
summary: 'Comment on my own session / exercise',
description:
"Anchored to the caller's own session. COMPLETED and ABANDONED sessions are allowed; an IN_PROGRESS session is rejected with code SESSION_IN_PROGRESS. Optional sessionExerciseId must belong to the session and not be removed. Writes an ActivityLog entry: comment.created.",
"Anchored to the caller's own session. COMPLETED and ABANDONED sessions are allowed; an IN_PROGRESS session is rejected with code SESSION_IN_PROGRESS. Optional sessionExerciseId must belong to the session and not be removed. Each active coach of the caller gets a USER_COMMENT feed notification. Writes an ActivityLog entry: comment.created.",
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
@@ -1090,6 +1090,30 @@ export const openapi: Record<string, unknown> = {
},
},
},
'/me/comments/read': {
post: {
tags: ['Profile'],
summary: 'Mark comments as read for the caller',
description:
'Writes CommentRead rows (wzór ConversationRead) for the given commentIds so their unread dot clears in history. Only comments the caller participates in (author, target, or authored by one of the caller\u2019s active trainees) are marked; own comments are always read. Idempotent.',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['commentIds'],
properties: {
commentIds: { type: 'array', items: { type: 'string' }, maxItems: 200 },
},
},
},
},
},
responses: { 200: { description: 'OK' } },
},
},
'/admin/equipment': {
get: {
tags: ['Equipment'],
@@ -2595,7 +2619,7 @@ export const openapi: Record<string, unknown> = {
tags: ['Trainer'],
summary: 'Trainer comment on the trainee (anchored to a session / exercise)',
description:
'Creates the comment and a TRAINER_COMMENT feed notification for the trainee. The session anchor may be COMPLETED or ABANDONED; an IN_PROGRESS session is rejected with code SESSION_IN_PROGRESS. Optional sessionExerciseId must belong to the session and not be removed. Writes an ActivityLog entry: comment.created.',
'Creates the comment and a TRAINER_COMMENT feed notification for the trainee (payload carries the exercise anchor: sessionId, sessionExerciseId, exerciseName, commentId, authorName, preview). The session anchor may be COMPLETED or ABANDONED; an IN_PROGRESS session is rejected with code SESSION_IN_PROGRESS. Optional sessionExerciseId must belong to the session and not be removed. Writes an ActivityLog entry: comment.created.',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'userId', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {

View File

@@ -19,6 +19,7 @@ describe('comments — under executed exercises', () => {
let traineeAbandonedSessionId: string;
let traineeAbandonedExerciseId: string;
let traineeCommentId: string;
let traineeExerciseName: string;
let mySessionId: string;
let myExerciseId: string;
@@ -46,6 +47,7 @@ describe('comments — under executed exercises', () => {
// Trainee: COMPLETED session + IN_PROGRESS session.
const exercise = await createExercise();
traineeExerciseName = exercise.name;
const plan = await seedPlan({
userId: trainee.id,
weeks: [
@@ -254,8 +256,9 @@ describe('comments — under executed exercises', () => {
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', body: 'Świetna forma!' }),
expect.objectContaining({ id: traineeCommentId, authorName: 'Tomasz', read: true }),
]);
});
@@ -264,8 +267,9 @@ describe('comments — under executed exercises', () => {
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', body: 'Świetna forma!' }),
expect.objectContaining({ id: traineeCommentId, authorName: 'Tomasz', read: false }),
]);
});
});
@@ -293,8 +297,15 @@ describe('comments — under executed exercises', () => {
});
expect(note).toBeTruthy();
notificationId = note!.id;
expect(note!.title).toBe('Trener Tomasz dodał komentarz do treningu');
expect(note!.payload).toMatchObject({ sessionId: traineeSessionId, trainerName: 'Tomasz' });
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')
@@ -340,6 +351,183 @@ describe('comments — under executed exercises', () => {
});
});
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