From 7a9f438cc77e8281ee886202a8b3c139ddaf37e7 Mon Sep 17 00:00:00 2001 From: tisachi Date: Mon, 9 Nov 2026 03:39:29 +0100 Subject: [PATCH] Api+App: komentarze usera - statusy przeczytania i typ USER_COMMENT (feed, profil, panel trenera) --- .../migration.sql | 20 ++ api/prisma/schema.prisma | 17 ++ api/src/routes/me.ts | 26 ++- api/src/services/comments.ts | 125 +++++++++-- api/src/services/me.ts | 24 ++- api/src/services/trainer.ts | 2 +- api/src/swagger.ts | 30 ++- api/test/integration/comments.test.ts | 196 +++++++++++++++++- app/src/api/queries.ts | 5 + app/src/api/types.ts | 4 +- app/src/components/ExerciseDetailDialog.tsx | 53 +++-- app/src/components/FeedItemRow.tsx | 30 ++- app/src/components/HistoryTable.tsx | 74 ++++++- app/src/i18n/locales/en/common.json | 8 +- app/src/i18n/locales/en/feed.json | 1 + app/src/i18n/locales/pl/common.json | 16 +- app/src/i18n/locales/pl/feed.json | 1 + app/src/pages/profile/ProfileHistory.tsx | 13 ++ app/src/pages/trainees/TraineeDetail.tsx | 13 ++ app/test/e2e/feed.spec.ts | 150 ++++++++++++-- app/test/e2e/mock-api.ts | 5 +- app/test/e2e/profile-mobile.spec.ts | 4 +- app/test/e2e/trainees.spec.ts | 6 +- app/test/history-report.test.tsx | 64 +++++- app/test/trainees.test.tsx | 2 +- 25 files changed, 801 insertions(+), 88 deletions(-) create mode 100644 api/prisma/migrations/20261109012753_comment_reads_and_user_comment_type/migration.sql diff --git a/api/prisma/migrations/20261109012753_comment_reads_and_user_comment_type/migration.sql b/api/prisma/migrations/20261109012753_comment_reads_and_user_comment_type/migration.sql new file mode 100644 index 0000000..65745d0 --- /dev/null +++ b/api/prisma/migrations/20261109012753_comment_reads_and_user_comment_type/migration.sql @@ -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; diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma index b6a1ad9..b1f8d0d 100644 --- a/api/prisma/schema.prisma +++ b/api/prisma/schema.prisma @@ -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 diff --git a/api/src/routes/me.ts b/api/src/routes/me.ts index 7ceb966..cc0f9e3 100644 --- a/api/src/routes/me.ts +++ b/api/src/routes/me.ts @@ -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; + const result = await markCommentsRead(prisma, req.user!.id, commentIds); + res.json(result); + }), + ); + /** * @openapi * /me/comments/{commentId}: diff --git a/api/src/services/comments.ts b/api/src/services/comments.ts index b297fc8..ab92ba8 100644 --- a/api/src/services/comments.ts +++ b/api/src/services/comments.ts @@ -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 }; +} diff --git a/api/src/services/me.ts b/api/src/services/me.ts index 8e3cfde..332651a 100644 --- a/api/src/services/me.ts +++ b/api/src/services/me.ts @@ -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, diff --git a/api/src/services/trainer.ts b/api/src/services/trainer.ts index b6bfe1b..a971da3 100644 --- a/api/src/services/trainer.ts +++ b/api/src/services/trainer.ts @@ -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 }; diff --git a/api/src/swagger.ts b/api/src/swagger.ts index 0e55880..0c72459 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -1004,7 +1004,7 @@ export const openapi: Record = { 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 = { 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 = { }, }, }, + '/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 = { 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: { diff --git a/api/test/integration/comments.test.ts b/api/test/integration/comments.test.ts index fba1a1d..c5c8233 100644 --- a/api/test/integration/comments.test.ts +++ b/api/test/integration/comments.test.ts @@ -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 diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index ed4a2b4..f8cdfac 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -1094,6 +1094,11 @@ export function deleteComment(commentId: string, scope: 'me' | { userId: string return api(path, { method: 'DELETE' }); } +/** Oznacza komentarze jako przeczytane per widz (wiersze CommentRead, idempotentne). */ +export function markCommentsRead(commentIds: string[]) { + return api('/me/comments/read', { method: 'POST', body: { commentIds } }); +} + // ---------- postępy per ćwiczenie ---------- export function useExerciseProgress() { return useQuery({ diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 6e7f493..4e21ef7 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -757,6 +757,8 @@ export interface ExerciseComment { authorName: string; body: string; createdAt: string; + /** Stan przeczytania per widz (historia); brak pola w odpowiedzi utworzenia. */ + read?: boolean; } export interface HistoryExercise { @@ -890,7 +892,7 @@ export interface ConversationThread { // ---------- aktualności (feed) ---------- export type NotificationType = - 'PLAN_READY' | 'PLAN_EDITED' | 'PLAN_SHARED' | 'GYM_DELETED' | 'TRAINER_COMMENT'; + 'PLAN_READY' | 'PLAN_EDITED' | 'PLAN_SHARED' | 'GYM_DELETED' | 'TRAINER_COMMENT' | 'USER_COMMENT'; export interface FeedNotificationItem { source: 'notification'; diff --git a/app/src/components/ExerciseDetailDialog.tsx b/app/src/components/ExerciseDetailDialog.tsx index e80dec1..950607f 100644 --- a/app/src/components/ExerciseDetailDialog.tsx +++ b/app/src/components/ExerciseDetailDialog.tsx @@ -97,26 +97,43 @@ export default function ExerciseDetailDialog({ {comments.length > 0 && (
+
+ {t('history.commentsHeading')} ({comments.length}) +
- {comments.map((c) => ( -
-
- {c.authorName} - · {fmtDate(c.createdAt)} -
{c.body}
+ {comments.map((c) => { + const unread = c.read === false && (!myUserId || c.authorId !== myUserId); + const mine = !!myUserId && c.authorId === myUserId; + return ( +
+
+ {c.authorName} + {unread && ( + + {t('history.commentNewBadge')} + + )} + · {fmtDate(c.createdAt)} +
{c.body}
+
+ {mine && onDeleteComment && ( + + )}
- {myUserId && c.authorId === myUserId && onDeleteComment && ( - - )} -
- ))} + ); + })}
)} diff --git a/app/src/components/FeedItemRow.tsx b/app/src/components/FeedItemRow.tsx index 9081da4..81bd77c 100644 --- a/app/src/components/FeedItemRow.tsx +++ b/app/src/components/FeedItemRow.tsx @@ -24,11 +24,21 @@ export function feedDeeplink(item: FeedItem): string | null { const planId = item.payload.planId; return typeof planId === 'string' ? `/plans/${planId}` : null; } - if (item.type === 'TRAINER_COMMENT') { + if (item.type === 'TRAINER_COMMENT' || item.type === 'USER_COMMENT') { + // Kotwica ćwiczenia (gdy komentarz przy ćwiczeniu) otwiera od razu dialog + // z komentarzem — klik w feedzie prowadzi wprost do treści. const sessionId = item.payload.sessionId; - return typeof sessionId === 'string' - ? `/profile/history?session=${sessionId}` - : '/profile/history'; + const exerciseId = item.payload.sessionExerciseId; + const query = new URLSearchParams(); + if (typeof sessionId === 'string') query.set('session', sessionId); + if (typeof exerciseId === 'string' && exerciseId) query.set('exercise', exerciseId); + const qs = query.toString(); + if (item.type === 'USER_COMMENT') { + const traineeId = item.payload.traineeId; + if (typeof traineeId !== 'string') return null; + return `/trainees/${traineeId}${qs ? `?${qs}` : ''}`; + } + return `/profile/history${qs ? `?${qs}` : ''}`; } return null; } @@ -49,6 +59,8 @@ export function feedItemIcon(item: FeedItem): { Icon: LucideIcon; label: string return { Icon: Building2, label: i18n.t('feed:itemType.gymDeleted') }; case 'TRAINER_COMMENT': return { Icon: MessageSquare, label: i18n.t('feed:itemType.trainerComment') }; + case 'USER_COMMENT': + return { Icon: MessageSquare, label: i18n.t('feed:itemType.traineeComment') }; } } switch (item.kind) { @@ -89,6 +101,11 @@ export function FeedItemRow({ item, compact = false }: { item: FeedItem; compact if (to) navigate(to); }; + const isComment = + item.source === 'notification' && + (item.type === 'TRAINER_COMMENT' || item.type === 'USER_COMMENT'); + const preview = isComment ? (item.payload.preview as string | undefined) : undefined; + return (