Komunikator: karta kontekstu rozmowcy (trening) i akcja 'Otworz panel podopiecznego' w watku (mostek do kokpitu treningowego)

This commit is contained in:
tisachi
2026-09-11 17:55:57 +02:00
parent d211b092f2
commit 2ef002668e
4 changed files with 199 additions and 2 deletions

View File

@@ -1,7 +1,7 @@
import { Fragment, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { Paperclip, Send, X } from 'lucide-react';
import { Paperclip, Send, UserRound, X } from 'lucide-react';
import {
sendMessage,
useHistory,
@@ -27,6 +27,7 @@ import {
import { useToast } from '../../components/toast';
import { useTopbar } from '../../topbar';
import { Avatar } from '../../components/Avatar';
import { ThreadContextCard } from './ThreadContextCard';
/* Bąbelek wiadomości: treść + załącznik + czas (mine = prawo, other = lewo). */
function MessageBubble({
@@ -184,7 +185,6 @@ function AttachmentPickerModal({
}
export default function MessageThread() {
useTopbar({ title: 'Komunikator', back: '/messages' });
const { coachingId = '' } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
@@ -193,6 +193,17 @@ export default function MessageThread() {
const myId = meData?.user.id;
const { data: thread, isLoading, error } = useMessages(coachingId);
/* Trener: mostek do kokpitu treningowego (panel podopiecznego); podopieczny
nie ma panelu trenera — akcja tylko dla roli trainer. */
useTopbar({
title: 'Komunikator',
back: '/messages',
actions:
thread?.role === 'trainer' && thread.other.id
? [{ label: 'Otwórz panel podopiecznego', icon: UserRound, to: `/trainees/${thread.other.id}` }]
: [],
});
const [body, setBody] = useState('');
const [pickerOpen, setPickerOpen] = useState(false);
const [attachSessionId, setAttachSessionId] = useState('');
@@ -282,6 +293,8 @@ export default function MessageThread() {
actions={<BackButton onClick={() => navigate('/messages')} />}
/>
{!error && thread && <ThreadContextCard thread={thread} />}
<Card>
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
{!error && (thread?.messages.length ?? 0) === 0 && (

View File

@@ -0,0 +1,130 @@
import { Flame } from 'lucide-react';
import { useDashboard, useTrainee } from '../../api/queries';
import type { ConversationThread } from '../../api/types';
import { MUSCLE_NAMES, TRAINEE_FLAGS } from '../../lib/labels';
import { fmtDate, fmtDateTime } from '../../lib/format';
import { Badge, Card, Muted, ProgressBar, SectionHeader, Skeleton, StatTile } from '../../components/ui';
/* Karta kontekstu rozmówcy — lekki kontekst treningowy (3–5 faktów) wspierający
rozmowę. Głębokie dane zostają w panelu podopiecznego (trener) — tu tylko
podsumowanie, bez duplikacji zakładek/historii/postępów. */
function ContextSkeleton() {
return (
<Card>
<Skeleton className="h-5 w-48" />
<div className="mt-3 grid grid-cols-2 gap-4 sm:grid-cols-3">
<Skeleton className="h-14" />
<Skeleton className="h-14" />
<Skeleton className="h-14" />
</div>
</Card>
);
}
/* Trener: kontekst treningowy podopiecznego (killstreak, sesje, plan, flagi). */
function TrainerContext({ traineeId }: { traineeId: string }) {
const { data, isLoading } = useTrainee(traineeId);
if (isLoading) return <ContextSkeleton />;
if (!data) return null;
return (
<Card>
<SectionHeader title="Trening podopiecznego" />
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 sm:gap-5">
<StatTile
label="Killstreak"
value={
<span className="inline-flex items-center gap-1.5">
<Flame className={`w-4 h-4 ${data.killstreak > 0 ? 'text-accent-text' : 'text-dim'}`} />
{data.killstreak}
</span>
}
/>
<StatTile label="Ostatnia sesja" value={data.lastSessionAt ? fmtDateTime(data.lastSessionAt) : '—'} />
<StatTile
label="Następny trening"
value={
data.nextTraining
? `${fmtDate(data.nextTraining.date)} · ${data.nextTraining.exercises
.map((e) => MUSCLE_NAMES[e.muscle] || e.muscle)
.join(', ')}`
: '—'
}
/>
</div>
{data.activePlan && (
<div className="mt-4">
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
<strong className="text-[0.95rem]">{data.activePlan.title}</strong>
{data.progress && (
<Muted className="text-[0.8125rem]">
{data.progress.completed}/{data.progress.total} dni · {data.progress.percent}%
</Muted>
)}
</div>
{data.progress && <ProgressBar percent={data.progress.percent} />}
</div>
)}
{data.flags.length > 0 && (
<div className="mt-4 flex flex-wrap gap-1.5">
{data.flags.map((f) => (
<Badge key={f} color={TRAINEE_FLAGS[f].color}>
{TRAINEE_FLAGS[f].label}
</Badge>
))}
</div>
)}
</Card>
);
}
/* Podopieczny: kontekst własnych treningów w tej relacji (dashboard). */
function TraineeContext() {
const { data, isLoading } = useDashboard();
if (isLoading) return <ContextSkeleton />;
if (!data) return null;
return (
<Card>
<SectionHeader title="Twoje treningi" />
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 sm:gap-5">
<StatTile
label="Killstreak"
value={
<span className="inline-flex items-center gap-1.5">
<Flame className={`w-4 h-4 ${data.killstreak > 0 ? 'text-accent-text' : 'text-dim'}`} />
{data.killstreak}
</span>
}
/>
<StatTile
label="Następny trening"
value={
data.nextTraining
? `${fmtDate(data.nextTraining.date)} · ${data.nextTraining.exercises
.map((e) => MUSCLE_NAMES[e.muscle] || e.muscle)
.join(', ')}`
: '—'
}
/>
</div>
{data.activePlan && (
<div className="mt-4">
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
<strong className="text-[0.95rem]">{data.activePlan.title}</strong>
{data.progress && (
<Muted className="text-[0.8125rem]">
{data.progress.completed}/{data.progress.total} dni · {data.progress.percent}%
</Muted>
)}
</div>
{data.progress && <ProgressBar percent={data.progress.percent} />}
</div>
)}
</Card>
);
}
export function ThreadContextCard({ thread }: { thread: ConversationThread }) {
if (thread.role === 'trainer') return <TrainerContext traineeId={thread.other.id} />;
return <TraineeContext />;
}

View File

@@ -103,6 +103,24 @@ test('komunikator: grupowanie wg roli z zakładkami Podopieczni/Trenerzy', async
await expect(page.getByText('Anna Nowak')).not.toBeVisible();
});
test('komunikator: karta kontekstu treningowego podopiecznego i mostek do panelu', async ({ page }) => {
mockApi(page, { me: trainerMe() });
await login(page);
await page.getByRole('link', { name: /Komunikator/ }).click();
await page.getByRole('button', { name: /Anna Nowak/ }).click();
await expect(page.getByRole('heading', { name: 'Anna Nowak' })).toBeVisible();
// karta kontekstu: lekkie podsumowanie treningu (TEST_TRAINEE_DETAIL)
await expect(page.getByText('Trening podopiecznego')).toBeVisible();
await expect(page.getByText('Plan testowy')).toBeVisible();
await expect(page.getByText('Zerowany streak')).toBeVisible();
// mostek do kokpitu treningowego (akcja w topmenu)
await page.getByRole('button', { name: 'Otwórz panel podopiecznego' }).click();
await expect(page.getByRole('heading', { name: 'Anna Nowak' })).toBeVisible();
await expect(page.getByText('Podstawowe informacje')).toBeVisible();
});
test('wątek: wysyłka wiadomości', async ({ page }) => {
mockApi(page, { me: trainerMe() });
await login(page);

View File

@@ -149,6 +149,21 @@ function mockApi() {
],
});
if (url.includes('/trainer/trainees/trainee-1/history')) return jsonResponse(200, TRAINEE_HISTORY);
if (url.includes('/trainer/trainees/trainee-1'))
return jsonResponse(200, {
coachingId: 'coaching-1',
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
socialMedia: null,
gyms: [{ id: 'gym-1', name: 'Żelazna Świątynia' }],
activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01' },
progress: { completed: 5, total: 14, percent: 36 },
killstreak: 3,
nextTraining: { dayId: 'day-1', date: '2026-08-26', exercises: [{ name: 'Przysiady', muscle: 'legs' }] },
extra: null,
missing: null,
lastSessionAt: '2026-08-24T08:30:00.000Z',
flags: ['no_session_7d'],
});
if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] });
if (url.includes('/me')) return jsonResponse(200, { user: TRAINER, memberships: [] });
if (url.includes('/dashboard'))
@@ -213,6 +228,27 @@ describe('Message thread — wątek', () => {
expect(screen.getByText('Dobrze się czuję')).toBeInTheDocument();
});
it('pokazuje kartę kontekstu treningowego podopiecznego i akcję „Otwórz panel podopiecznego”', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToThread(user);
// karta kontekstu: sekcja + plan + flaga + killstreak
expect(await screen.findByText('Trening podopiecznego')).toBeInTheDocument();
expect(screen.getByText('Plan testowy')).toBeInTheDocument();
expect(screen.getByText('Brak sesji 7 dni')).toBeInTheDocument();
expect(screen.getByText('3')).toBeInTheDocument();
// mostek do kokpitu treningowego (grupa Akcje w topmenu)
const openPanel = screen.getByRole('button', { name: 'Otwórz panel podopiecznego' });
expect(openPanel).toBeInTheDocument();
await user.click(openPanel);
// lądowanie w panelu podopiecznego (zakładka Przegląd)
expect(await screen.findByRole('heading', { name: 'Anna Nowak' })).toBeInTheDocument();
expect(screen.getByText('Podstawowe informacje')).toBeInTheDocument();
});
it('wysyła wiadomość (Wyślij)', async () => {
mockApi();
const user = userEvent.setup();