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

View File

@@ -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({

View File

@@ -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';

View File

@@ -97,26 +97,43 @@ export default function ExerciseDetailDialog({
{comments.length > 0 && (
<div className="mt-4 border-t border-line pt-3">
<div className="mb-1.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
{t('history.commentsHeading')} ({comments.length})
</div>
<div className="space-y-1.5">
{comments.map((c) => (
<div key={c.id} className="flex items-start gap-2 py-1 text-[0.875rem]">
<div className="min-w-0 flex-1">
<span className="font-semibold">{c.authorName}</span>
<span className="text-dim"> · {fmtDate(c.createdAt)}</span>
<div>{c.body}</div>
{comments.map((c) => {
const unread = c.read === false && (!myUserId || c.authorId !== myUserId);
const mine = !!myUserId && c.authorId === myUserId;
return (
<div
key={c.id}
className={`flex items-start gap-2 rounded-[8px] px-2 py-1.5 text-[0.875rem] ${
unread ? 'border-l-2 border-accent bg-accent/10' : mine ? 'bg-input/60' : ''
}`}
>
<div className="min-w-0 flex-1">
<span className="font-semibold">{c.authorName}</span>
{unread && (
<Badge color="green" className="ml-2 align-middle">
{t('history.commentNewBadge')}
</Badge>
)}
<span className="text-dim"> · {fmtDate(c.createdAt)}</span>
<div className={mine ? 'text-dim' : undefined}>{c.body}</div>
</div>
{mine && onDeleteComment && (
<button
type="button"
aria-label={t('history.deleteCommentAria', { author: c.authorName })}
onClick={() => void onDeleteComment(c.id)}
className="-m-1 shrink-0 cursor-pointer p-1 text-dim hover:text-danger"
>
<Trash2 className="h-4 w-4" />
</button>
)}
</div>
{myUserId && c.authorId === myUserId && onDeleteComment && (
<button
type="button"
aria-label={t('history.deleteCommentAria', { author: c.authorName })}
onClick={() => void onDeleteComment(c.id)}
className="-m-1 shrink-0 cursor-pointer p-1 text-dim hover:text-danger"
>
<Trash2 className="h-4 w-4" />
</button>
)}
</div>
))}
);
})}
</div>
</div>
)}

View File

@@ -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 (
<button
type="button"
@@ -119,6 +136,11 @@ export function FeedItemRow({ item, compact = false }: { item: FeedItem; compact
{!compact && item.source === 'announcement' && (
<span className="mt-1 block line-clamp-3 text-dim text-[0.8125rem]">{item.body}</span>
)}
{!compact && isComment && preview && (
<span className="mt-1 block line-clamp-2 border-l-2 border-accent/50 pl-2 text-[0.8125rem] text-ink/85 italic">
{preview}
</span>
)}
</span>
{!item.read && (
<span aria-hidden="true" className="mt-2.5 h-2 w-2 shrink-0 rounded-full bg-accent" />

View File

@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronRight, ChevronUp, MessageSquare } from 'lucide-react';
import { ChevronDown, ChevronRight, ChevronUp, MessageSquare, StickyNote } from 'lucide-react';
import type { HistoryExercise, HistorySession } from '../api/types';
import { fmtDate, fmtDuration, fmtVolume } from '../lib/format';
import { localizedName } from '../lib/localizedName';
@@ -16,6 +16,10 @@ interface HistoryTableProps {
myUserId?: string;
/** Sesja otwarta od razu (np. po kliknięciu karty załącznika). */
initialOpenSessionId?: string;
/** Ćwiczenie z rozwiniętym dialogiem od razu (deeplink z feedu: ?exercise=). */
initialOpenExerciseId?: string;
/** Oznaczenie wyświetlonych komentarzy jako przeczytane (per widz). */
onMarkCommentsRead?: (commentIds: string[]) => Promise<void>;
onAddComment?: (args: {
sessionId: string;
sessionExerciseId: string;
@@ -44,6 +48,11 @@ function toExerciseReport(ex: HistoryExercise) {
};
}
/** Komentarze drugiej strony bez wiersza CommentRead = nieprzeczytane (read=false). */
function unreadComments(ex: HistoryExercise) {
return ex.comments.filter((c) => c.read === false).length;
}
/**
* Read-only session history: session accordion with exercise cards that open
* `ExerciseDetailDialog` (set table + comments). Shared by the user's Profile
@@ -54,6 +63,8 @@ export default function HistoryTable({
canComment = false,
myUserId,
initialOpenSessionId,
initialOpenExerciseId,
onMarkCommentsRead,
onAddComment,
onDeleteComment,
}: HistoryTableProps) {
@@ -62,7 +73,23 @@ export default function HistoryTable({
const [selected, setSelected] = useState<{
session: HistorySession;
exercise: HistoryExercise;
} | null>(null);
} | null>(() => {
// Deeplink z feedu (?session=..&exercise=..) otwiera od razu dialog ćwiczenia.
if (!initialOpenExerciseId) return null;
for (const s of sessions) {
const ex = s.exercises.find((e) => e.id === initialOpenExerciseId);
if (ex) return { session: s, exercise: ex };
}
return null;
});
// Otwarcie dialogu = wyświetlenie komentarzy → oznacz przeczytane (gasną odznaki).
useEffect(() => {
if (!selected || !onMarkCommentsRead) return;
const ids = selected.exercise.comments.filter((c) => c.read === false).map((c) => c.id);
if (ids.length > 0) void onMarkCommentsRead(ids);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selected]);
return (
<div className="divide-y divide-line">
@@ -93,6 +120,7 @@ export default function HistoryTable({
set.reps != null ? sum + (set.planned?.loadKg ?? s.bodyKg ?? 0) * set.reps : sum,
0,
);
const sessionUnread = s.exercises.reduce((n, ex) => n + unreadComments(ex), 0);
const duration = s.endedAt ? fmtDuration(s.startedAt, s.endedAt) : null;
return (
<div key={s.id} className="px-1">
@@ -128,6 +156,16 @@ export default function HistoryTable({
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
{sessionUnread > 0 && (
<Badge
color="green"
title={t('history.commentsUnread', { count: sessionUnread })}
aria-label={t('history.commentsUnread', { count: sessionUnread })}
>
<MessageSquare className="h-3 w-3" aria-hidden="true" />
{sessionUnread}
</Badge>
)}
<Badge color={st.color}>{t(st.labelKey)}</Badge>
{open ? (
<ChevronUp className="h-4 w-4 text-dim" />
@@ -158,8 +196,10 @@ export default function HistoryTable({
const exExtra = ex.sets.filter(
(set) => set.planned == null && set.reps != null,
).length;
// komentarze serii: wskaznik, by trener nie musial otwierac dialogu
// notatki serii usera: osobny wskaźnik (nie mylić z komentarzami)
const exNotes = ex.sets.filter((set) => set.note).length;
const exComments = ex.comments.length;
const exUnread = unreadComments(ex);
return (
<button
key={ex.id}
@@ -193,13 +233,35 @@ export default function HistoryTable({
{t('history.bonusValue', { n: exExtra })}
</span>
)}
{exComments > 0 && (
<Badge
color={exUnread > 0 ? 'green' : 'blue'}
title={t(
exUnread > 0 ? 'history.commentsUnread' : 'history.commentsBadge',
{ count: exUnread > 0 ? exUnread : exComments },
)}
aria-label={t(
exUnread > 0 ? 'history.commentsUnread' : 'history.commentsBadge',
{ count: exUnread > 0 ? exUnread : exComments },
)}
>
<MessageSquare className="h-3 w-3" aria-hidden="true" />
{exComments}
{exUnread > 0 && (
<span
aria-hidden="true"
className="h-1.5 w-1.5 rounded-full bg-accent-text"
/>
)}
</Badge>
)}
{exNotes > 0 && (
<Badge
color="green"
color="gray"
title={t('history.setNotesBadge', { count: exNotes })}
aria-label={t('history.setNotesBadge', { count: exNotes })}
>
<MessageSquare className="h-3 w-3" aria-hidden="true" />
<StickyNote className="h-3 w-3" aria-hidden="true" />
{exNotes}
</Badge>
)}

View File

@@ -189,6 +189,12 @@
"sessionContext": "Session from {{date}} · {{plan}}",
"setNotes": "Set notes",
"setNotesBadge_one": "{{count}} set note",
"setNotesBadge_other": "{{count}} set notes"
"setNotesBadge_other": "{{count}} set notes",
"commentsHeading": "Comments",
"commentNewBadge": "New",
"commentsBadge_one": "{{count}} comment on this exercise",
"commentsBadge_other": "{{count}} comments on this exercise",
"commentsUnread_one": "{{count}} unread comment on this exercise",
"commentsUnread_other": "{{count}} unread comments on this exercise"
}
}

View File

@@ -11,6 +11,7 @@
"sharedPlan": "Shared plan",
"gymDeleted": "Deleted gym",
"trainerComment": "Trainer comment",
"traineeComment": "Trainee comment",
"announcement": "Announcement",
"hoursChange": "Hours change",
"exception": "Schedule exception"

View File

@@ -211,9 +211,17 @@
"collapseSets": "Zwiń",
"actualWord": "Wykonanie",
"sessionContext": "Sesja z {{date}} · {{plan}}",
"setNotes": "Komentarze przy seriach",
"setNotesBadge_one": "{{count}} komentarz przy serii",
"setNotesBadge_few": "{{count}} komentarze przy seriach",
"setNotesBadge_other": "{{count}} komentarzy przy seriach"
"setNotes": "Notatki przy seriach",
"setNotesBadge_one": "{{count}} notatka przy seriach",
"setNotesBadge_few": "{{count}} notatki przy seriach",
"setNotesBadge_other": "{{count}} notatek przy seriach",
"commentsHeading": "Komentarze",
"commentNewBadge": "Nowe",
"commentsBadge_one": "{{count}} komentarz przy ćwiczeniu",
"commentsBadge_few": "{{count}} komentarze przy ćwiczeniu",
"commentsBadge_other": "{{count}} komentarzy przy ćwiczeniu",
"commentsUnread_one": "{{count}} nieprzeczytany komentarz przy ćwiczeniu",
"commentsUnread_few": "{{count}} nieprzeczytane komentarze przy ćwiczeniu",
"commentsUnread_other": "{{count}} nieprzeczytanych komentarzy przy ćwiczeniu"
}
}

View File

@@ -11,6 +11,7 @@
"sharedPlan": "Udostępniony plan",
"gymDeleted": "Usunięta siłownia",
"trainerComment": "Komentarz trenera",
"traineeComment": "Komentarz podopiecznego",
"announcement": "Ogłoszenie",
"hoursChange": "Zmiana godzin",
"exception": "Wyjątek w godzinach"

View File

@@ -6,6 +6,7 @@ import { History } from 'lucide-react';
import {
addMyComment,
deleteComment,
markCommentsRead,
useHistory,
useMe,
usePresenceHistory,
@@ -40,6 +41,7 @@ export default function ProfileHistory() {
const { data: meData } = useMe();
const [params] = useSearchParams();
const initialOpenSessionId = params.get('session') ?? undefined;
const initialOpenExerciseId = params.get('exercise') ?? undefined;
// miesiące z sesjami (nowe → stare) — do selektora w topmenu
const monthsKey = [
@@ -92,6 +94,15 @@ export default function ProfileHistory() {
}
};
const markRead = async (commentIds: string[]) => {
try {
await markCommentsRead(commentIds);
await queryClient.invalidateQueries({ queryKey: ['me', 'history'] });
} catch (e) {
push((e as Error).message, 'error');
}
};
// „Wszystkie” = pełny fetch (bez refetcha przy powrocie); miesiąc = filtr API
const sessions = month === '' ? (fullHist?.sessions ?? []) : (hist?.sessions ?? []);
const loading = month === '' ? fullLoading : isLoading;
@@ -132,6 +143,8 @@ export default function ProfileHistory() {
canComment
myUserId={meData?.user.id}
initialOpenSessionId={initialOpenSessionId}
initialOpenExerciseId={initialOpenExerciseId}
onMarkCommentsRead={markRead}
onAddComment={addComment}
onDeleteComment={removeComment}
/>

View File

@@ -7,6 +7,7 @@ import {
addTraineeComment,
archiveTrainee,
deleteComment,
markCommentsRead,
useMe,
useTrainee,
useTraineeHistory,
@@ -47,6 +48,7 @@ export default function TraineeDetail() {
const { push } = useToast();
const [params] = useSearchParams();
const initialOpenSessionId = params.get('session') ?? undefined;
const initialOpenExerciseId = params.get('exercise') ?? undefined;
// ?tab=<id> (np. po zapisie planu) > ?session=<id> (Historia) > ostatnio wybrana zakładka
const storedTab = sessionStorage.getItem(`fitos:trainee-tab:${userId}`) ?? undefined;
const initialTab =
@@ -90,6 +92,15 @@ export default function TraineeDetail() {
}
};
const markRead = async (commentIds: string[]) => {
try {
await markCommentsRead(commentIds);
await queryClient.invalidateQueries({ queryKey: ['trainees', userId, 'history'] });
} catch (e) {
push((e as Error).message, 'error');
}
};
const doArchive = async () => {
setBusy(true);
try {
@@ -217,6 +228,8 @@ export default function TraineeDetail() {
canComment
myUserId={meData?.user.id}
initialOpenSessionId={initialOpenSessionId}
initialOpenExerciseId={initialOpenExerciseId}
onMarkCommentsRead={markRead}
onAddComment={addComment}
onDeleteComment={removeComment}
/>

View File

@@ -1,9 +1,16 @@
import { test, expect } from './fixtures';
import { mockApi, TEST_GYM_OWNED } from './mock-api';
import { mockApi, TEST_GYM_OWNED, TEST_USER } from './mock-api';
const NOW = Date.now();
const iso = (minsAgo: number) => new Date(NOW - minsAgo * 60_000).toISOString();
function trainerMe() {
return {
user: TEST_USER,
memberships: [{ gymId: TEST_GYM_OWNED.id, roles: ['TRAINER'], gym: TEST_GYM_OWNED }],
};
}
function feedState() {
return {
items: [
@@ -149,7 +156,9 @@ test('Aktualności: menu kontekstowe — filtr typu i wyszukiwarka', async ({ pa
await expect(page.getByText('Zamknięcie 24.12.2026')).toBeVisible();
});
test('Aktualności: komentarz trenera prowadzi do historii treningów', async ({ page }) => {
test('Aktualności: komentarz trenera prowadzi wprost do dialogu ćwiczenia w historii', async ({
page,
}) => {
mockApi(page, {
feed: {
items: [
@@ -157,8 +166,15 @@ test('Aktualności: komentarz trenera prowadzi do historii treningów', async ({
source: 'notification',
id: 'n-cmt-1',
type: 'TRAINER_COMMENT',
title: 'Trener Marek Trener dodał komentarz do treningu',
payload: { sessionId: 'my-hist-1', trainerName: 'Marek Trener' },
title: 'Trener Marek Trener: komentarz przy ćwiczeniu Przysiady',
payload: {
sessionId: 'my-hist-1',
sessionExerciseId: 'my-se-1',
exerciseName: 'Przysiady',
commentId: 'cmt-1',
authorName: 'Marek Trener',
preview: 'Szlifuj technikę, kolana prosto',
},
read: false,
createdAt: iso(5),
},
@@ -167,15 +183,22 @@ test('Aktualności: komentarz trenera prowadzi do historii treningów', async ({
});
await login(page);
// podpis typu wpisu + klik = deeplink do historii (z kotwicą sesji z payloadu)
// podpis typu wpisu + fragment treści komentarza w kartach aktualności
await page.getByRole('link', { name: 'Zobacz wszystkie' }).click();
await expect(page.getByText('Komentarz trenera')).toBeVisible();
await page.getByRole('button', { name: /Trener Marek Trener dodał komentarz/ }).click();
await expect(page).toHaveURL(/\/profile\/history\?session=my-hist-1/);
await expect(page.getByRole('heading', { name: 'Historia treningów', level: 2 })).toBeVisible();
await expect(page.getByText('Szlifuj technikę, kolana prosto')).toBeVisible();
await page.getByRole('button', { name: /Trener Marek Trener: komentarz/ }).click();
// deeplink z kotwicą ćwiczenia (session + exercise z payloadu)
await expect(page).toHaveURL(/\/profile\/history\?session=my-hist-1&exercise=my-se-1/);
// dialog otwarty od razu — treść strony za dialogiem jest aria-hidden, więc sprawdzamy tekstem
await expect(page.getByText('Historia treningów')).toBeVisible();
// dialog ćwiczenia otwiera się od razu — bez szukania komentarza po wierszach
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(dialog.getByText('Przysiady')).toBeVisible();
});
test('Aktualności: komentarz trenera do sesji porzuconej — klik rozwija sesję i pokazuje komentarz', async ({
test('Aktualności: komentarz trenera do sesji porzuconej — klik otwiera dialog z nieprzeczytanym komentarzem', async ({
page,
}) => {
// Deeplink musi trafiać w sesję ABANDONED, która realnie istnieje w /me/history.
@@ -203,6 +226,7 @@ test('Aktualności: komentarz trenera do sesji porzuconej — klik rozwija sesj
authorName: 'Marek Trener',
body: 'Do przeanalizowania po porzuceniu',
createdAt: iso(60),
read: false,
},
],
sets: [
@@ -225,8 +249,15 @@ test('Aktualności: komentarz trenera do sesji porzuconej — klik rozwija sesj
source: 'notification',
id: 'n-cmt-2',
type: 'TRAINER_COMMENT',
title: 'Trener Marek Trener dodał komentarz do treningu',
payload: { sessionId: 'my-hist-ab-1', trainerName: 'Marek Trener' },
title: 'Trener Marek Trener: komentarz przy ćwiczeniu Przysiady',
payload: {
sessionId: 'my-hist-ab-1',
sessionExerciseId: 'my-se-ab-1',
exerciseName: 'Przysiady',
commentId: 'c-ab-1',
authorName: 'Marek Trener',
preview: 'Do przeanalizowania po porzuceniu',
},
read: false,
createdAt: iso(5),
},
@@ -238,14 +269,101 @@ test('Aktualności: komentarz trenera do sesji porzuconej — klik rozwija sesj
await page.getByRole('link', { name: 'Zobacz wszystkie' }).click();
await expect(page.getByText('Komentarz trenera')).toBeVisible();
await page.getByRole('button', { name: /Trener Marek Trener dodał komentarz/ }).click();
await expect(page).toHaveURL(/\/profile\/history\?session=my-hist-ab-1/);
await expect(page.getByRole('heading', { name: 'Historia treningów', level: 2 })).toBeVisible();
// sesja porzucona rozwinięta (kotwica z payloadu) — dialog ćwiczenia z komentarzem
await page.getByRole('button', { name: /Trener Marek Trener: komentarz/ }).click();
await expect(page).toHaveURL(/\/profile\/history\?session=my-hist-ab-1&exercise=my-se-ab-1/);
await expect(page.getByText('Historia treningów')).toBeVisible();
await expect(page.getByText('Porzucona')).toBeVisible();
await page.getByRole('button', { name: /Przysiady/ }).click();
// dialog otwarty od razu (kotwica ćwiczenia z payloadu) + wyróżnienie nieprzeczytanego
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(dialog.getByText('Do przeanalizowania po porzuceniu')).toBeVisible();
await expect(dialog.getByText('Nowe')).toBeVisible();
});
test('Aktualności: komentarz podopiecznego powiadamia trenera i otwiera dialog w jego karcie', async ({
page,
}) => {
const traineeHistory = {
sessions: [
{
id: 'hist-sess-1',
status: 'COMPLETED',
startedAt: '2026-08-24T07:00:00.000Z',
endedAt: '2026-08-24T08:30:00.000Z',
date: '2026-08-24',
dayOfWeek: 1,
plan: 'Plan testowy',
norm: { done: 1, total: 1 },
bonus: 0,
deficit: 0,
exercises: [
{
id: 'se-1',
name: 'Przysiady',
muscle: 'legs',
isExtra: false,
comments: [
{
id: 'uc-1',
authorId: 'trainee-1',
authorName: 'Anna Nowak',
body: 'Bark mnie boli po wyciskaniu',
createdAt: iso(30),
read: false,
},
],
sets: [
{
index: 0,
reps: 10,
rir: 2,
difficulty: null,
note: null,
planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 },
},
],
},
],
},
],
};
mockApi(page, {
me: trainerMe(),
feed: {
items: [
{
source: 'notification',
id: 'n-uc-1',
type: 'USER_COMMENT',
title: 'Anna Nowak: komentarz przy ćwiczeniu Przysiady',
payload: {
sessionId: 'hist-sess-1',
sessionExerciseId: 'se-1',
exerciseName: 'Przysiady',
commentId: 'uc-1',
authorName: 'Anna Nowak',
traineeId: 'trainee-1',
preview: 'Bark mnie boli po wyciskaniu',
},
read: false,
createdAt: iso(15),
},
],
},
traineeHistory,
});
await login(page);
await page.getByRole('link', { name: 'Zobacz wszystkie' }).click();
await expect(page.getByText('Komentarz podopiecznego')).toBeVisible();
await page.getByRole('button', { name: /Anna Nowak: komentarz/ }).click();
// klik w feedzie trenera = karta podopiecznego (Historia) z od razu otwartym dialogiem
await expect(page).toHaveURL(/\/trainees\/trainee-1\?session=hist-sess-1&exercise=se-1/);
await expect(page.getByText('Anna Nowak').first()).toBeVisible();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(dialog.getByText('Bark mnie boli po wyciskaniu')).toBeVisible();
await expect(dialog.getByText('Nowe')).toBeVisible();
});
test('Aktualności: zmiana planu przez trenera — podpis typu i klik do szczegółów planu', async ({

View File

@@ -1396,6 +1396,8 @@ export interface MockApiOptions {
userSearch?: unknown;
/** Ciało odpowiedzi GET /trainer/trainees/:id (domyślnie: TEST_TRAINEE_DETAIL). */
traineeDetail?: unknown;
/** Ciało odpowiedzi GET /trainer/trainees/:id/history (domyślnie: TEST_TRAINEE_HISTORY; stateful POST komentarzy). */
traineeHistory?: unknown;
/** Ciało odpowiedzi GET /messages/conversations (domyślnie: TEST_CONVERSATIONS). */
conversations?: unknown;
/** Ciało odpowiedzi GET /messages/conversations/:id (domyślnie: TEST_MESSAGE_THREAD). */
@@ -1469,6 +1471,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
invitations = { invitations: TEST_INVITATIONS },
userSearch = { users: TEST_USER_SEARCH },
traineeDetail = TEST_TRAINEE_DETAIL,
traineeHistory: traineeHistoryOverride,
conversations = TEST_CONVERSATIONS,
messageThread = TEST_MESSAGE_THREAD,
gymInvitations = { invitations: [] },
@@ -1557,7 +1560,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
// Stateful: komentarze pod ćwiczeniami — dodane przez POST widoczne po refetch historii.
const traineeHistory = JSON.parse(
JSON.stringify(TEST_TRAINEE_HISTORY),
JSON.stringify(traineeHistoryOverride ?? TEST_TRAINEE_HISTORY),
) as typeof TEST_TRAINEE_HISTORY;
// Stateful: virtual gyms (ratings, claims) + gym invitations (sent/received).

View File

@@ -133,10 +133,10 @@ test('mobile: historia — kompaktowe serie, objętość/czas i filtr miesiąca'
await expect(page.getByText('1 h 30 min')).toBeVisible();
await expect(page.getByText('320 kg')).toBeVisible();
// tap na sesji rozwija ćwiczenia; licznik komentarzy serii przy wierszu ćwiczenia
// tap na sesji rozwija ćwiczenia; licznik notatek serii przy wierszu ćwiczenia
await page.getByRole('button', { name: /600 kg/ }).click();
await expect(page.getByText('Przysiady')).toBeVisible();
await expect(page.getByTitle('1 komentarz przy serii')).toBeVisible();
await expect(page.getByTitle('1 notatka przy seriach')).toBeVisible();
// tap na ćwiczeniu otwiera dialog z kompaktowymi kartami serii (wariant mobilny)
await page.getByRole('button', { name: /Przysiady/ }).click();
const dialog = page.getByRole('dialog');

View File

@@ -95,12 +95,12 @@ test('szczegóły podopiecznego: przegląd i historia z planem vs. fakty', async
await page.getByRole('button', { name: /24\.08\.2026/ }).click();
await expect(page.getByText('Przysiady')).toBeVisible();
await expect(page.getByText('dodane')).toBeVisible();
// licznik komentarzy serii przy wierszu ćwiczenia — trener nie musi otwierać dialogu
await expect(page.getByTitle('1 komentarz przy serii')).toBeVisible();
// licznik notatek serii przy wierszu ćwiczenia — trener nie musi otwierać dialogu
await expect(page.getByTitle('1 notatka przy seriach')).toBeVisible();
// dialog ćwiczenia: callout komentarza serii + ikona wskazująca przy numerze serii
await page.getByRole('button', { name: /Przysiady/ }).click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('Komentarze przy seriach')).toBeVisible();
await expect(dialog.getByText('Notatki przy seriach')).toBeVisible();
await expect(dialog.getByText('ostatnia seria była ciężka').first()).toBeVisible();
await expect(dialog.getByTitle('ostatnia seria była ciężka')).toBeVisible();
await page.getByRole('button', { name: 'Zamknij' }).click();

View File

@@ -1,6 +1,6 @@
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import HistoryTable from '../src/components/HistoryTable';
import ExerciseReportTable from '../src/components/ExerciseReportTable';
import DifficultyDots from '../src/components/DifficultyDots';
@@ -84,8 +84,9 @@ describe('HistoryTable — master/detail (dialog ćwiczenia)', () => {
// rozwinięta sesja: podsumowania ćwiczeń w kartach
expect(screen.getByRole('button', { name: /Przysiad/ })).toBeInTheDocument();
expect(screen.getByText('dodane')).toBeInTheDocument();
// licznik komentarzy serii przy wierszu ćwiczenia (trener nie musi otwierać dialogu)
expect(screen.getByTitle('1 komentarz przy serii')).toBeInTheDocument();
// licznik komentarzy ćwiczenia (osobno od notatek serii) — trener nie musi otwierać dialogu
expect(screen.getByTitle('1 komentarz przy ćwiczeniu')).toBeInTheDocument();
expect(screen.getByTitle('1 notatka przy seriach')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /Przysiad/ }));
const dialog = screen.getByRole('dialog');
@@ -101,8 +102,9 @@ describe('HistoryTable — master/detail (dialog ćwiczenia)', () => {
expect(within(dialog).getAllByText('luz').length).toBeGreaterThanOrEqual(2);
expect(within(dialog).getAllByText(/Seria 1/).length).toBeGreaterThanOrEqual(1);
expect(within(dialog).getByTitle('luz')).toBeInTheDocument();
expect(within(dialog).getByText('Komentarze przy seriach')).toBeInTheDocument();
// komentarz w stopce dialogu
expect(within(dialog).getByText('Notatki przy seriach')).toBeInTheDocument();
// komentarz w stopce dialogu + nagłówek sekcji komentarzy
expect(within(dialog).getByText('Komentarze (1)')).toBeInTheDocument();
expect(within(dialog).getByText('Dobre tempo')).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Zamknij' }));
@@ -148,6 +150,54 @@ describe('HistoryTable — master/detail (dialog ćwiczenia)', () => {
expect(within(dialog).queryByRole('button', { name: 'Dodaj komentarz' })).not.toBeInTheDocument();
expect(within(dialog).getByText('Komentarze dostępne po zakończeniu treningu.')).toBeInTheDocument();
});
it('nieprzeczytany komentarz: odznaka przy wierszu ćwiczenia i w nagłówku sesji', () => {
const unreadSession: HistorySession = {
...SESSION,
exercises: [
{ ...SESSION.exercises[0], comments: [{ ...SESSION.exercises[0].comments[0], read: false }] },
SESSION.exercises[1],
],
};
render(<HistoryTable sessions={[unreadSession]} initialOpenSessionId="s1" myUserId="u1" />);
// ta sama odznaka nieprzeczytanych: nagłówek sesji (widoczny po zwinięciu) + wiersz ćwiczenia
expect(screen.getAllByTitle('1 nieprzeczytany komentarz przy ćwiczeniu')).toHaveLength(2);
});
it('deeplink (?session=..&exercise=..) otwiera od razu dialog ćwiczenia', () => {
render(
<HistoryTable
sessions={[SESSION]}
initialOpenSessionId="s1"
initialOpenExerciseId="se-1"
/>,
);
const dialog = screen.getByRole('dialog');
expect(within(dialog).getByText('Przysiad')).toBeInTheDocument();
expect(within(dialog).getByText('Dobre tempo')).toBeInTheDocument();
});
it('otwarcie dialogu oznacza nieprzeczytane komentarze jako przeczytane', async () => {
const user = userEvent.setup();
const mark = vi.fn(async (_ids: string[]) => {});
const unreadSession: HistorySession = {
...SESSION,
exercises: [
{ ...SESSION.exercises[0], comments: [{ ...SESSION.exercises[0].comments[0], read: false }] },
SESSION.exercises[1],
],
};
render(
<HistoryTable
sessions={[unreadSession]}
initialOpenSessionId="s1"
myUserId="u1"
onMarkCommentsRead={mark}
/>,
);
await user.click(screen.getByRole('button', { name: /Przysiad/ }));
expect(mark).toHaveBeenCalledWith(['c1']);
});
});
describe('ExerciseReportTable — karty mobilne i zwijanie', () => {
@@ -173,13 +223,13 @@ describe('ExerciseReportTable — karty mobilne i zwijanie', () => {
expect(screen.queryByText('S4')).not.toBeInTheDocument();
// komentarz serii spoza zwiniętej listy pozostaje widoczny (callout poza prog)
expect(screen.getByText('ciezka')).toBeInTheDocument();
expect(screen.getByText('Komentarze przy seriach')).toBeInTheDocument();
expect(screen.getByText('Notatki przy seriach')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Pokaż więcej (+2)' }));
expect(screen.getByText('S4')).toBeInTheDocument();
expect(screen.getByText('S5')).toBeInTheDocument();
// po rozwinięciu komentarz przenosi się do karty serii — bez duplikatu
expect(screen.getByText('ciezka')).toBeInTheDocument();
expect(screen.queryByText('Komentarze przy seriach')).not.toBeInTheDocument();
expect(screen.queryByText('Notatki przy seriach')).not.toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Zwiń' }));
expect(screen.queryByText('S4')).not.toBeInTheDocument();
});

View File

@@ -712,7 +712,7 @@ describe('Trainees — lista i szczegóły', () => {
expect(screen.getByText('4/10 · 10–20')).toBeInTheDocument();
// detale cwiczen: komentarz serii widoczny jako callout z etykieta sekcji
expect(screen.getByText('Martwy ciąg')).toBeInTheDocument();
expect(screen.getByText('Komentarze przy seriach')).toBeInTheDocument();
expect(screen.getByText('Notatki przy seriach')).toBeInTheDocument();
expect(screen.getAllByText('bolely plecy').length).toBeGreaterThanOrEqual(1);
});