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

@@ -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}
/>