From a230dee285b84cd21762eb29139b01899befefb8 Mon Sep 17 00:00:00 2001 From: tisachi Date: Tue, 27 Oct 2026 06:22:17 +0100 Subject: [PATCH] =?UTF-8?q?App+API:=20ogloszenia=20=E2=80=94=20strona=20sz?= =?UTF-8?q?czegolow=20z=20autorem=20(GET=20/me/feed/announcements/:id=20oz?= =?UTF-8?q?nacza=20przeczytane),=20skracanie=20list=20do=203=20lini=20i=20?= =?UTF-8?q?menu=20kontekstowe=20Aktualnosci=20w=20topbarze=20(wyszukiwarka?= =?UTF-8?q?,=20filtr=20typu,=20filtr=20okresu=20z=20kalendarzowym=20selekt?= =?UTF-8?q?orem=20miesiaca,=20akcja=20Oznacz=20wszystkie;=20wspoldzielony?= =?UTF-8?q?=20FilterDropdown;=20swagger=20+=20testy=20unit/integracyjne/e2?= =?UTF-8?q?e)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/src/routes/feed.ts | 19 + api/src/services/announcements.ts | 9 +- api/src/services/feed.ts | 187 ++++- api/src/swagger.ts | 14 + api/test/integration/feed.test.ts | 123 ++- app/src/App.tsx | 2 + app/src/api/queries.ts | 13 + app/src/api/types.ts | 27 +- app/src/components/FeedItemRow.tsx | 8 +- app/src/components/FilterDropdown.tsx | 70 ++ app/src/i18n/locales/en/common.json | 1 + app/src/i18n/locales/en/feed.json | 24 +- app/src/i18n/locales/en/gyms.json | 3 +- app/src/i18n/locales/pl/common.json | 1 + app/src/i18n/locales/pl/feed.json | 24 +- app/src/i18n/locales/pl/gyms.json | 3 +- .../announcements/AnnouncementDetail.tsx | 78 ++ app/src/pages/announcements/Announcements.tsx | 98 ++- app/src/pages/gyms/GymAnnouncementsPage.tsx | 36 +- app/src/pages/plans/Plans.tsx | 74 +- app/src/store/list-search.ts | 4 +- app/src/topbar/Topbar.tsx | 1 + app/test/announcement-detail.test.tsx | 110 +++ app/test/e2e/feed.spec.ts | 75 +- app/test/e2e/mock-api.ts | 758 ++++++++++++++---- app/test/gym-detail.test.tsx | 10 +- 26 files changed, 1504 insertions(+), 268 deletions(-) create mode 100644 app/src/components/FilterDropdown.tsx create mode 100644 app/src/pages/announcements/AnnouncementDetail.tsx create mode 100644 app/test/announcement-detail.test.tsx diff --git a/api/src/routes/feed.ts b/api/src/routes/feed.ts index 4dc25ce..0fe86ea 100644 --- a/api/src/routes/feed.ts +++ b/api/src/routes/feed.ts @@ -2,6 +2,7 @@ import { Router } from 'express'; import type { AppDeps } from '../deps.js'; import { authenticate } from '../middleware/auth.js'; import { + getAnnouncementDetail, getFeed, getFeedUnreadCount, markAnnouncementRead, @@ -89,6 +90,24 @@ export function createFeedRoutes({ prisma }: AppDeps) { }), ); + /** + * @openapi + * /me/feed/announcements/{id}: + * get: + * summary: Single announcement with author info (visible to the user only); GET marks it as read + * tags: [Feed] + * responses: + * 200: { description: 'OK, returns { announcement: {...authorId, authorName, authorRole}, read: true }' } + * 404: { description: Not found or not visible } + */ + router.get( + '/announcements/:id', + asyncHandler(async (req, res) => { + const result = await getAnnouncementDetail(prisma, req.user!.id, req.params.id); + res.json(result); + }), + ); + /** * @openapi * /me/feed/announcements/{id}/read: diff --git a/api/src/services/announcements.ts b/api/src/services/announcements.ts index df99301..188cdc1 100644 --- a/api/src/services/announcements.ts +++ b/api/src/services/announcements.ts @@ -1,5 +1,6 @@ import type { PrismaClient } from '@prisma/client'; import { badRequest, forbidden, notFound } from '../lib/errors.js'; +import { authorInfos } from './feed.js'; import type { DayAvailability } from './me.js'; export interface AnnouncementInput { @@ -35,8 +36,14 @@ export async function listGymAnnouncements(prisma: PrismaClient, gymId: string, where: { gymId }, orderBy: { createdAt: 'desc' }, }); + const infos = await authorInfos(prisma, announcements); return { - announcements, + announcements: announcements.map((a) => ({ + ...a, + ...(a.authorId + ? infos.get(a.authorId) + : { authorId: null, authorName: null, authorRole: null }), + })), canManage: membership.roles.includes('OWNER'), }; } diff --git a/api/src/services/feed.ts b/api/src/services/feed.ts index 115bd07..b5d4c05 100644 --- a/api/src/services/feed.ts +++ b/api/src/services/feed.ts @@ -52,7 +52,16 @@ export interface FeedNotificationItem { createdAt: string; } -export interface FeedAnnouncementItem { +/** Rola autora ogłoszenia w sensie odbiorcy: admin platformy albo OWNER/TRENER siłowni. */ +export type AnnouncementAuthorRole = 'ADMIN' | 'OWNER' | 'TRAINER'; + +export interface AnnouncementAuthorInfo { + authorId: string | null; + authorName: string | null; + authorRole: AnnouncementAuthorRole | null; +} + +export interface FeedAnnouncementItem extends AnnouncementAuthorInfo { source: 'announcement'; id: string; kind: 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION'; @@ -75,6 +84,103 @@ async function memberGymIds(prisma: PrismaClient, userId: string): Promise m.gymId); } +type AnnouncementAuthorSelect = { + id: string; + firstName: string | null; + lastName: string | null; + isAdmin: boolean; +}; + +/** + * Pola „od kogo" dla listy ogłoszeń: zbiorcze membershipy autorów w siłowni + * (bez N+1 per wiersz) + fallback OWNER dla ręcznych ogłoszeń po utracie + * członkostwa. + */ +export async function authorInfos( + prisma: PrismaClient, + announcements: { authorId: string | null; gymId: string | null; kind: string }[], +): Promise> { + const authorIds = [ + ...new Set(announcements.map((a) => a.authorId).filter((v): v is string => !!v)), + ]; + const memberships = + authorIds.length === 0 + ? [] + : await prisma.gymMembership.findMany({ + where: { + userId: { in: authorIds }, + gymId: { + in: [...new Set(announcements.map((a) => a.gymId).filter((v): v is string => !!v))], + }, + }, + select: { userId: true, gymId: true, roles: true }, + }); + const authors = + authorIds.length === 0 + ? [] + : await prisma.user.findMany({ + where: { id: { in: authorIds } }, + select: { id: true, firstName: true, lastName: true, isAdmin: true }, + }); + const byAuthor = new Map(authors.map((u) => [u.id, u])); + const result = new Map(); + for (const a of announcements) { + if (!a.authorId) continue; + const author = byAuthor.get(a.authorId); + if (!author) continue; + const membership = memberships.find((m) => m.userId === a.authorId && m.gymId === a.gymId); + const role: AnnouncementAuthorRole | null = author.isAdmin + ? 'ADMIN' + : membership + ? membership.roles.includes('OWNER') + ? 'OWNER' + : membership.roles.includes('TRAINER') + ? 'TRAINER' + : 'OWNER' + : a.kind === 'MANUAL' + ? 'OWNER' + : null; + result.set(a.authorId, { + authorId: a.authorId, + authorName: [author.firstName, author.lastName].join(' ').trim() || null, + authorRole: role, + }); + } + return result; +} + +/** Pola „od kogo" dla pojedynczego ogłoszenia (jeden membership). */ +async function authorInfo( + prisma: PrismaClient, + author: AnnouncementAuthorSelect | null, + gymId: string | null, + kind: string, +): Promise { + if (!author) return { authorId: null, authorName: null, authorRole: null }; + const membership = gymId + ? await prisma.gymMembership.findFirst({ + where: { userId: author.id, gymId }, + select: { roles: true }, + }) + : null; + const role: AnnouncementAuthorRole | null = author.isAdmin + ? 'ADMIN' + : membership + ? membership.roles.includes('OWNER') + ? 'OWNER' + : membership.roles.includes('TRAINER') + ? 'TRAINER' + : 'OWNER' + : kind === 'MANUAL' + ? 'OWNER' + : null; + return { + authorId: author.id, + authorName: [author.firstName, author.lastName].join(' ').trim() || null, + authorRole: role, + }; +} + /** * Umerged feed „Aktualności”: osobiste powiadomienia + ogłoszenia siłowni usera * i globalne. Po `limit` z każdego źródła (kursor = `createdAt`), merge po @@ -104,10 +210,15 @@ export async function getFeed( }, orderBy: { createdAt: 'desc' }, take: limit, - include: { gym: { select: { id: true, name: true } } }, + include: { + gym: { select: { id: true, name: true } }, + author: { select: { id: true, firstName: true, lastName: true, isAdmin: true } }, + }, }), ]); + const infos = await authorInfos(prisma, announcements); + const readSet = new Set( ( await prisma.announcementRead.findMany({ @@ -127,17 +238,25 @@ export async function getFeed( read: n.readAt !== null, createdAt: n.createdAt.toISOString(), })), - ...announcements.map((a): FeedAnnouncementItem => ({ - source: 'announcement', - id: a.id, - kind: a.kind, - title: a.title, - body: a.body, - gymId: a.gymId, - gymName: a.gym?.name ?? null, - createdAt: a.createdAt.toISOString(), - read: readSet.has(a.id), - })), + ...announcements.map((a): FeedAnnouncementItem => { + const info = a.authorId + ? (infos.get(a.authorId) ?? { authorId: null, authorName: null, authorRole: null }) + : { authorId: null, authorName: null, authorRole: null }; + return { + source: 'announcement', + id: a.id, + kind: a.kind, + title: a.title, + body: a.body, + gymId: a.gymId, + gymName: a.gym?.name ?? null, + authorId: info.authorId, + authorName: info.authorName, + authorRole: info.authorRole, + createdAt: a.createdAt.toISOString(), + read: readSet.has(a.id), + }; + }), ].sort((a, b) => b.createdAt.localeCompare(a.createdAt)); const page = items.slice(0, limit); @@ -194,6 +313,48 @@ export async function markAnnouncementRead(prisma: PrismaClient, userId: string, return { ok: true }; } +/** + * Szczegóły pojedynczego ogłoszenia (strona „Aktualności -> ogłoszenie"). + * Widoczność jak w feedzie: globalne albo z siłowni usera; GET oznacza + * przeczytane (bez osobnej mutacji po stronie UI). + */ +export async function getAnnouncementDetail(prisma: PrismaClient, userId: string, id: string) { + const announcement = await prisma.announcement.findUnique({ + where: { id }, + include: { + gym: { select: { id: true, name: true } }, + author: { select: { id: true, firstName: true, lastName: true, isAdmin: true } }, + }, + }); + if (!announcement) throw notFound('Announcement not found'); + if (announcement.gymId !== null) { + const membership = await prisma.gymMembership.findFirst({ + where: { userId, gymId: announcement.gymId }, + select: { id: true }, + }); + if (!membership) throw notFound('Announcement not found'); + } + await prisma.announcementRead.upsert({ + where: { announcementId_userId: { announcementId: id, userId } }, + update: {}, + create: { announcementId: id, userId }, + }); + const info = await authorInfo(prisma, announcement.author, announcement.gymId, announcement.kind); + return { + announcement: { + id: announcement.id, + kind: announcement.kind, + title: announcement.title, + body: announcement.body, + gymId: announcement.gymId, + gymName: announcement.gym?.name ?? null, + ...info, + createdAt: announcement.createdAt.toISOString(), + }, + read: true, + }; +} + /** Oznacza wszystkie widoczne wpisy jako przeczytane (oba źródła naraz). */ export async function markFeedAllRead(prisma: PrismaClient, userId: string) { const gymIds = await memberGymIds(prisma, userId); diff --git a/api/src/swagger.ts b/api/src/swagger.ts index 4b7c079..8c639cb 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -477,6 +477,8 @@ export const openapi: Record = { get: { tags: ['Gyms'], summary: "List the gym's announcements (any member; canManage = OWNER)", + description: + 'Announcements carry author attribution: authorId, authorName, authorRole (ADMIN | OWNER | TRAINER; null for system-generated).', security: [{ bearerAuth: [] }], parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }], }, @@ -801,6 +803,8 @@ export const openapi: Record = { tags: ['Feed'], 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).', security: [{ bearerAuth: [] }], parameters: [ { name: 'limit', in: 'query', schema: { type: 'integer', default: 20 } }, @@ -835,6 +839,16 @@ export const openapi: Record = { parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], }, }, + '/me/feed/announcements/{id}': { + get: { + tags: ['Feed'], + summary: + 'Single announcement with author info (visible to the user only); GET marks it as read', + description: 'Returns { announcement: {...authorId, authorName, authorRole}, read: true }.', + security: [{ bearerAuth: [] }], + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + }, + }, '/me/feed/announcements/{id}/read': { post: { tags: ['Feed'], diff --git a/api/test/integration/feed.test.ts b/api/test/integration/feed.test.ts index 543087d..d2307bf 100644 --- a/api/test/integration/feed.test.ts +++ b/api/test/integration/feed.test.ts @@ -120,7 +120,10 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => { it('ogłoszenia siłowni: OWNER tworzy, MEMBER czyta bez prawa edycji, brak członkostwa = 404', async () => { const app = buildApp(); - const { user: owner, token: ownerToken } = await createUserWithToken(); + const { user: owner, token: ownerToken } = await createUserWithToken({ + firstName: 'Anna', + lastName: 'Kowalska', + }); const { user: member, token: memberToken } = await createUserWithToken(); const { user: stranger, token: strangerToken } = await createUserWithToken(); const created = await app @@ -143,6 +146,11 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => { expect(list.status).toBe(200); expect(list.body.canManage).toBe(false); expect(list.body.announcements).toHaveLength(1); + expect(list.body.announcements[0]).toMatchObject({ + authorId: owner.id, + authorName: 'Anna Kowalska', + authorRole: 'OWNER', + }); const memberPost = await app .post(`/api/v1/gyms/${gymId}/announcements`) @@ -333,6 +341,119 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => { expect(again.status).toBe(200); }); + it('szczegóły ogłoszenia: atrybucja autora, GET oznacza przeczytane, postronny = 404', async () => { + const app = buildApp(); + const { user: admin, token: adminToken } = await createUserWithToken({ + isAdmin: true, + firstName: 'Adam', + lastName: 'Admin', + }); + const { user: owner, token: ownerToken } = await createUserWithToken({ + firstName: 'Olgierd', + lastName: 'Właściciel', + }); + const { token: memberToken } = await createUserWithToken(); + const { token: strangerToken } = await createUserWithToken(); + const created = await app + .post('/api/v1/gyms') + .set('Authorization', `Bearer ${ownerToken}`) + .send({ name: `Szczeg. Gym ${rand()}`, location: 'Zielona Góra' }); + const gymId = created.body.gym.id as string; + await app.post(`/api/v1/gyms/${gymId}/join`).set('Authorization', `Bearer ${memberToken}`); + + const gymPost = await app + .post(`/api/v1/gyms/${gymId}/announcements`) + .set('Authorization', `Bearer ${ownerToken}`) + .send({ title: 'Dlugie ogloszenie', body: 'X'.repeat(2000) }); + expect(gymPost.status).toBe(201); + + const globalPost = await app + .post('/api/v1/admin/announcements') + .set('Authorization', `Bearer ${adminToken}`) + .send({ title: 'Przerwa platformy', body: 'W nocy nie będzie działalo.' }); + expect(globalPost.status).toBe(201); + + // feed: pola autora przy każdym ogłoszeniu widocznym członkowi + const feed = await app + .get('/api/v1/me/feed') + .set('Authorization', `Bearer ${memberToken}`); + const gymItem = feed.body.items.find( + (i: { id?: string }) => i.id === gymPost.body.announcement.id, + ); + expect(gymItem).toMatchObject({ + authorName: 'Olgierd Właściciel', + authorRole: 'OWNER', + read: false, + }); + const globalItem = feed.body.items.find( + (i: { id?: string }) => i.id === globalPost.body.announcement.id, + ); + expect(globalItem).toMatchObject({ authorName: 'Adam Admin', authorRole: 'ADMIN' }); + + // szczegóły: pełna treść + autor + automatyczne oznaczenie przeczytanego + const detail = await app + .get(`/api/v1/me/feed/announcements/${gymPost.body.announcement.id}`) + .set('Authorization', `Bearer ${memberToken}`); + expect(detail.status).toBe(200); + expect(detail.body.read).toBe(true); + expect(detail.body.announcement).toMatchObject({ + id: gymPost.body.announcement.id, + kind: 'MANUAL', + title: 'Dlugie ogloszenie', + gymName: created.body.gym.name, + authorId: owner.id, + authorName: 'Olgierd Właściciel', + authorRole: 'OWNER', + }); + expect(detail.body.announcement.body).toHaveLength(2000); + + const unread = await app + .get('/api/v1/me/feed/unread-count') + .set('Authorization', `Bearer ${memberToken}`); + expect(unread.body.unreadCount).toBe(1); + const feedAfter = await app + .get('/api/v1/me/feed') + .set('Authorization', `Bearer ${memberToken}`); + const readItem = feedAfter.body.items.find( + (i: { id?: string }) => i.id === gymPost.body.announcement.id, + ); + expect(readItem.read).toBe(true); + + // ogłoszenie systemowe: bez autora + const exc = await app + .post(`/api/v1/gyms/${gymId}/exceptions`) + .set('Authorization', `Bearer ${ownerToken}`) + .send({ date: '2027-01-01', availability: null }); + expect(exc.status).toBe(201); + const sys = await prisma.announcement.findFirst({ where: { gymId, kind: 'EXCEPTION' } }); + const sysDetail = await app + .get(`/api/v1/me/feed/announcements/${sys!.id}`) + .set('Authorization', `Bearer ${memberToken}`); + expect(sysDetail.status).toBe(200); + expect(sysDetail.body.announcement).toMatchObject({ + authorId: null, + authorName: null, + authorRole: null, + }); + + // postronny: brak widoczności = 404 (także dla globalnego nie istnieje problem — tylko per-gym) + const strangerDetail = await app + .get(`/api/v1/me/feed/announcements/${gymPost.body.announcement.id}`) + .set('Authorization', `Bearer ${strangerToken}`); + expect(strangerDetail.status).toBe(404); + + // globalne widoczne dla postronnego, autor = ADMIN + const strangerGlobal = await app + .get(`/api/v1/me/feed/announcements/${globalPost.body.announcement.id}`) + .set('Authorization', `Bearer ${strangerToken}`); + expect(strangerGlobal.status).toBe(200); + expect(strangerGlobal.body.announcement).toMatchObject({ + gymId: null, + authorName: 'Adam Admin', + authorRole: 'ADMIN', + }); + }); + it('ogłoszenia admina: globalne widoczne dla wszystkich; typ systemowy nietykalny', async () => { const app = buildApp(); const { user: admin, token: adminToken } = await createUserWithToken({ isAdmin: true }); diff --git a/app/src/App.tsx b/app/src/App.tsx index ee69dc3..d81e09d 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -32,6 +32,7 @@ import Invitations from './pages/Invitations'; import Messages from './pages/messages/Messages'; import MessageThread from './pages/messages/MessageThread'; import Announcements from './pages/announcements/Announcements'; +import AnnouncementDetail from './pages/announcements/AnnouncementDetail'; /** * Trasa tylko dla trenerów — API i tak odda 403, ale nie pokazujemy pustej @@ -115,6 +116,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index 2e78166..b808808 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -3,6 +3,7 @@ import { api } from './client'; import type { ActiveSession, ActivePresence, + AnnouncementDetail, Availability, CalendarDay, Conversation, @@ -1055,6 +1056,18 @@ export function markFeedAllRead() { return api('/me/feed/read-all', { method: 'POST' }); } +/** + * Szczegóły ogłoszenia (strona /announcements/:id). GET oznacza przeczytane + * po stronie API — strona unieważnia feed po wczytaniu, żeby zgasł badge. + */ +export function useAnnouncementDetail(id: string | undefined) { + return useQuery({ + queryKey: ['announcement', id], + queryFn: () => api<{ announcement: AnnouncementDetail }>(`/me/feed/announcements/${id}`), + enabled: !!id, + }); +} + // ---------- ogłoszenia siłowni (właściciel) ---------- export function useGymAnnouncements(gymId: string | undefined, enabled = true) { return useQuery({ diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 32e3b65..99ed325 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -695,7 +695,17 @@ export interface FeedNotificationItem { export type AnnouncementKind = 'MANUAL' | 'HOURS_CHANGE' | 'EXCEPTION'; -export interface FeedAnnouncementItem { +/** Rola autora ogłoszenia: admin platformy albo OWNER/TRENER siłowni; null = systemowe. */ +export type AnnouncementAuthorRole = 'ADMIN' | 'OWNER' | 'TRAINER'; + +/** Atrybucja „od kogo" w kontraktach list i szczegółów ogłoszeń. */ +export interface AnnouncementAuthorInfo { + authorId: string | null; + authorName: string | null; + authorRole: AnnouncementAuthorRole | null; +} + +export interface FeedAnnouncementItem extends AnnouncementAuthorInfo { source: 'announcement'; id: string; kind: AnnouncementKind; @@ -709,11 +719,20 @@ export interface FeedAnnouncementItem { export type FeedItem = FeedNotificationItem | FeedAnnouncementItem; -/** Ogłoszenie siłowni w widoku zarządzania (właściciel) i listy członków. */ -export interface GymAnnouncement { +/** Szczegóły pojedynczego ogłoszenia (GET /me/feed/announcements/:id, oznacza przeczytane). */ +export interface AnnouncementDetail extends AnnouncementAuthorInfo { id: string; + kind: AnnouncementKind; + title: string; + body: string; gymId: string | null; - authorId: string | null; + gymName: string | null; + createdAt: string; +} + +/** Ogłoszenie siłowni w widoku zarządzania (właściciel) i listy członków. */ +export interface GymAnnouncement extends AnnouncementAuthorInfo { + id: string; kind: AnnouncementKind; title: string; body: string; diff --git a/app/src/components/FeedItemRow.tsx b/app/src/components/FeedItemRow.tsx index 8cbdfdc..68ec674 100644 --- a/app/src/components/FeedItemRow.tsx +++ b/app/src/components/FeedItemRow.tsx @@ -24,7 +24,7 @@ export function feedDeeplink(item: FeedItem): string | null { } return null; } - return item.gymId ? `/gyms/${item.gymId}` : null; + return `/announcements/${item.id}`; } /** Ikona + podpis źródła wpisu (wspólna dla karty dashboardu i strony aktualności). */ @@ -59,6 +59,10 @@ export function FeedItemRow({ item, compact = false }: { item: FeedItem; compact const { push } = useToast(); const { Icon, label } = feedItemIcon(item); const to = feedDeeplink(item); + const attribution = + item.source === 'announcement' && item.authorName && item.authorRole + ? `${item.gymName ?? i18n.t('feed:platform')} · ${item.authorName} (${i18n.t('feed:authorRole.' + item.authorRole)})` + : label; const open = async () => { if (!item.read) { @@ -98,7 +102,7 @@ export function FeedItemRow({ item, compact = false }: { item: FeedItem; compact {item.title} - {label} · {timeAgo(item.createdAt)} + {attribution} · {timeAgo(item.createdAt)} {!compact && item.source === 'announcement' && ( {item.body} diff --git a/app/src/components/FilterDropdown.tsx b/app/src/components/FilterDropdown.tsx new file mode 100644 index 0000000..84d6c84 --- /dev/null +++ b/app/src/components/FilterDropdown.tsx @@ -0,0 +1,70 @@ +import { useState } from 'react'; +import type { ReactNode } from 'react'; +import { Check, ChevronDown } from 'lucide-react'; +import { Button } from './ui'; +import { cn } from '../lib/utils'; + +/** + * Otwierany panel (filtr/sort) z listą opcji; zamknięcie kliknięciem tła lub wyborem. + * Współdzielony przez strony list (Plany, Aktualności...) — kontrolka w menu + * kontekstowym topbaru. + */ +export function FilterDropdown({ + icon, + label, + active, + options, + selected, + onSelect, +}: { + icon: ReactNode; + label: string; + active: boolean; + options: { id: string; label: string }[]; + selected: string; + onSelect: (id: string) => void; +}) { + const [open, setOpen] = useState(false); + return ( +
+ + {open && ( + <> +
setOpen(false)} /> + {/* telefon: panel filtrów otwiera się w górę od dolnego paska — dropdown też w górę */} +
+ {options.map((o) => ( + + ))} +
+ + )} +
+ ); +} diff --git a/app/src/i18n/locales/en/common.json b/app/src/i18n/locales/en/common.json index 01b18a9..ec82ed8 100644 --- a/app/src/i18n/locales/en/common.json +++ b/app/src/i18n/locales/en/common.json @@ -43,6 +43,7 @@ "searchTrainees": "Search trainee", "searchInvitations": "Search invitation", "searchMessages": "Search conversation", + "searchAnnouncements": "Search announcements", "prevMonth": "Previous month", "nextMonth": "Next month", "prevMonthWithData": "Previous month with data", diff --git a/app/src/i18n/locales/en/feed.json b/app/src/i18n/locales/en/feed.json index d9c0163..70f840e 100644 --- a/app/src/i18n/locales/en/feed.json +++ b/app/src/i18n/locales/en/feed.json @@ -12,5 +12,27 @@ "announcement": "Announcement", "hoursChange": "Hours change", "exception": "Schedule exception" - } + }, + "platform": "Platform", + "systemBadge": "System", + "authorRole": { + "ADMIN": "Admin", + "OWNER": "Owner", + "TRAINER": "Trainer" + }, + "detail": { + "title": "Announcement", + "notFound": "The announcement does not exist or you no longer have access to it.", + "openGym": "Open gym" + }, + "filters": { + "typeLabel": "Type: {{label}}", + "ALL": "All", + "UNREAD": "Unread", + "ANNOUNCEMENTS": "Announcements", + "NOTIFICATIONS": "Notifications" + }, + "noResultsTitle": "No results", + "noResultsDesc": "No item matches the search or filter.", + "filterPaginationHint": "Search and filter apply to the items loaded so far." } diff --git a/app/src/i18n/locales/en/gyms.json b/app/src/i18n/locales/en/gyms.json index 701bf7f..54bb919 100644 --- a/app/src/i18n/locales/en/gyms.json +++ b/app/src/i18n/locales/en/gyms.json @@ -125,7 +125,8 @@ "publish": "Publish", "publishing": "Publishing…", "empty": "No announcements.", - "systemBadge": "System" + "systemBadge": "System", + "authorLine": "by {{name}} ({{role}})" }, "invites": { "desc": "A private gym is hidden — invite specific users.", diff --git a/app/src/i18n/locales/pl/common.json b/app/src/i18n/locales/pl/common.json index a453c12..8919a94 100644 --- a/app/src/i18n/locales/pl/common.json +++ b/app/src/i18n/locales/pl/common.json @@ -43,6 +43,7 @@ "searchTrainees": "Szukaj podopiecznego", "searchInvitations": "Szukaj zaproszenia", "searchMessages": "Szukaj rozmowy", + "searchAnnouncements": "Szukaj w aktualnościach", "prevMonth": "Poprzedni miesiąc", "nextMonth": "Następny miesiąc", "prevMonthWithData": "Poprzedni miesiąc z danymi", diff --git a/app/src/i18n/locales/pl/feed.json b/app/src/i18n/locales/pl/feed.json index c616b37..5b2f12f 100644 --- a/app/src/i18n/locales/pl/feed.json +++ b/app/src/i18n/locales/pl/feed.json @@ -12,5 +12,27 @@ "announcement": "Ogłoszenie", "hoursChange": "Zmiana godzin", "exception": "Wyjątek w godzinach" - } + }, + "platform": "Platforma", + "systemBadge": "Systemowe", + "authorRole": { + "ADMIN": "Administrator", + "OWNER": "Właściciel", + "TRAINER": "Trener" + }, + "detail": { + "title": "Ogłoszenie", + "notFound": "Ogłoszenie nie istnieje lub nie masz do niego dostępu.", + "openGym": "Otwórz siłownię" + }, + "filters": { + "typeLabel": "Typ: {{label}}", + "ALL": "Wszystkie", + "UNREAD": "Nieprzeczytane", + "ANNOUNCEMENTS": "Ogłoszenia", + "NOTIFICATIONS": "Powiadomienia" + }, + "noResultsTitle": "Brak wyników", + "noResultsDesc": "Żaden wpis nie pasuje do wyszukiwania lub filtra.", + "filterPaginationHint": "Wyszukiwanie i filtr działają na wczytanych wpisach." } diff --git a/app/src/i18n/locales/pl/gyms.json b/app/src/i18n/locales/pl/gyms.json index ad15f75..557ece7 100644 --- a/app/src/i18n/locales/pl/gyms.json +++ b/app/src/i18n/locales/pl/gyms.json @@ -129,7 +129,8 @@ "publish": "Opublikuj", "publishing": "Publikowanie…", "empty": "Brak ogłoszeń.", - "systemBadge": "Systemowe" + "systemBadge": "Systemowe", + "authorLine": "od {{name}} ({{role}})" }, "invites": { "desc": "Prywatna siłownia jest ukryta — zapraszaj określonych userów.", diff --git a/app/src/pages/announcements/AnnouncementDetail.tsx b/app/src/pages/announcements/AnnouncementDetail.tsx new file mode 100644 index 0000000..1726737 --- /dev/null +++ b/app/src/pages/announcements/AnnouncementDetail.tsx @@ -0,0 +1,78 @@ +import { useEffect } from 'react'; +import { Link, useParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { useQueryClient } from '@tanstack/react-query'; +import { Building2 } from 'lucide-react'; +import { useAnnouncementDetail } from '../../api/queries'; +import { BackButton, Card, ErrorText, Loading } from '../../components/ui'; +import { useTopbar } from '../../topbar'; +import { fmtDateTime } from '../../lib/format'; + +/** + * Pełna treść pojedynczego ogłoszenia (deeplink z Aktualności i list siłowni). + * GET /me/feed/announcements/:id oznacza przeczytane po stronie API — + * unieważniamy feed, żeby badge nieprzeczytanych zgasł od razu. + */ +export default function AnnouncementDetail() { + const { id } = useParams(); + const { t } = useTranslation('feed'); + useTopbar({ title: t('detail.title'), back: '/announcements' }); + const queryClient = useQueryClient(); + const { data, isLoading, error } = useAnnouncementDetail(id); + + useEffect(() => { + if (data) void queryClient.invalidateQueries({ queryKey: ['feed'] }); + }, [data, queryClient]); + + if (isLoading) return ; + if (error || !data) { + return ( + <> + + {t('detail.notFound')} + + ); + } + + const a = data.announcement; + const source = a.gymName ?? t('platform'); + const author = + a.authorName && a.authorRole ? ` · ${a.authorName} (${t(`authorRole.${a.authorRole}`)})` : ''; + + return ( + <> +
+
+ + {a.title} + + + {source} + {author} · {fmtDateTime(a.createdAt)} + {a.kind !== 'MANUAL' && ( + + {t('systemBadge')} + + )} + +
+ +
+ + +

{a.body}

+ {a.gymId && ( +
+ +
+ )} +
+ + ); +} diff --git a/app/src/pages/announcements/Announcements.tsx b/app/src/pages/announcements/Announcements.tsx index c185345..947d38b 100644 --- a/app/src/pages/announcements/Announcements.tsx +++ b/app/src/pages/announcements/Announcements.tsx @@ -1,19 +1,59 @@ +import { useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useQueryClient } from '@tanstack/react-query'; -import { Megaphone } from 'lucide-react'; +import { Filter, Megaphone } from 'lucide-react'; import { markFeedAllRead, useFeed } from '../../api/queries'; +import type { FeedItem } from '../../api/types'; import { FeedItemRow } from '../../components/FeedItemRow'; +import { FilterDropdown } from '../../components/FilterDropdown'; import { Button, Card, EmptyState, ErrorText, Loading } from '../../components/ui'; import { useToast } from '../../components/toast'; -import { useTopbar } from '../../topbar'; +import { useListSearch } from '../../store/list-search'; +import { MonthPickerCore, useTopbar } from '../../topbar'; +import { monthStr } from '../../lib/format'; + +/** Filtry typu wpisu w menu kontekstowym (domyślnie: wszystko naraz). */ +const TYPE_FILTERS: { + id: 'ALL' | 'UNREAD' | 'ANNOUNCEMENTS' | 'NOTIFICATIONS'; + labelKey: string; +}[] = [ + { id: 'ALL', labelKey: 'filters.ALL' }, + { id: 'UNREAD', labelKey: 'filters.UNREAD' }, + { id: 'ANNOUNCEMENTS', labelKey: 'filters.ANNOUNCEMENTS' }, + { id: 'NOTIFICATIONS', labelKey: 'filters.NOTIFICATIONS' }, +]; + +/** Pola tekstu przeszukiwane w aktualnościach (ogłoszenia i powiadomienia). */ +function matchesQuery(item: FeedItem, q: string): boolean { + if (item.source === 'announcement') { + return [item.title, item.body, item.gymName, item.authorName].some( + (v) => v && v.toLowerCase().includes(q), + ); + } + return [item.title, JSON.stringify(item.payload)].some((v) => v.toLowerCase().includes(q)); +} export default function Announcements() { const { t } = useTranslation('feed'); - useTopbar({ title: t('nav:announcements') }); + const [typeFilter, setTypeFilter] = useState< + 'ALL' | 'UNREAD' | 'ANNOUNCEMENTS' | 'NOTIFICATIONS' + >('ALL'); + // okres: '' = wszystkie; inaczej miesiąc 'RRRR-MM' (selektor jak w historii) + const [period, setPeriod] = useState(''); const queryClient = useQueryClient(); const { push } = useToast(); const { data, isLoading, error, hasNextPage, isFetchingNextPage, fetchNextPage } = useFeed(20); const items = data?.pages.flatMap((p) => p.items ?? []) ?? []; + // miesiące dostępne w załadowanym feedzie (malejąco) — opcje filtra okresu + const months = useMemo( + () => [...new Set(items.map((i) => monthStr(new Date(i.createdAt))))].sort().reverse(), + [items], + ); + const query = useListSearch((s) => s.queries.announcements); + const setQuery = useListSearch((s) => s.setQuery); + + // wyszukiwarka jest w menu kontekstowym (topbar) — czyścimy ją przy opuszczeniu strony + useEffect(() => () => setQuery('announcements', ''), [setQuery]); const markAll = async () => { try { @@ -25,6 +65,40 @@ export default function Announcements() { } }; + useTopbar({ + title: t('nav:announcements'), + search: 'announcements', + dateFilter: ( + + ), + filters: [ + } + label={t('filters.typeLabel', { + label: t(TYPE_FILTERS.find((f) => f.id === typeFilter)?.labelKey ?? 'filters.ALL'), + })} + active={typeFilter !== 'ALL'} + options={TYPE_FILTERS.map((f) => ({ id: f.id, label: t(f.labelKey) }))} + selected={typeFilter} + onSelect={(id) => setTypeFilter(id as typeof typeFilter)} + />, + ], + filterActive: typeFilter !== 'ALL' || period !== '', + actions: items.some((i) => !i.read) ? [{ label: t('markAll'), onClick: markAll }] : [], + }); + + const filtered = useMemo(() => { + let list = items; + if (typeFilter === 'UNREAD') list = list.filter((i) => !i.read); + else if (typeFilter === 'ANNOUNCEMENTS') list = list.filter((i) => i.source === 'announcement'); + else if (typeFilter === 'NOTIFICATIONS') list = list.filter((i) => i.source === 'notification'); + if (period !== '') list = list.filter((i) => monthStr(new Date(i.createdAt)) === period); + const q = query.trim().toLowerCase(); + if (q) list = list.filter((i) => matchesQuery(i, q)); + return list; + }, [items, typeFilter, period, query]); + if (isLoading) return ; if (error) return ( @@ -34,26 +108,23 @@ export default function Announcements() { ); + const filtering = typeFilter !== 'ALL' || period !== '' || query.trim() !== ''; + return ( <> - {items.some((i) => !i.read) && ( -
- -
- )} {items.length === 0 ? ( + ) : filtered.length === 0 ? ( + ) : (
- {items.map((item) => ( + {filtered.map((item) => ( ))}
)} - {hasNextPage && ( + {hasNextPage && !filtering && (
)} + {hasNextPage && filtering && ( +

{t('filterPaginationHint')}

+ )}
); diff --git a/app/src/pages/gyms/GymAnnouncementsPage.tsx b/app/src/pages/gyms/GymAnnouncementsPage.tsx index b9667aa..47ec7e9 100644 --- a/app/src/pages/gyms/GymAnnouncementsPage.tsx +++ b/app/src/pages/gyms/GymAnnouncementsPage.tsx @@ -1,5 +1,5 @@ import { useState } from 'react'; -import { useParams } from 'react-router-dom'; +import { Link, useParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useQueryClient } from '@tanstack/react-query'; import { Megaphone } from 'lucide-react'; @@ -80,7 +80,7 @@ export default function GymAnnouncementsPage() { ); } -/* Lista tylko do odczytu (treść podstrony). */ +/* Lista tylko do odczytu (treść podstrony): klik = strona ogłoszenia z pełną treścią. */ function AnnouncementsList({ gymId }: { gymId: string }) { const { t } = useTranslation('gyms'); const { data, isLoading } = useGymAnnouncements(gymId); @@ -98,7 +98,11 @@ function AnnouncementsList({ gymId }: { gymId: string }) { return (
{announcements.map((a) => ( -
+
{a.title} {a.kind !== 'MANUAL' && ( @@ -110,8 +114,18 @@ function AnnouncementsList({ gymId }: { gymId: string }) { {fmtDateTime(a.createdAt)}
-

{a.body}

-
+ {a.authorName && a.authorRole && ( + + {t('announcements.authorLine', { + name: a.authorName, + role: t(`feed:authorRole.${a.authorRole}`), + })} + + )} +

+ {a.body} +

+ ))}
); @@ -211,7 +225,17 @@ function AnnouncementsManageSection({ gymId }: { gymId: string }) { {fmtDateTime(a.createdAt)}
-

{a.body}

+ {a.authorName && a.authorRole && ( + + {t('announcements.authorLine', { + name: a.authorName, + role: t(`feed:authorRole.${a.authorRole}`), + })} + + )} +

+ {a.body} +

{a.kind === 'MANUAL' && (
- {open && ( - <> -
setOpen(false)} /> - {/* telefon: panel filtrów otwiera się w górę od dolnego paska — dropdown też w górę */} -
- {options.map((o) => ( - - ))} -
- - )} -
- ); -} - /** Sortowanie listy planów wg klucza („default” = kolejność z API). */ function sortPlans(list: Plan[], sortKey: SortKey): Plan[] { if (sortKey === 'default') return list; diff --git a/app/src/store/list-search.ts b/app/src/store/list-search.ts index 04b8dcf..d1aaea6 100644 --- a/app/src/store/list-search.ts +++ b/app/src/store/list-search.ts @@ -1,6 +1,7 @@ import { create } from 'zustand'; -export type SearchableSection = 'plans' | 'gyms' | 'trainees' | 'invitations' | 'messages'; +export type SearchableSection = + 'plans' | 'gyms' | 'trainees' | 'invitations' | 'messages' | 'announcements'; const EMPTY_QUERIES: Record = { plans: '', @@ -8,6 +9,7 @@ const EMPTY_QUERIES: Record = { trainees: '', invitations: '', messages: '', + announcements: '', }; interface ListSearchState { diff --git a/app/src/topbar/Topbar.tsx b/app/src/topbar/Topbar.tsx index 5aa2a1d..bc75130 100644 --- a/app/src/topbar/Topbar.tsx +++ b/app/src/topbar/Topbar.tsx @@ -15,6 +15,7 @@ const SEARCH_KEYS: Record = { trainees: 'topbar.searchTrainees', invitations: 'topbar.searchInvitations', messages: 'topbar.searchMessages', + announcements: 'topbar.searchAnnouncements', }; function SectionSearchInput({ section }: { section: SearchableSection }) { diff --git a/app/test/announcement-detail.test.tsx b/app/test/announcement-detail.test.tsx new file mode 100644 index 0000000..f6d63e6 --- /dev/null +++ b/app/test/announcement-detail.test.tsx @@ -0,0 +1,110 @@ +import { render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import AnnouncementDetail from '../src/pages/announcements/AnnouncementDetail'; +import { Topbar } from '../src/topbar'; +import { setAccessToken } from '../src/api/client'; +import type { AnnouncementDetail as AnnouncementDetailType } from '../src/api/types'; + +const GYM_ANNOUNCEMENT: AnnouncementDetailType = { + id: 'a1', + kind: 'MANUAL', + title: 'Awarida klimatyzacji', + body: 'Klimatyzacja nie działa do odwołania.', + gymId: 'g1', + gymName: 'Gym A', + authorId: 'u-owner', + authorName: 'Anna Kowalska', + authorRole: 'OWNER', + createdAt: '2026-01-05T00:00:00.000Z', +}; + +const GLOBAL_ANNOUNCEMENT: AnnouncementDetailType = { + ...GYM_ANNOUNCEMENT, + id: 'a2', + title: 'Przerwa techniczna', + gymId: null, + gymName: null, + authorName: 'Adam Admin', + authorRole: 'ADMIN', +}; + +function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function stubFetch(announcement: AnnouncementDetailType | null) { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes('/me/feed/announcements/')) { + if (!announcement) + return jsonResponse(404, { + error: { code: 'NOT_FOUND', message: 'Announcement not found' }, + }); + return jsonResponse(200, { announcement, read: true }); + } + throw new Error(`Unexpected fetch: ${url}`); + }), + ); +} + +function renderDetail(path: string) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + } /> + + + , + ); +} + +beforeEach(() => { + setAccessToken('tok'); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('app strona szczegółów ogłoszenia', () => { + it('ogłoszenie siłowni: pełna treść, atrybucja autora i link do siłowni', async () => { + stubFetch(GYM_ANNOUNCEMENT); + renderDetail('/announcements/a1'); + + expect(await screen.findByText('Awarida klimatyzacji')).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Ogłoszenie' })).toBeInTheDocument(); + expect(screen.getByText('Klimatyzacja nie działa do odwołania.')).toBeInTheDocument(); + expect(screen.getByText(/Gym A · Anna Kowalska \(Właściciel\)/)).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Otwórz siłownię' })).toHaveAttribute( + 'href', + '/gyms/g1', + ); + }); + + it('ogłoszenie globalne: źródło Platforma, autor Admin, bez linku do siłowni', async () => { + stubFetch(GLOBAL_ANNOUNCEMENT); + renderDetail('/announcements/a2'); + + expect(await screen.findByText(/Platforma · Adam Admin \(Administrator\)/)).toBeInTheDocument(); + expect(screen.queryByRole('link', { name: 'Otwórz siłownię' })).not.toBeInTheDocument(); + }); + + it('brak ogłoszenia: komunikat błędu zamiast treści', async () => { + stubFetch(null); + renderDetail('/announcements/nope'); + + expect( + await screen.findByText('Ogłoszenie nie istnieje lub nie masz do niego dostępu.'), + ).toBeInTheDocument(); + }); +}); diff --git a/app/test/e2e/feed.spec.ts b/app/test/e2e/feed.spec.ts index 3a2df23..a0dd32e 100644 --- a/app/test/e2e/feed.spec.ts +++ b/app/test/e2e/feed.spec.ts @@ -24,6 +24,9 @@ function feedState() { body: 'Sauna niedostępna do piątku.', gymId: TEST_GYM_OWNED.id, gymName: TEST_GYM_OWNED.name, + authorId: 'u-owner', + authorName: 'Anna Kowalska', + authorRole: 'OWNER', read: false, createdAt: iso(60), }, @@ -35,8 +38,11 @@ function feedState() { body: 'Tego dnia siłownia będzie nieczynna.', gymId: TEST_GYM_OWNED.id, gymName: TEST_GYM_OWNED.name, + authorId: null, + authorName: null, + authorRole: null, read: true, - createdAt: iso(1440), + createdAt: iso(46000), }, ], }; @@ -64,7 +70,9 @@ test('Aktualności: karta na dashboardzie i badge nieprzeczytanych w nawigacji', await expect(page.getByRole('link', { name: /Aktualności/ })).toContainText('2'); }); -test('Aktualności: strona pełna z treścią ogłoszeń i „Oznacz wszystkie”', async ({ page }) => { +test('Aktualności: strona pełna z treścią ogłoszeń, autorem i „Oznacz wszystkie”', async ({ + page, +}) => { mockApi(page, { feed: feedState() }); await login(page); @@ -72,18 +80,79 @@ test('Aktualności: strona pełna z treścią ogłoszeń i „Oznacz wszystkie await expect(page.getByRole('heading', { name: 'Aktualności', exact: true })).toBeVisible(); await expect(page.getByText('Sauna niedostępna do piątku.')).toBeVisible(); await expect(page.getByText('Tego dnia siłownia będzie nieczynna.')).toBeVisible(); + // atrybucja autora: siłownia · imię nazwisko (rola) + await expect(page.getByText('Żelazna Świątynia · Anna Kowalska (Właściciel)')).toBeVisible(); await page.getByRole('button', { name: 'Oznacz wszystkie' }).click(); // badge znika po oznaczeniu wszystkich await expect(page.getByRole('link', { name: /Aktualności/ })).not.toContainText('2'); }); -test('Aktualności: klik w ogłoszenie prowadzi do siłowni', async ({ page }) => { +test('Aktualności: menu kontekstowe — filtr typu i wyszukiwarka', async ({ page }) => { + mockApi(page, { feed: feedState() }); + await login(page); + + await page.getByRole('link', { name: 'Zobacz wszystkie' }).click(); + await expect(page.getByText('Awarida sauny')).toBeVisible(); + await expect(page.getByText('Plan startowy')).toBeVisible(); + + // filtr typu: tylko powiadomienia + await page.getByRole('button', { name: 'Typ: Wszystkie' }).click(); + await page.getByRole('button', { name: 'Powiadomienia', exact: true }).click(); + await expect(page.getByText('Plan startowy')).toBeVisible(); + await expect(page.getByText('Awarida sauny')).toBeHidden(); + + // filtr typu: tylko ogłoszenia + await page.getByRole('button', { name: 'Typ: Powiadomienia' }).click(); + await page.getByRole('button', { name: 'Ogłoszenia', exact: true }).click(); + await expect(page.getByText('Awarida sauny')).toBeVisible(); + await expect(page.getByText('Plan startowy')).toBeHidden(); + + // wyszukiwarka w menu kontekstowym zawęża ogłoszenia + await page.locator('input[type="search"]').fill('sauny'); + await expect(page.getByText('Awarida sauny')).toBeVisible(); + await expect(page.getByText('Zamknięcie 24.12.2026')).toBeHidden(); + await page.locator('input[type="search"]').fill(''); + + // filtr okresu (selektor miesiąca jak w historii): miesiąc najstarszego wpisu + const shortMonth = (d: Date) => { + const s = new Intl.DateTimeFormat('pl-PL', { month: 'short' }).format(d).replace(/\.$/, ''); + return s.charAt(0).toUpperCase() + s.slice(1); + }; + const monthLabel = (d: Date) => { + const name = new Intl.DateTimeFormat('pl-PL', { month: 'long' }).format(d); + return `${name.charAt(0).toUpperCase()}${name.slice(1)} ${d.getFullYear()}`; + }; + const prevDate = new Date(NOW - 46000 * 60_000); + await page.getByRole('button', { name: 'Wszystkie', exact: true }).click(); + if (prevDate.getFullYear() !== new Date(NOW).getFullYear()) { + await page.getByRole('button', { name: String(prevDate.getFullYear()), exact: true }).click(); + } + await page.getByRole('button', { name: shortMonth(prevDate), exact: true }).click(); + await expect(page.getByText('Zamknięcie 24.12.2026')).toBeVisible(); + await expect(page.getByText('Awarida sauny')).toBeHidden(); + + // powrót do pełnego zakresu + await page.getByRole('button', { name: monthLabel(prevDate) }).click(); + await page.getByRole('button', { name: 'Wszystkie', exact: true }).click(); + await expect(page.getByText('Awarida sauny')).toBeVisible(); + await expect(page.getByText('Zamknięcie 24.12.2026')).toBeVisible(); +}); + +test('Aktualności: klik w ogłoszenie prowadzi na stronę ogłoszenia z powrotem do listy', async ({ + page, +}) => { mockApi(page, { feed: feedState() }); await login(page); await page.getByRole('link', { name: 'Zobacz wszystkie' }).click(); await page.getByRole('button', { name: /Awarida sauny/ }).click(); + await expect(page).toHaveURL(new RegExp(`/announcements/a-1`)); + await expect(page.getByRole('heading', { name: 'Ogłoszenie' })).toBeVisible(); + await expect(page.getByText('Sauna niedostępna do piątku.')).toBeVisible(); + await expect(page.getByText('Anna Kowalska (Właściciel)')).toBeVisible(); + // powrót do Aktualności + link do siłowni + await page.getByRole('link', { name: 'Otwórz siłownię' }).click(); await expect(page).toHaveURL(new RegExp(`/gyms/${TEST_GYM_OWNED.id}`)); await expect(page.getByRole('heading', { name: TEST_GYM_OWNED.name })).toBeVisible(); }); diff --git a/app/test/e2e/mock-api.ts b/app/test/e2e/mock-api.ts index 090c842..1971e09 100644 --- a/app/test/e2e/mock-api.ts +++ b/app/test/e2e/mock-api.ts @@ -25,18 +25,52 @@ export const TEST_USER = { }; export const TEST_EQUIPMENT = [ - { id: 'eq-1', name: 'Sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: 'Sztanga z talerzami.' }, - { id: 'eq-2', name: 'Hantle', kind: 'DUMBBELL', spec: { minKg: 2.5, maxKg: 25 }, description: 'Hantle wolne.' }, - { id: 'eq-3', name: 'Kettlebell', kind: 'KETTLEBELL', spec: { minKg: 4, maxKg: 32 }, description: 'Kettlebell.' }, + { + id: 'eq-1', + name: 'Sztanga', + kind: 'BARBELL', + spec: { maxLoadKg: 100 }, + description: 'Sztanga z talerzami.', + }, + { + id: 'eq-2', + name: 'Hantle', + kind: 'DUMBBELL', + spec: { minKg: 2.5, maxKg: 25 }, + description: 'Hantle wolne.', + }, + { + id: 'eq-3', + name: 'Kettlebell', + kind: 'KETTLEBELL', + spec: { minKg: 4, maxKg: 32 }, + description: 'Kettlebell.', + }, ]; export const TEST_FOCUS_AREAS = [ - { id: 'fa-1', name: 'Klatka piersiowa', muscle: 'chest', description: 'Wyciskanie, rozpiętki, pompki.', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' }, - { id: 'fa-2', name: 'Nogi', muscle: 'legs', description: 'Przysiady, wykroki.', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' }, + { + id: 'fa-1', + name: 'Klatka piersiowa', + muscle: 'chest', + description: 'Wyciskanie, rozpiętki, pompki.', + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'fa-2', + name: 'Nogi', + muscle: 'legs', + description: 'Przysiady, wykroki.', + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + }, ]; export const TEST_FOCUS_CHAIN = { - develop: [{ muscle: 'chest', name: 'Klatka piersiowa', exercises: [{ id: 'pz-2', name: 'Wyciskanie' }] }], + develop: [ + { muscle: 'chest', name: 'Klatka piersiowa', exercises: [{ id: 'pz-2', name: 'Wyciskanie' }] }, + ], canDo: [], difficult: [], avoid: [{ muscle: 'legs', name: 'Nogi', exercises: [{ id: 'pz-1', name: 'Przysiady' }] }], @@ -105,8 +139,18 @@ export const TEST_DAY = { }; export const TEST_GYM_PHOTOS = [ - { id: 'photo-1', url: '/gyms/gym-1/photos/photo-1', order: 0, createdAt: '2026-01-01T00:00:00.000Z' }, - { id: 'photo-2', url: '/gyms/gym-1/photos/photo-2', order: 1, createdAt: '2026-01-02T00:00:00.000Z' }, + { + id: 'photo-1', + url: '/gyms/gym-1/photos/photo-1', + order: 0, + createdAt: '2026-01-01T00:00:00.000Z', + }, + { + id: 'photo-2', + url: '/gyms/gym-1/photos/photo-2', + order: 1, + createdAt: '2026-01-02T00:00:00.000Z', + }, ]; export const TEST_GYM_OWNED = { @@ -151,7 +195,15 @@ export const TEST_GYM_VIRTUAL_PUBLIC = { capacity: 30, kind: 'VIRTUAL', isPrivate: false, - equipment: [{ id: 'gev-1', gymId: 'gym-v1', equipmentId: 'eq-1', quantity: 2, equipment: TEST_EQUIPMENT[0] }], + equipment: [ + { + id: 'gev-1', + gymId: 'gym-v1', + equipmentId: 'eq-1', + quantity: 2, + equipment: TEST_EQUIPMENT[0], + }, + ], }; /** Prywatna wirtualna siłownia, której właścicielem jest test user. */ @@ -170,7 +222,13 @@ export const TEST_GYM_VIRTUAL_PRIVATE = { export const TEST_GYM_INVITATION_RECEIVED = { id: 'gym-inv-1', direction: 'received', - gym: { id: 'gym-v3', name: 'Prywatna Beta', location: 'Poznań', kind: 'VIRTUAL', isPrivate: true }, + gym: { + id: 'gym-v3', + name: 'Prywatna Beta', + location: 'Poznań', + kind: 'VIRTUAL', + isPrivate: true, + }, user: null, invitedBy: { id: 'owner-1', firstName: 'Marek', lastName: 'Trener', email: 'marek@test.local' }, invitedAt: '2026-08-20T00:00:00.000Z', @@ -189,7 +247,11 @@ export const TEST_USER_WITH_SOCIALS = { export const TEST_TRAINEE = { user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null }, gyms: [{ id: 'gym-1', name: 'Żelazna Świątynia' }], - activePlan: { id: 'plan-1', title: 'Plan testowy', progress: { completed: 5, total: 20, percent: 25 } }, + activePlan: { + id: 'plan-1', + title: 'Plan testowy', + progress: { completed: 5, total: 20, percent: 25 }, + }, killstreak: 3, lastSessionAt: '2026-08-24T07:00:00.000Z', flags: ['streak_reset'], @@ -207,15 +269,31 @@ export const TEST_TRAINEE_DETAIL = { id: 'gym-1', name: 'Żelazna Świątynia', equipment: [ - { id: 'ge-1', gymId: 'gym-1', equipmentId: 'eq-1', quantity: 1, equipment: TEST_EQUIPMENT[0] }, - { id: 'ge-2', gymId: 'gym-1', equipmentId: 'eq-2', quantity: 2, equipment: TEST_EQUIPMENT[1] }, + { + id: 'ge-1', + gymId: 'gym-1', + equipmentId: 'eq-1', + quantity: 1, + equipment: TEST_EQUIPMENT[0], + }, + { + id: 'ge-2', + gymId: 'gym-1', + equipmentId: 'eq-2', + quantity: 2, + equipment: TEST_EQUIPMENT[1], + }, ], }, ], activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01' }, progress: { completed: 5, total: 20, percent: 25 }, killstreak: 3, - nextTraining: { dayId: 'day-1', date: '2026-08-25', exercises: [{ name: 'Przysiady', muscle: 'legs' }] }, + nextTraining: { + dayId: 'day-1', + date: '2026-08-25', + exercises: [{ name: 'Przysiady', muscle: 'legs' }], + }, extra: { sets: 5 }, missing: { sets: 1 }, lastSessionAt: '2026-08-24T07:00:00.000Z', @@ -263,7 +341,13 @@ export const TEST_TRAINEE_HISTORY = { planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 }, }, ], - comments: [] as { id: string; authorId: string; authorName: string; body: string; createdAt: string }[], + comments: [] as { + id: string; + authorId: string; + authorName: string; + body: string; + createdAt: string; + }[], }, { id: 'se-2', @@ -271,7 +355,13 @@ export const TEST_TRAINEE_HISTORY = { muscle: 'chest', isExtra: true, sets: [{ index: 0, reps: 8, rir: 1, difficulty: null, note: null, planned: null }], - comments: [] as { id: string; authorId: string; authorName: string; body: string; createdAt: string }[], + comments: [] as { + id: string; + authorId: string; + authorName: string; + body: string; + createdAt: string; + }[], }, ], }, @@ -299,7 +389,13 @@ export const TEST_TRAINEE_HISTORY = { planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 }, }, ], - comments: [] as { id: string; authorId: string; authorName: string; body: string; createdAt: string }[], + comments: [] as { + id: string; + authorId: string; + authorName: string; + body: string; + createdAt: string; + }[], }, ], }, @@ -322,14 +418,28 @@ export const TEST_INVITATIONS = [ { id: 'inv-1', direction: 'received', - other: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener', nickname: null, email: 'marek@test.local', phone: null }, + other: { + id: 'trainer-1', + firstName: 'Marek', + lastName: 'Trener', + nickname: null, + email: 'marek@test.local', + phone: null, + }, invitedAt: '2026-08-20T00:00:00.000Z', expiresAt: '2026-08-27T00:00:00.000Z', }, { id: 'inv-2', direction: 'sent', - other: { id: 'trainee-2', firstName: 'Piotr', lastName: 'Podopieczny', nickname: null, email: 'piotr@test.local', phone: null }, + other: { + id: 'trainee-2', + firstName: 'Piotr', + lastName: 'Podopieczny', + nickname: null, + email: 'piotr@test.local', + phone: null, + }, invitedAt: '2026-08-21T00:00:00.000Z', expiresAt: '2026-08-28T00:00:00.000Z', }, @@ -406,7 +516,11 @@ export const TEST_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' }, + lastMessage: { + body: 'Dobrze się czuję', + createdAt: '2026-08-24T10:00:00.000Z', + senderId: 'trainee-1', + }, unreadCount: 2, }, { @@ -467,8 +581,22 @@ export function myHistoryBody() { comments: [], sets: [ // komentarz trenującego przy serii (widoczny w historii) - { index: 0, reps: 10, rir: 2, difficulty: null, note: 'ostatnia seria była ciężka', planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }, - { index: 1, reps: null, rir: null, difficulty: null, note: null, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }, + { + index: 0, + reps: 10, + rir: 2, + difficulty: null, + note: 'ostatnia seria była ciężka', + planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 }, + }, + { + index: 1, + reps: null, + rir: null, + difficulty: null, + note: null, + planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 }, + }, ], }, ], @@ -491,7 +619,15 @@ export function myHistoryBody() { muscle: 'chest', isExtra: false, comments: [], - sets: [{ index: 0, reps: 8, rir: 1, difficulty: null, planned: { reps: 8, loadKg: 40, restSec: 90, rir: 2 } }], + sets: [ + { + index: 0, + reps: 8, + rir: 1, + difficulty: null, + planned: { reps: 8, loadKg: 40, restSec: 90, rir: 2 }, + }, + ], }, ], }, @@ -576,7 +712,17 @@ export const TEST_TRAINEE_PLAN_DETAIL = { order: 0, exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' }, sets: [ - { id: 'tps-1', index: 0, reps: 10, loadKg: 60, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null }, + { + id: 'tps-1', + index: 0, + reps: 10, + loadKg: 60, + restSec: 90, + rir: 2, + cardioBpm: null, + timeSec: null, + speed: null, + }, ], }, ], @@ -631,7 +777,17 @@ export const TEST_TRAINEE_PLAN_DETAIL_ACTIVE = { order: 0, exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' }, sets: [ - { id: 'tps-2', index: 0, reps: 8, loadKg: 40, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null }, + { + id: 'tps-2', + index: 0, + reps: 8, + loadKg: 40, + restSec: 90, + rir: 2, + cardioBpm: null, + timeSec: null, + speed: null, + }, ], }, ], @@ -667,7 +823,17 @@ export const TEST_TRAINEE_PLAN_DETAIL_FINISHED = { order: 0, exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' }, sets: [ - { id: 'tps-3', index: 0, reps: 8, loadKg: 40, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null }, + { + id: 'tps-3', + index: 0, + reps: 8, + loadKg: 40, + restSec: 90, + rir: 2, + cardioBpm: null, + timeSec: null, + speed: null, + }, ], }, ], @@ -686,7 +852,14 @@ export const TEST_TRAINEE_PLAN_DETAIL_DONE = { }; export const TEST_TRAINEE_LATEST_RESULTS = [ - { exerciseId: 'ex-1', name: 'Przysiady', muscle: 'legs', date: '2026-08-24', sets: [{ reps: 12, loadKg: 70 }], oneRm: 80.6 }, + { + exerciseId: 'ex-1', + name: 'Przysiady', + muscle: 'legs', + date: '2026-08-24', + sets: [{ reps: 12, loadKg: 70 }], + oneRm: 80.6, + }, ]; /** @@ -760,7 +933,17 @@ export const TEST_SESSION = { }, ], }, - sets: [{ id: 'ss-1', planSetId: 'ps-1', index: 0, reps: null, rir: null, difficulty: null, note: null }], + sets: [ + { + id: 'ss-1', + planSetId: 'ps-1', + index: 0, + reps: null, + rir: null, + difficulty: null, + note: null, + }, + ], }, { id: 'se-2', @@ -769,7 +952,17 @@ export const TEST_SESSION = { removed: false, exercise: makeExercise('pz-2', 'Wyciskanie', 'chest'), planExercise: null, - sets: [{ id: 'ss-2', planSetId: null, index: 0, reps: null, rir: null, difficulty: null, note: null }], + sets: [ + { + id: 'ss-2', + planSetId: null, + index: 0, + reps: null, + rir: null, + difficulty: null, + note: null, + }, + ], }, ], }; @@ -781,7 +974,11 @@ export function mockDayExecution(page: Page) { // zapisie seria staje się uzupełniona, a „Następna” przesuwa się na kolejną pustą. const session = JSON.parse(JSON.stringify(TEST_SESSION)) as typeof TEST_SESSION; page.route('**/api/v1/days/day-1', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ day: TEST_DAY }) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ day: TEST_DAY }), + }), ); page.route('**/api/v1/sessions/sets/*', (route) => { const req = route.request(); @@ -799,7 +996,11 @@ export function mockDayExecution(page: Page) { return route.fallback(); }); page.route('**/api/v1/sessions/sess-1', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ session }) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ session }), + }), ); } @@ -820,7 +1021,11 @@ export function mockDayExecutionAbandon(page: Page) { ...TEST_DAY, status: abandoned ? 'SKIPPED' : 'PLANNED', sessions: [ - { id: 'sess-1', status: abandoned ? 'ABANDONED' : 'IN_PROGRESS', startedAt: '2026-08-24T07:00:00.000Z' }, + { + id: 'sess-1', + status: abandoned ? 'ABANDONED' : 'IN_PROGRESS', + startedAt: '2026-08-24T07:00:00.000Z', + }, ], }, }), @@ -830,12 +1035,18 @@ export function mockDayExecutionAbandon(page: Page) { route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify({ session: { ...TEST_SESSION, status: abandoned ? 'ABANDONED' : 'IN_PROGRESS' } }), + body: JSON.stringify({ + session: { ...TEST_SESSION, status: abandoned ? 'ABANDONED' : 'IN_PROGRESS' }, + }), }), ); page.route('**/api/v1/sessions/sess-1/abandon', (route) => { abandoned = true; - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ok: true }), + }); }); } @@ -921,7 +1132,12 @@ export interface MockApiOptions { /** Ciało GET /gym-contact/conversations (skrzynka właściciela; domyślnie: wyprowadzone z memberSends). */ gymContactInbox?: unknown; /** Baza ciała GET /gym-contact/conversations/:id (domyślnie: wątek członka z memberSends). */ - gymContactThread?: { role: string; conversation?: unknown; messages: unknown[]; canReply?: boolean }; + gymContactThread?: { + role: string; + conversation?: unknown; + messages: unknown[]; + canReply?: boolean; + }; /** Ciało GET /gyms/:id/stats/overview (domyślnie: przykładowe KPI REAL + heatmapa). */ gymStats?: unknown; } @@ -1023,7 +1239,9 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { const myGymsBody = myGyms ?? { gyms: [{ ...TEST_GYM_OWNED, equipment: ownedGymEquipment }] }; // Stateful: komentarze pod ćwiczeniami — dodane przez POST widoczne po refetch historii. - const traineeHistory = JSON.parse(JSON.stringify(TEST_TRAINEE_HISTORY)) as typeof TEST_TRAINEE_HISTORY; + const traineeHistory = JSON.parse( + JSON.stringify(TEST_TRAINEE_HISTORY), + ) as typeof TEST_TRAINEE_HISTORY; // Stateful: virtual gyms (ratings, claims) + gym invitations (sent/received). const virtualGymState = [ @@ -1045,8 +1263,9 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { rejectReason: null as string | null, }; const gymClaimsState: Record[] = []; - const gymInvitationState: Record[] = (gymInvitations as { invitations: Record[] }) - .invitations.map((i) => ({ ...i })); + const gymInvitationState: Record[] = ( + gymInvitations as { invitations: Record[] } + ).invitations.map((i) => ({ ...i })); let claimSeq = 0; let gymInviteSeq = 0; const findVirtualGym = (id: string) => @@ -1059,7 +1278,13 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { photos.length ? `/gyms/gym-1/photos/${photos[0].id}` : null; const gymDetailBody = () => JSON.stringify({ - gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment, photos: [...gymPhotosState], coverPhoto: coverOf(gymPhotosState), currentOccupancy: occupancyOf('gym-1') }, + gym: { + ...TEST_GYM_OWNED, + equipment: ownedGymEquipment, + photos: [...gymPhotosState], + coverPhoto: coverOf(gymPhotosState), + currentOccupancy: occupancyOf('gym-1'), + }, roles: ['OWNER', 'TRAINER'], isAdmin: false, }); @@ -1092,17 +1317,29 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { const patch = (req.postDataJSON() ?? {}) as Record; meBody = { ...meBody, user: { ...meBody.user, ...patch } }; } - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(meBody) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(meBody), + }); }); // registered after `**/api/v1/me` — month-aware: ?month=YYYY-MM filtruje po s.date. const historyBody = (history ?? myHistoryBody()) as { sessions: { date: string | null }[] }; page.route('**/api/v1/me/history*', (route) => { - const monthParam = route.request().url().match(/[?&]month=(\d{4}-\d{2})/)?.[1] ?? null; + const monthParam = + route + .request() + .url() + .match(/[?&]month=(\d{4}-\d{2})/)?.[1] ?? null; const sessions = monthParam ? historyBody.sessions.filter((s) => (s.date ?? '').slice(0, 7) === monthParam) : historyBody.sessions; - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ sessions }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ sessions }), + }); }); // Stateful: parametry ciała — POST /weight dopisuje punkt (refetch po dodaniu). @@ -1115,16 +1352,32 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { const body = (req.postDataJSON() ?? {}) as { value: number; date?: string }; const date = body.date ?? new Date().toISOString().slice(0, 10); bodyParams.weight.push({ id: `w-new-${bodyParams.weight.length}`, value: body.value, date }); - return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ ok: true }) }); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ ok: true }), + }); } - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ok: true }), + }); }); page.route('**/api/v1/me/body-parameters', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(bodyParams) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(bodyParams), + }), ); page.route('**/api/v1/me/active-session', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(activeSession) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(activeSession), + }), ); // ---------- feed / aktualności (powiadomienia + ogłoszenia), stateful ---------- @@ -1138,9 +1391,18 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { // Najpierw ogólna trasa, potem szczegółyne (Playwright: późniejsze rejestracje mają priorytet). page.route('**/api/v1/me/feed*', (route) => { const limit = Number(new URL(route.request().url()).searchParams.get('limit') ?? '20'); - return route.fulfill( - feedJson(200, { items: feedItems.slice(0, limit), nextCursor: null }), - ); + return route.fulfill(feedJson(200, { items: feedItems.slice(0, limit), nextCursor: null })); + }); + // GET /me/feed/announcements/:id — szczegóły ogłoszenia (oznacza przeczytane). + page.route('**/api/v1/me/feed/announcements/*', (route) => { + const id = new URL(route.request().url()).pathname.split('/').at(-1); + const item = feedItems.find((i) => i.source === 'announcement' && i.id === id); + if (!item) + return route.fulfill( + feedJson(404, { error: { code: 'NOT_FOUND', message: 'Announcement not found' } }), + ); + item.read = true; + return route.fulfill(feedJson(200, { announcement: item, read: true })); }); page.route('**/api/v1/me/feed/*/read', (route) => { const id = new URL(route.request().url()).pathname.split('/').at(-2); @@ -1155,17 +1417,23 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { return route.fulfill(feedJson(200, { ok: true })); }); page.route('**/api/v1/me/feed/unread-count', (route) => - route.fulfill( - feedJson(200, { unreadCount: feedItems.filter((i) => !i.read).length }), - ), + route.fulfill(feedJson(200, { unreadCount: feedItems.filter((i) => !i.read).length })), ); // ---------- udostępnianie planów (PlanShare) ---------- page.route('**/api/v1/plans/shared-with-me', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(sharedWithMe ?? { plans: [] }) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(sharedWithMe ?? { plans: [] }), + }), ); page.route('**/api/v1/me/trainers', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(myTrainers ?? { trainers: [] }) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(myTrainers ?? { trainers: [] }), + }), ); page.route('**/api/v1/plans/*/share', (route) => route.fulfill({ @@ -1192,7 +1460,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { ); page.route('**/api/v1/dashboard', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(dashboard) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(dashboard), + }), ); page.route('**/api/v1/gyms/all', (route) => @@ -1288,23 +1560,29 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { status: 201, contentType: 'application/json', body: JSON.stringify({ - gym: { id: 'gym-new', name: body.name, location: body.location ?? null, availability: body.availability ?? null, capacity: body.capacity ?? null, kind: body.kind ?? 'VIRTUAL', isPrivate: body.isPrivate ?? false, equipment: [], roles: ['OWNER'] }, + gym: { + id: 'gym-new', + name: body.name, + location: body.location ?? null, + availability: body.availability ?? null, + capacity: body.capacity ?? null, + kind: body.kind ?? 'VIRTUAL', + isPrivate: body.isPrivate ?? false, + equipment: [], + roles: ['OWNER'], + }, }), }); } return route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify( - withOccupancy(myGymsBody), - ), + body: JSON.stringify(withOccupancy(myGymsBody)), }); }); // Owner-scoped schedule exceptions. - page.route('**/api/v1/gyms/*/exceptions/*', (route) => - route.fulfill({ status: 204 }), - ); + page.route('**/api/v1/gyms/*/exceptions/*', (route) => route.fulfill({ status: 204 })); page.route('**/api/v1/gyms/*/exceptions', (route) => { const req = route.request(); @@ -1375,13 +1653,23 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { return route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify({ gym: { ...TEST_GYM_JOINABLE, currentOccupancy: occupancyOf(TEST_GYM_JOINABLE.id) }, roles: [], isAdmin: false }), + body: JSON.stringify({ + gym: { ...TEST_GYM_JOINABLE, currentOccupancy: occupancyOf(TEST_GYM_JOINABLE.id) }, + roles: [], + isAdmin: false, + }), }); } return route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment, currentOccupancy: occupancyOf('gym-1') } }), + body: JSON.stringify({ + gym: { + ...TEST_GYM_OWNED, + equipment: ownedGymEquipment, + currentOccupancy: occupancyOf('gym-1'), + }, + }), }); }); @@ -1452,7 +1740,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { return route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() }); } // GET — serwowanie pliku zdjęcia. - return route.fulfill({ status: 200, contentType: 'image/png', body: Buffer.from(TINY_PNG, 'base64') }); + return route.fulfill({ + status: 200, + contentType: 'image/png', + body: Buffer.from(TINY_PNG, 'base64'), + }); }); // ---------- zdjęcia instancji urządzeń (max 5 per instancja) ---------- @@ -1461,7 +1753,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { page.route('**/api/v1/gyms/*/equipment/*/photos', (route) => { const req = route.request(); - if (req.method() !== 'POST') return route.fulfill({ status: 200, contentType: 'application/json', body: eqGymBody() }); + if (req.method() !== 'POST') + return route.fulfill({ status: 200, contentType: 'application/json', body: eqGymBody() }); const instanceId = req.url().match(/equipment\/([^/]+)\/photos/)?.[1]; const link = ownedGymEquipment.find((e) => e.id === instanceId); const raw = req.postData() || ''; @@ -1495,7 +1788,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { return route.fulfill({ status: 200, contentType: 'application/json', body: eqGymBody() }); } // GET — serwowanie pliku zdjęcia urządzenia. - return route.fulfill({ status: 200, contentType: 'image/png', body: Buffer.from(TINY_PNG, 'base64') }); + return route.fulfill({ + status: 200, + contentType: 'image/png', + body: Buffer.from(TINY_PNG, 'base64'), + }); }); // ---------- virtual gyms (ratings) ---------- @@ -1509,11 +1806,17 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { page.route('**/api/v1/gyms/*/rate', (route) => { const req = route.request(); - if (req.method() !== 'POST') return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }); + if (req.method() !== 'POST') + return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }); const gymId = req.url().match(/gyms\/([^/]+)\/rate/)?.[1]; const body = JSON.parse(req.postData() || '{}'); const gym = virtualGymState.find((g) => g.id === gymId); - if (!gym) return route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Gym not found' } }) }); + if (!gym) + return route.fulfill({ + status: 404, + contentType: 'application/json', + body: JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Gym not found' } }), + }); const vote = body.vote as 'UP' | 'DOWN'; if (gym.myVote === vote) { // toggle off @@ -1541,7 +1844,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { const raw = req.postData() || ''; // multipart: name="x" const field = (name: string) => - raw.match(new RegExp(`name="${name}"[^\\r\\n]*\\r?\\n\\r?\\n([^\\r\\n]*)`))?.[1]?.trim() || null; + raw.match(new RegExp(`name="${name}"[^\\r\\n]*\\r?\\n\\r?\\n([^\\r\\n]*)`))?.[1]?.trim() || + null; const gymId = field('gymId'); const gymName = field('gymName'); const gymLocation = field('gymLocation'); @@ -1550,9 +1854,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { id: `claim-${claimSeq}`, gymId, type: gymId ? 'verification' : 'new', - gym: gymId ? { id: gymId, name: 'Wirtualna Alfa', kind: 'VIRTUAL', isPrivate: false } : null, - gymName: gymId ? null : gymName ?? 'Nowa Realna Siłownia', - gymLocation: gymId ? null : gymLocation ?? 'ul. Testowa 1, Warszawa', + gym: gymId + ? { id: gymId, name: 'Wirtualna Alfa', kind: 'VIRTUAL', isPrivate: false } + : null, + gymName: gymId ? null : (gymName ?? 'Nowa Realna Siłownia'), + gymLocation: gymId ? null : (gymLocation ?? 'ul. Testowa 1, Warszawa'), gymAvailability: null, gymCapacity: null, description: 'opis', @@ -1572,9 +1878,17 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { const g = findVirtualGym(gymId); if (g) g.claimStatus = 'PENDING'; } - return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ claim }) }); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ claim }), + }); } - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ claims: gymClaimsState }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ claims: gymClaimsState }), + }); }); page.route('**/api/v1/gyms/claims/*', (route) => { @@ -1615,7 +1929,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { inv.status = 'DECLINED'; } } - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ invitation: inv ?? { id } }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ invitation: inv ?? { id } }), + }); } return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }); }); @@ -1628,27 +1946,54 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { const invitation = { id: `gym-inv-new-${gymInviteSeq}`, direction: 'sent', - gym: { id: body.gymId, name: 'Moja Prywatna Wirtualna', location: 'Wrocław', kind: 'VIRTUAL', isPrivate: true }, - user: { id: body.userId, firstName: 'Jan', lastName: 'Kowalski', email: 'jan.kowalski@test.local' }, + gym: { + id: body.gymId, + name: 'Moja Prywatna Wirtualna', + location: 'Wrocław', + kind: 'VIRTUAL', + isPrivate: true, + }, + user: { + id: body.userId, + firstName: 'Jan', + lastName: 'Kowalski', + email: 'jan.kowalski@test.local', + }, invitedBy: null, invitedAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 7 * 86400000).toISOString(), }; gymInvitationState.push(invitation); - return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ invitation }) }); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ invitation }), + }); } - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ invitations: gymInvitationState }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ invitations: gymInvitationState }), + }); }); // registered last — takes priority over the `invitations/*` glob for the search URL page.route('**/api/v1/gyms/invitations/search*', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(userSearch) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(userSearch), + }), ); // ---------- trainer / trainees ---------- // trailing * — the search URL carries ?firstName=&lastName= page.route('**/api/v1/trainer/search*', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(userSearch) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(userSearch), + }), ); page.route('**/api/v1/trainer/invitations/*', (route) => { @@ -1728,7 +2073,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { // registered last — takes priority over the wildcard `trainees/*` route. // Month-aware: treningi tylko w bieżącym miesiącu (puste pozostałe miesiące). page.route('**/api/v1/trainer/trainees/*/calendar*', (route) => { - const monthParam = route.request().url().match(/[?&]month=(\d{4}-\d{2})/)?.[1] ?? null; + const monthParam = + route + .request() + .url() + .match(/[?&]month=(\d{4}-\d{2})/)?.[1] ?? null; const current = traineeCalendarBody(); const body = monthParam === null || monthParam === current.month @@ -1744,13 +2093,21 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { // ---------- komunikator (messages) ---------- const sentMessages: unknown[] = []; page.route('**/api/v1/messages/conversations', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(conversations) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(conversations), + }), ); page.route('**/api/v1/messages/conversations/*', (route) => { const req = route.request(); if (req.method() === 'POST') { - const body = req.postDataJSON() as { body: string; sessionId?: string; sessionExerciseId?: string }; + const body = req.postDataJSON() as { + body: string; + sessionId?: string; + sessionExerciseId?: string; + }; const attachment = body.sessionId ? body.sessionExerciseId ? { @@ -1759,7 +2116,14 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { plan: 'Plan testowy', exercise: { name: 'Przysiady', - sets: [{ index: 0, reps: 10, rir: 2, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }], + sets: [ + { + index: 0, + reps: 10, + rir: 2, + planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 }, + }, + ], }, exercises: [], } @@ -1805,12 +2169,20 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { createdAt: '2026-08-24T11:00:00.000Z', }; page.route('**/api/v1/me/comments', (route) => - route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ comment: newComment }) }), + route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ comment: newComment }), + }), ); page.route('**/api/v1/trainer/trainees/*/comments', (route) => { const req = route.request(); if (req.method() === 'POST') { - const body = req.postDataJSON() as { body: string; sessionId?: string; sessionExerciseId?: string }; + const body = req.postDataJSON() as { + body: string; + sessionId?: string; + sessionExerciseId?: string; + }; const comment = { id: `c-${Date.now()}`, authorId: 'trainer-1', @@ -1824,7 +2196,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { if (ex.id === body.sessionExerciseId) ex.comments.push(comment); } } - return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ comment }) }); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ comment }), + }); } return route.fulfill({ status: 204 }); }); @@ -1846,7 +2222,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { const info = GYM_PRESENCE_INFO[gymId] ?? { name: gymId, capacity: null }; const src = (req.postDataJSON() as { source?: string } | null)?.source ?? 'MANUAL'; if (activePresence && activePresence.gymId === gymId) { - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ presence: activePresence }), + }); } closeActivePresence(); const now = new Date().toISOString(); @@ -1862,22 +2242,38 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { closedAt: null, durationMinutes: 0, }; - return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }) }); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ presence: activePresence }), + }); }); page.route('**/api/v1/me/presence/check-out', (route) => { closeActivePresence(); - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ checkedOut: true }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ checkedOut: true }), + }); }); page.route('**/api/v1/me/presence/heartbeat', (route) => { // heartbeat odświeża slot — globalny modal keep-alive zamyka się po potwierdzeniu if (activePresence) activePresence.lastActivityAt = new Date().toISOString(); - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ touched: activePresence != null }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ touched: activePresence != null }), + }); }); page.route('**/api/v1/me/presence/history*', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ visits: presenceVisits }) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ visits: presenceVisits }), + }), ); page.route('**/api/v1/me/presence/stats', (route) => @@ -1886,14 +2282,25 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { contentType: 'application/json', body: JSON.stringify( presenceStats ?? { - stats: { visits: presenceVisits.length, avgStayMinutes: null, heatmap: [], topGyms: [], peak: 0, topEquipment: [] }, + stats: { + visits: presenceVisits.length, + avgStayMinutes: null, + heatmap: [], + topGyms: [], + peak: 0, + topEquipment: [], + }, }, ), }), ); page.route('**/api/v1/me/presence', (route) => - route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }) }), + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ presence: activePresence }), + }), ); // zmiana siłowni planu (modal rozpoczęcia treningu) @@ -1902,11 +2309,13 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { if (req.method() !== 'PATCH') return route.fallback(); const planId = req.url().match(/plans\/([^/]+)\/gym/)?.[1] ?? ''; const gymId = (req.postDataJSON() as { gymId?: string | null } | null)?.gymId ?? null; - const info = gymId ? GYM_PRESENCE_INFO[gymId] ?? { name: gymId } : null; + const info = gymId ? (GYM_PRESENCE_INFO[gymId] ?? { name: gymId }) : null; return route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify({ plan: { id: planId, gym: gymId ? { id: gymId, name: info!.name } : null } }), + body: JSON.stringify({ + plan: { id: planId, gym: gymId ? { id: gymId, name: info!.name } : null }, + }), }); }); @@ -1949,7 +2358,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { // GET /gyms/:id/contact — member (leniwy wątek) albo owner (lista wątków, gdy podano ciało). page.route('**/api/v1/gyms/*/contact', (route) => { if (gymContact !== undefined) - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymContact) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(gymContact), + }); return route.fulfill({ status: 200, contentType: 'application/json', @@ -1987,7 +2400,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { // GET /gym-contact/conversations — skrzynka właściciela. page.route('**/api/v1/gym-contact/conversations', (route) => { if (gymContactInbox !== undefined) - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymContactInbox) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(gymContactInbox), + }); const conv = memberConversation(); const last = memberSends[memberSends.length - 1]; return route.fulfill({ @@ -2038,7 +2455,10 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { return route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify({ ...gymContactThread, messages: [...(gymContactThread.messages ?? []), ...ownerReplies] }), + body: JSON.stringify({ + ...gymContactThread, + messages: [...(gymContactThread.messages ?? []), ...ownerReplies], + }), }); return route.fulfill({ status: 200, @@ -2054,7 +2474,10 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { // DELETE /gym-contact/messages/:id — tylko autor (twardy delete). page.route('**/api/v1/gym-contact/messages/*', (route) => { - const id = route.request().url().match(/messages\/([^/?]+)/)?.[1]; + const id = route + .request() + .url() + .match(/messages\/([^/?]+)/)?.[1]; const mi = memberSends.findIndex((m) => m.id === id); if (mi >= 0) memberSends.splice(mi, 1); const oi = ownerReplies.findIndex((m) => m.id === id); @@ -2064,43 +2487,54 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { // GET /gyms/:id/presence-stats — telemetria bytności (widok ogólny REAL, każdy zalogowany). page.route('**/api/v1/gyms/*/presence-stats*', (route) => { - const body = - gymPresenceStats ?? { - gym: { id: 'gym-1', name: TEST_GYM_OWNED.name, kind: 'REAL', capacity: 50 }, - stats: { - visits: 96, - avgStayMinutes: 68, - heatmap: [ - { day: 0, hour: 18, count: 5 }, - { day: 2, hour: 17, count: 3 }, - ], - topGyms: [], - peak: 5, - topEquipment: [{ equipmentId: 'eq-1', name: 'ławka', nameEn: 'bench', count: 41 }], - live: 7, - visitsPerDay: 3.2, - }, - }; - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) }); + const body = gymPresenceStats ?? { + gym: { id: 'gym-1', name: TEST_GYM_OWNED.name, kind: 'REAL', capacity: 50 }, + stats: { + visits: 96, + avgStayMinutes: 68, + heatmap: [ + { day: 0, hour: 18, count: 5 }, + { day: 2, hour: 17, count: 3 }, + ], + topGyms: [], + peak: 5, + topEquipment: [{ equipmentId: 'eq-1', name: 'ławka', nameEn: 'bench', count: 41 }], + live: 7, + visitsPerDay: 3.2, + }, + }; + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(body), + }); }); // GET /gyms/:id/stats/overview — KPI + heatmapa (REAL, właściciel/admin). page.route('**/api/v1/gyms/*/stats/overview*', (route) => { - const body = - gymStats ?? { - gym: { id: 'gym-1', name: TEST_GYM_OWNED.name, kind: 'REAL', capacity: 50 }, - presence: { - visits: 42, - visitsPerDay: 1.4, - avgStayMinutes: 75, - peak: 5, - live: 2, - heatmap: [{ day: 0, hour: 18, count: 3 }], - }, - members: { total: 12, byRole: { OWNER: 1, TRAINER: 2, MEMBER: 9 }, newInRange: 4 }, - activity: { sessionsStarted: 20, sessionsCompleted: 17, sessionsAbandoned: 3, uniqueExercisers: 6 }, - }; - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) }); + const body = gymStats ?? { + gym: { id: 'gym-1', name: TEST_GYM_OWNED.name, kind: 'REAL', capacity: 50 }, + presence: { + visits: 42, + visitsPerDay: 1.4, + avgStayMinutes: 75, + peak: 5, + live: 2, + heatmap: [{ day: 0, hour: 18, count: 3 }], + }, + members: { total: 12, byRole: { OWNER: 1, TRAINER: 2, MEMBER: 9 }, newInRange: 4 }, + activity: { + sessionsStarted: 20, + sessionsCompleted: 17, + sessionsAbandoned: 3, + uniqueExercisers: 6, + }, + }; + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(body), + }); }); // Detale publicznej/prywatnej VIRTUAL (GET /gyms/gym-v1|gym-v2) — przeniesione @@ -2123,7 +2557,11 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { route.fulfill({ status: 200, contentType: 'application/json', - body: JSON.stringify({ gym: { ...privateVirtualGym, photos: [] }, roles: ['OWNER'], isAdmin: false }), + body: JSON.stringify({ + gym: { ...privateVirtualGym, photos: [] }, + roles: ['OWNER'], + isAdmin: false, + }), }), ); } @@ -2221,25 +2659,45 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) { const req = route.request(); const url = req.url(); if (req.method() === 'PATCH' || req.method() === 'DELETE') { - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ok: true }), + }); } - if ( - url.includes('/activate') || - url.includes('/abandon') || - url.includes('/complete') - ) { - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) }); + if (url.includes('/activate') || url.includes('/abandon') || url.includes('/complete')) { + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ok: true }), + }); } if (url.endsWith('/tp-2')) { - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_ACTIVE }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_ACTIVE }), + }); } if (url.endsWith('/tp-3')) { - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_FINISHED }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_FINISHED }), + }); } if (url.endsWith('/tp-4')) { - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_DONE }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_DONE }), + }); } - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL }), + }); }); page.route('**/api/v1/trainer/trainees/*/plans', (route) => { const req = route.request(); @@ -2258,6 +2716,10 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) { body: JSON.stringify({ plan: { id: 'tp-new', gym } }), }); } - return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plans: TEST_TRAINEE_PLANS }) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ plans: TEST_TRAINEE_PLANS }), + }); }); } diff --git a/app/test/gym-detail.test.tsx b/app/test/gym-detail.test.tsx index c9b7932..acaf034 100644 --- a/app/test/gym-detail.test.tsx +++ b/app/test/gym-detail.test.tsx @@ -56,6 +56,9 @@ const ANNOUNCEMENT: GymAnnouncement = { kind: 'MANUAL', title: 'Awarida klimatyzacji', body: 'Klimatyzacja nie działa.', + authorId: 'u-owner', + authorName: 'Anna Kowalska', + authorRole: 'OWNER', createdAt: '2026-01-05T00:00:00.000Z', }; @@ -316,11 +319,16 @@ describe('app podstrony sekcji siłowni', () => { expect(() => actionButton('Edytuj urządzenia')).toThrow(); }); - it('podstrona ogłoszeń: lista read-only; właściciel otwiera modal tworzenia', async () => { + it('podstrona ogłoszeń: lista read-only z autorem i linkiem do szczegółów; właściciel otwiera modal tworzenia', async () => { stubGymFetch(); renderGym('/gyms/g1/announcements'); expect(await screen.findByText('Awarida klimatyzacji')).toBeInTheDocument(); + expect(await screen.findByText('od Anna Kowalska (Właściciel)')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: /Awarida klimatyzacji/ })).toHaveAttribute( + 'href', + '/announcements/a1', + ); fireEvent.click(actionButton('Nowe ogłoszenie')); const dialog = await screen.findByRole('dialog'); expect(within(dialog).getByRole('button', { name: 'Opublikuj' })).toBeInTheDocument();