Api+App: komentarze usera - statusy przeczytania i typ USER_COMMENT (feed, profil, panel trenera)
This commit is contained in:
@@ -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}:
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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: {
|
||||
|
||||
Reference in New Issue
Block a user