diff --git a/api/src/routes/messages.ts b/api/src/routes/messages.ts index 9ccb002..2b611de 100644 --- a/api/src/routes/messages.ts +++ b/api/src/routes/messages.ts @@ -25,7 +25,7 @@ export function createMessageRoutes({ prisma }: AppDeps) { * @openapi * /messages/conversations: * get: - * summary: My ACTIVE coaching relations as conversations (last message + unread count) + * summary: My ACTIVE coaching relations as conversations (my role + last message + unread count) * tags: [Messages] * responses: * 200: { description: OK } diff --git a/api/src/services/messages.ts b/api/src/services/messages.ts index 1fa0719..29cf96c 100644 --- a/api/src/services/messages.ts +++ b/api/src/services/messages.ts @@ -3,6 +3,8 @@ import { badRequest, notFound } from '../lib/errors.js'; export interface ConversationListItem { coachingId: string; + /** Moja rola w relacji (odwrotna dla drugiej strony: podopieczny/trener). */ + role: 'trainer' | 'trainee'; other: { id: string; firstName: string | null; lastName: string | null; nickname: string | null }; lastMessage: { body: string; createdAt: string; senderId: string } | null; unreadCount: number; @@ -65,6 +67,7 @@ export async function listConversations(prisma: PrismaClient, userId: string) { const last = lastByCoaching.get(c.id) ?? null; return { coachingId: c.id, + role: c.trainerId === userId ? ('trainer' as const) : ('trainee' as const), other: other ? { id: other.id, firstName: other.firstName, lastName: other.lastName, nickname: other.nickname } : { id: otherId, firstName: null, lastName: null, nickname: null }, diff --git a/api/test/integration/messages.test.ts b/api/test/integration/messages.test.ts index d9d3f57..46b69f3 100644 --- a/api/test/integration/messages.test.ts +++ b/api/test/integration/messages.test.ts @@ -137,6 +137,7 @@ describe('messages — trainer↔trainee conversations', () => { expect(asTrainer.body.conversations).toHaveLength(1); expect(asTrainer.body.conversations[0]).toMatchObject({ coachingId, + role: 'trainer', other: { id: trainee.id, firstName: 'Anna', nickname: 'annafit' }, unreadCount: 1, }); @@ -151,6 +152,7 @@ describe('messages — trainer↔trainee conversations', () => { expect(asTrainee.body.conversations).toHaveLength(1); expect(asTrainee.body.conversations[0]).toMatchObject({ coachingId, + role: 'trainee', other: { id: trainer.id, firstName: 'Tomasz', nickname: null }, unreadCount: 0, }); diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 285e740..c928580 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -400,6 +400,8 @@ export interface CircumferenceSeries { // ---------- komunikator (messages) ---------- export interface Conversation { coachingId: string; + /** Moja rola w relacji (odwrotna dla rozmówcy: podopieczny/trener). */ + role: 'trainer' | 'trainee'; other: { id: string; firstName: string | null; lastName: string | null; nickname: string | null }; lastMessage: { body: string; createdAt: string; senderId: string } | null; unreadCount: number; diff --git a/app/src/pages/messages/Messages.tsx b/app/src/pages/messages/Messages.tsx index 891c4f0..231cdf2 100644 --- a/app/src/pages/messages/Messages.tsx +++ b/app/src/pages/messages/Messages.tsx @@ -1,15 +1,38 @@ -import { useEffect } from 'react'; +import { useEffect, useMemo, useState } from 'react'; import { useNavigate } from 'react-router-dom'; -import { MessageSquare } from 'lucide-react'; +import { ArrowUpDown, ChevronDown, MessageSquare, Users } from 'lucide-react'; import { useConversations, useMe } from '../../api/queries'; import { displayName, timeAgo } from '../../lib/format'; -import { Card, EmptyState, ErrorText, Skeleton } from '../../components/ui'; +import { cn } from '../../lib/utils'; +import { + Badge, + Button, + Card, + EmptyState, + ErrorText, + H3, + Skeleton, + Tabs, +} from '../../components/ui'; import { Avatar } from '../../components/Avatar'; import { useListSearch } from '../../store/list-search'; import { useTopbar } from '../../topbar'; +/* Opcje sortowania rozmów — komunikacyjne (inne niż metryki treningowe w /trainees) */ +const SORT_OPTIONS = [ + { id: 'none', label: 'Brak' }, + { id: 'unread', label: 'Nieprzeczytane' }, + { id: 'name', label: 'Nazwa' }, +] as const; +type SortKey = (typeof SORT_OPTIONS)[number]['id']; + +/* Grupy rozmów wg roli rozmówcy: ja=trener → podopieczni; ja=podopieczny → trenerzy */ +const ROLE_GROUPS = [ + { id: 'trainees', label: 'Podopieczni', myRole: 'trainer' as const }, + { id: 'trainers', label: 'Trenerzy', myRole: 'trainee' as const }, +]; + export default function Messages() { - useTopbar({ title: 'Komunikator', search: 'messages' }); const navigate = useNavigate(); const { data, isLoading, error } = useConversations(); const { data: meData } = useMe(); @@ -18,6 +41,108 @@ export default function Messages() { const setQuery = useListSearch((s) => s.setQuery); useEffect(() => () => setQuery('messages', ''), [setQuery]); + const [sortKey, setSortKey] = useState('none'); + const [sortOpen, setSortOpen] = useState(false); + const [groupByRole, setGroupByRole] = useState(false); + const [activeRoleTab, setActiveRoleTab] = useState(null); + + useTopbar({ + title: 'Komunikator', + search: 'messages', + filters: [ + /* sortowanie: przycisk „Sortuj: ” + rozwijany select (kompaktowo w grupie filtrów) */ +
+ + {sortOpen && ( + <> +
setSortOpen(false)} /> + {/* telefon: panel filtrów otwiera się w górę od dolnego paska — dropdown też w górę */} +
+ {SORT_OPTIONS.map((s) => ( + + ))} +
+ + )} +
, + /* grupowanie wg roli rozmówcy — opcja (domyślnie lista płaska) */ + , + ], + filterActive: sortKey !== 'none' || groupByRole, + }); + + const conversations = data?.conversations ?? []; + const q = query.toLowerCase(); + const filtered = useMemo(() => { + const list = conversations.filter((c) => !q || displayName(c.other).toLowerCase().includes(q)); + const byName = (a: (typeof list)[number], b: (typeof list)[number]) => + displayName(a.other).localeCompare(displayName(b.other), 'pl'); + const byLastMessage = (a: (typeof list)[number], b: (typeof list)[number]) => + (b.lastMessage?.createdAt ?? '').localeCompare(a.lastMessage?.createdAt ?? ''); + switch (sortKey) { + case 'unread': + list.sort( + (a, b) => b.unreadCount - a.unreadCount || byLastMessage(a, b) || byName(a, b), + ); + break; + case 'name': + list.sort(byName); + break; + default: + break; // bez sortowania — kolejność z API (najnowsze rozmowy najpierw) + } + return list; + }, [conversations, q, sortKey]); + + // grupy wg roli rozmówcy (tylko niepuste; stała kolejność: Podopieczni, Trenerzy) + const roleGroups = useMemo( + () => + ROLE_GROUPS.map((g) => ({ + ...g, + items: filtered.filter((c) => c.role === g.myRole), + })).filter((g) => g.items.length > 0), + [filtered], + ); + // aktywna zakładka roli (domyślnie pierwsza; fallback gdy grupa zniknie np. po wyszukiwarce) + const activeGroup = roleGroups.find((g) => g.id === activeRoleTab) ?? roleGroups[0]; + if (isLoading) { return (
@@ -27,89 +152,109 @@ export default function Messages() { ); } - const conversations = data?.conversations ?? []; - const q = query.toLowerCase(); - const filtered = conversations - .filter((c) => !q || displayName(c.other).toLowerCase().includes(q)) - .sort((a, b) => { - const ta = a.lastMessage?.createdAt ?? ''; - const tb = b.lastMessage?.createdAt ?? ''; - return tb.localeCompare(ta); - }); + const renderRows = (items: typeof filtered) => ( +
+ {items.map((c) => { + const name = displayName(c.other); + const unread = c.unreadCount > 0; + const mine = c.lastMessage?.senderId === myId; + return ( + + ); + })} +
+ ); return ( - + <> {error && Błąd: {(error as Error).message}} {!error && conversations.length === 0 && ( - + + + )} {!error && conversations.length > 0 && filtered.length === 0 && ( -

Brak wyników dla podanego zapytania.

+ +

Brak wyników dla podanego zapytania.

+
)} {!error && filtered.length > 0 && ( -
- {filtered.map((c) => { - const name = displayName(c.other); - const unread = c.unreadCount > 0; - const mine = c.lastMessage?.senderId === myId; - return ( - - ); - })} -
+ groupByRole && activeGroup ? ( + <> + {/* lista ról rozmówców jako zakładki — łatwiej się odnaleźć */} +
+ ({ id: g.id, label: g.label }))} + active={activeGroup.id} + onChange={setActiveRoleTab} + /> +
+
+
+

{activeGroup.label}

+ {activeGroup.items.length} +
+ {renderRows(activeGroup.items)} +
+ + ) : ( + {renderRows(filtered)} + ) )} -
+ ); } diff --git a/app/test/e2e/messages.spec.ts b/app/test/e2e/messages.spec.ts index 1d5cee3..16e838f 100644 --- a/app/test/e2e/messages.spec.ts +++ b/app/test/e2e/messages.spec.ts @@ -45,6 +45,64 @@ test('wyszukiwarka w menu kontekstowym filtruje listę rozmów', async ({ page } await expect(page.getByText('Anna Nowak')).toBeVisible(); }); +test('komunikator: sortowanie wg nieprzeczytanych i nazwy', async ({ page }) => { + mockApi(page, { me: trainerMe() }); + await login(page); + await page.getByRole('link', { name: /Komunikator/ }).click(); + await expect(page.getByText('Anna Nowak')).toBeVisible(); + + // nieprzeczytane: Anna (2) wyżej niż Piotr (0) + await page.getByRole('button', { name: 'Sortuj: Brak' }).click(); + await page.getByRole('button', { name: 'Nieprzeczytane' }).click(); + await expect(page.getByRole('button', { name: 'Sortuj: Nieprzeczytane' })).toBeVisible(); + expect(await page.getByText('Anna Nowak').evaluate((el) => el.getBoundingClientRect().top)).toBeLessThan( + await page.getByText('Piotr Kowal').evaluate((el) => el.getBoundingClientRect().top), + ); + + // nazwa: alfabetycznie Anna < Piotr + await page.getByRole('button', { name: 'Sortuj: Nieprzeczytane' }).click(); + await page.getByRole('button', { name: 'Nazwa' }).click(); + await expect(page.getByRole('button', { name: 'Sortuj: Nazwa' })).toBeVisible(); +}); + +test('komunikator: grupowanie wg roli z zakładkami Podopieczni/Trenerzy', async ({ page }) => { + mockApi(page, { + me: trainerMe(), + conversations: { + conversations: [ + { + coachingId: 'coaching-1', + role: 'trainer', + other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null }, + lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' }, + unreadCount: 0, + }, + { + coachingId: 'coaching-3', + role: 'trainee', + other: { id: 'trainer-2', firstName: 'Tomasz', lastName: 'Kowalczyk', nickname: null }, + lastMessage: { body: 'Hej, omówmy plan', createdAt: '2026-09-01T09:00:00.000Z', senderId: 'trainer-2' }, + unreadCount: 0, + }, + ], + }, + }); + await login(page); + await page.getByRole('link', { name: /Komunikator/ }).click(); + + await page.getByRole('button', { name: 'Grupuj wg roli' }).click(); + // domyślnie pierwsza grupa: Podopieczni + await expect(page.getByRole('button', { name: 'Podopieczni' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Trenerzy' })).toBeVisible(); + await expect(page.getByText('Anna Nowak')).toBeVisible(); + await expect(page.getByText('Tomasz Kowalczyk')).not.toBeVisible(); + + // przełączenie na Trenerzy + await page.getByRole('button', { name: 'Trenerzy' }).click(); + await expect(page.getByText('Tomasz Kowalczyk')).toBeVisible(); + await expect(page.getByText('Anna Nowak')).not.toBeVisible(); +}); + test('wątek: wysyłka wiadomości', async ({ page }) => { mockApi(page, { me: trainerMe() }); await login(page); diff --git a/app/test/e2e/mock-api.ts b/app/test/e2e/mock-api.ts index ecb4152..7b5cb2e 100644 --- a/app/test/e2e/mock-api.ts +++ b/app/test/e2e/mock-api.ts @@ -367,12 +367,14 @@ export const TEST_CONVERSATIONS = { conversations: [ { coachingId: 'coaching-1', + role: 'trainer', other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null }, lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' }, unreadCount: 2, }, { coachingId: 'coaching-2', + role: 'trainer', other: { id: 'trainee-2', firstName: 'Piotr', lastName: 'Kowal', nickname: null }, lastMessage: null, unreadCount: 0, diff --git a/app/test/e2e/nickname-social.spec.ts b/app/test/e2e/nickname-social.spec.ts index 6bbcbf4..f778625 100644 --- a/app/test/e2e/nickname-social.spec.ts +++ b/app/test/e2e/nickname-social.spec.ts @@ -106,6 +106,7 @@ test('komunikator: nick rozmówcy w liście i w wątku', async ({ page }) => { conversations: [ { coachingId: 'coaching-1', + role: 'trainer', other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: 'annanowak' }, lastMessage: { body: 'Dobrze się czuję', diff --git a/app/test/message-thread.test.tsx b/app/test/message-thread.test.tsx index 923e332..bbf13c0 100644 --- a/app/test/message-thread.test.tsx +++ b/app/test/message-thread.test.tsx @@ -141,6 +141,7 @@ function mockApi() { conversations: [ { coachingId: 'coaching-1', + role: 'trainer', other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' }, lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' }, unreadCount: 0, diff --git a/app/test/messages.test.tsx b/app/test/messages.test.tsx index fc9c728..37a1a14 100644 --- a/app/test/messages.test.tsx +++ b/app/test/messages.test.tsx @@ -30,16 +30,25 @@ const TRAINER: User = { const CONVERSATIONS: Conversation[] = [ { coachingId: 'coaching-1', + role: 'trainer', other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' }, lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' }, unreadCount: 2, }, { coachingId: 'coaching-2', + role: 'trainer', other: { id: 'trainee-2', firstName: 'Piotr', lastName: 'Kowal' }, lastMessage: null, unreadCount: 0, }, + { + coachingId: 'coaching-3', + role: 'trainee', + other: { id: 'trainer-2', firstName: 'Tomasz', lastName: 'Kowalczyk' }, + lastMessage: { body: 'Hej, omówmy plan', createdAt: '2026-09-01T09:00:00.000Z', senderId: 'trainer-2' }, + unreadCount: 1, + }, ]; function jsonResponse(status: number, body: unknown) { @@ -128,16 +137,18 @@ describe('Messages — lista rozmów', () => { expect(screen.getByText('Brak wiadomości')).toBeInTheDocument(); }); - it('oznacza własną ostatnią wiadomość „Ty:" i sortuje rozmowy od najnowszej', async () => { + it('oznacza własną ostatnią wiadomość „Ty:" i zachowuje kolejność z API (najnowsze najpierw)', async () => { const convs: Conversation[] = [ { coachingId: 'coaching-2', + role: 'trainer', other: { id: 'trainee-2', firstName: 'Piotr', lastName: 'Kowal' }, lastMessage: { body: 'Do zobaczenia', createdAt: '2026-08-25T09:00:00.000Z', senderId: 'trainer-1' }, unreadCount: 0, }, { coachingId: 'coaching-1', + role: 'trainer', other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' }, lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' }, unreadCount: 0, @@ -169,6 +180,63 @@ describe('Messages — lista rozmów', () => { expect(screen.getByText('Brak rozmów')).toBeInTheDocument(); }); + it('sortowanie wg nieprzeczytanych: rozmowy z nieprzeczytanymi na górze', async () => { + mockApi(CONVERSATIONS); + const user = userEvent.setup(); + renderApp(); + await loginToMessages(user); + + // domyślnie: kolejność z API (Anna, Piotr, Tomasz) + const rows = () => + screen.getAllByRole('button').filter((b) => /Anna Nowak|Piotr Kowal|Tomasz Kowalczyk/.test(b.textContent ?? '')); + expect(rows()[0]).toHaveTextContent('Anna Nowak'); + + await user.click(screen.getByRole('button', { name: 'Sortuj: Brak' })); + await user.click(screen.getByRole('button', { name: 'Nieprzeczytane' })); + expect(screen.getByRole('button', { name: 'Sortuj: Nieprzeczytane' })).toBeInTheDocument(); + + // Anna (2 nieprzeczytane) > Tomasz (1) > Piotr (0) + expect(rows()[0]).toHaveTextContent('Anna Nowak'); + expect(rows()[1]).toHaveTextContent('Tomasz Kowalczyk'); + expect(rows()[2]).toHaveTextContent('Piotr Kowal'); + }); + + it('sortowanie wg nazwy: rozmowy alfabetycznie', async () => { + mockApi(CONVERSATIONS); + const user = userEvent.setup(); + renderApp(); + await loginToMessages(user); + + await user.click(screen.getByRole('button', { name: 'Sortuj: Brak' })); + await user.click(screen.getByRole('button', { name: 'Nazwa' })); + + const rows = screen.getAllByRole('button').filter((b) => /Anna Nowak|Piotr Kowal|Tomasz Kowalczyk/.test(b.textContent ?? '')); + expect(rows[0]).toHaveTextContent('Anna Nowak'); + expect(rows[1]).toHaveTextContent('Piotr Kowal'); + expect(rows[2]).toHaveTextContent('Tomasz Kowalczyk'); + }); + + it('grupowanie wg roli: zakładki Podopieczni/Trenerzy z rozmowami w odpowiednich grupach', async () => { + mockApi(CONVERSATIONS); + const user = userEvent.setup(); + renderApp(); + await loginToMessages(user); + + await user.click(screen.getByRole('button', { name: 'Grupuj wg roli' })); + + // domyślnie pierwsza grupa: Podopieczni (Anna + Piotr) + expect(screen.getByRole('button', { name: 'Podopieczni' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Trenerzy' })).toBeInTheDocument(); + expect(screen.getByText('Anna Nowak')).toBeInTheDocument(); + expect(screen.getByText('Piotr Kowal')).toBeInTheDocument(); + expect(screen.queryByText('Tomasz Kowalczyk')).not.toBeInTheDocument(); + + // przełączenie na Trenerzy + await user.click(screen.getByRole('button', { name: 'Trenerzy' })); + expect(screen.getByText('Tomasz Kowalczyk')).toBeInTheDocument(); + expect(screen.queryByText('Anna Nowak')).not.toBeInTheDocument(); + }); + it('wyszukiwarka w menu kontekstowym filtruje listę rozmów', async () => { mockApi(CONVERSATIONS); const user = userEvent.setup();