API+App: powiadomienie feed o komentarzu trenera pod cwiczeniem - typ TRAINER_COMMENT (schemat + migracja), createNotification w addTraineeComment, widok w feedzie podopiecznego (swagger, testy integracyjne i e2e)

This commit is contained in:
tisachi
2026-11-05 19:31:16 +01:00
parent e21d7aac0e
commit 600c3f8c68
11 changed files with 132 additions and 2 deletions

View File

@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "NotificationType" ADD VALUE 'TRAINER_COMMENT';

View File

@@ -261,6 +261,7 @@ enum NotificationType {
PLAN_READY
PLAN_SHARED
GYM_DELETED
TRAINER_COMMENT
}
/// Osobiste powiadomienie generowane przez system. `payload` jest self-contained

View File

@@ -674,6 +674,7 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* /trainer/trainees/{userId}/comments:
* post:
* summary: Trainer comment on the trainee (anchored to a session / exercise)
* description: Creates the comment and a TRAINER_COMMENT feed notification for the trainee.
* tags: [Trainer]
* responses:
* 201: { description: Created }

View File

@@ -1,6 +1,7 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, notFound } from '../lib/errors.js';
import { assertActiveTrainee } from './trainer.js';
import { createNotification } from './feed.js';
export interface CommentInput {
body: string;
@@ -47,6 +48,24 @@ export async function addTraineeComment(
body: input.body,
},
});
// Notification for the trainee ("Aktualności" feed). The payload is a
// self-contained snapshot (GYM_DELETED pattern) so it survives comment deletion.
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 ||
'';
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 },
});
return { comment };
}

View File

@@ -1003,7 +1003,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).',
'Announcement items carry author attribution: authorId, authorName, authorRole (ADMIN | OWNER | TRAINER; null for system-generated). Notification types: PLAN_READY, PLAN_SHARED, GYM_DELETED, TRAINER_COMMENT (payload: sessionId, trainerName; deeplink /profile/history).',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'limit', in: 'query', schema: { type: 'integer', default: 20 } },

View File

@@ -193,6 +193,76 @@ describe('comments — under executed exercises', () => {
});
});
describe('TRAINER_COMMENT notifications (feed)', () => {
let noteCommentId: string;
let notificationId: string;
it('notifies the trainee with a TRAINER_COMMENT entry after a trainer comment', async () => {
const before = await app
.get('/api/v1/me/feed/unread-count')
.set('Authorization', `Bearer ${trainee.token}`);
expect(before.status).toBe(200);
const res = await app
.post(`/api/v1/trainer/trainees/${trainee.id}/comments`)
.set('Authorization', `Bearer ${trainer.token}`)
.send({ body: 'Zwróć uwagę na kolana', sessionId: traineeSessionId, sessionExerciseId: traineeExerciseId });
expect(res.status).toBe(201);
noteCommentId = res.body.comment.id;
const note = await prisma.notification.findFirst({
where: { userId: trainee.id, type: 'TRAINER_COMMENT' },
orderBy: { createdAt: 'desc' },
});
expect(note).toBeTruthy();
notificationId = note!.id;
expect(note!.title).toBe('Trener Tomasz dodał komentarz do treningu');
expect(note!.payload).toMatchObject({ sessionId: traineeSessionId, trainerName: 'Tomasz' });
const feed = await app
.get('/api/v1/me/feed')
.set('Authorization', `Bearer ${trainee.token}`);
expect(feed.status).toBe(200);
const item = feed.body.items.find((i: { id: string }) => i.id === notificationId);
expect(item).toMatchObject({
source: 'notification',
type: 'TRAINER_COMMENT',
read: false,
payload: { sessionId: traineeSessionId },
});
const after = await app
.get('/api/v1/me/feed/unread-count')
.set('Authorization', `Bearer ${trainee.token}`);
expect(after.status).toBe(200);
expect(after.body.unreadCount).toBe(before.body.unreadCount + 1);
});
it('keeps the notification after the trainer deletes the comment', async () => {
const del = await app
.delete(`/api/v1/trainer/trainees/${trainee.id}/comments/${noteCommentId}`)
.set('Authorization', `Bearer ${trainer.token}`);
expect(del.status).toBe(204);
const note = await prisma.notification.findUnique({ where: { id: notificationId } });
expect(note).toBeTruthy();
});
it('does not notify the trainee for their own comment (addMyComment)', async () => {
const count = await prisma.notification.count({
where: { userId: trainee.id, type: 'TRAINER_COMMENT' },
});
const res = await app
.post('/api/v1/me/comments')
.set('Authorization', `Bearer ${trainee.token}`)
.send({ body: 'własna notatka', sessionId: traineeSessionId });
expect(res.status).toBe(201);
const after = await prisma.notification.count({
where: { userId: trainee.id, type: 'TRAINER_COMMENT' },
});
expect(after).toBe(count);
});
});
describe('POST /me/comments', () => {
it('creates a comment on my own session + exercise', async () => {
const res = await app

View File

@@ -806,7 +806,7 @@ export interface ConversationThread {
}
// ---------- aktualności (feed) ----------
export type NotificationType = 'PLAN_READY' | 'PLAN_SHARED' | 'GYM_DELETED';
export type NotificationType = 'PLAN_READY' | 'PLAN_SHARED' | 'GYM_DELETED' | 'TRAINER_COMMENT';
export interface FeedNotificationItem {
source: 'notification';

View File

@@ -4,6 +4,7 @@ import {
Building2,
Dumbbell,
Megaphone,
MessageSquare,
Share2,
type LucideIcon,
} from 'lucide-react';
@@ -22,6 +23,12 @@ export function feedDeeplink(item: FeedItem): string | null {
const planId = item.payload.planId;
return typeof planId === 'string' ? `/plans/${planId}` : null;
}
if (item.type === 'TRAINER_COMMENT') {
const sessionId = item.payload.sessionId;
return typeof sessionId === 'string'
? `/profile/history?session=${sessionId}`
: '/profile/history';
}
return null;
}
return `/announcements/${item.id}`;
@@ -37,6 +44,8 @@ export function feedItemIcon(item: FeedItem): { Icon: LucideIcon; label: string
return { Icon: Share2, label: i18n.t('feed:itemType.sharedPlan') };
case 'GYM_DELETED':
return { Icon: Building2, label: i18n.t('feed:itemType.gymDeleted') };
case 'TRAINER_COMMENT':
return { Icon: MessageSquare, label: i18n.t('feed:itemType.trainerComment') };
}
}
switch (item.kind) {

View File

@@ -9,6 +9,7 @@
"planFromTrainer": "Plan from trainer",
"sharedPlan": "Shared plan",
"gymDeleted": "Deleted gym",
"trainerComment": "Trainer comment",
"announcement": "Announcement",
"hoursChange": "Hours change",
"exception": "Schedule exception"

View File

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

View File

@@ -139,6 +139,32 @@ 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 }) => {
mockApi(page, {
feed: {
items: [
{
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' },
read: false,
createdAt: iso(5),
},
],
},
});
await login(page);
// podpis typu wpisu + klik = deeplink do historii (z kotwicą sesji z payloadu)
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();
});
test('Aktualności: klik w ogłoszenie prowadzi na stronę ogłoszenia z powrotem do listy', async ({
page,
}) => {