+
);
}
export default function GymsList() {
const { t } = useTranslation('gyms');
+ const [kind, setKind] = useState<'' | GymKind>('');
+
+ const query = useListSearch((s) => s.queries.gyms);
+ const setQuery = useListSearch((s) => s.setQuery);
+ // wyszukiwanie serwerowe — debounce, żeby nie odpytywać API przy każdym znaku
+ const [debounced, setDebounced] = useState(query);
+ useEffect(() => {
+ const id = setTimeout(() => setDebounced(query.trim()), 300);
+ return () => clearTimeout(id);
+ }, [query]);
+
useTopbar({
title: t('common:nav.gyms'),
search: 'gyms',
actions: [{ label: t('newGym'), to: '/gyms/new', icon: Plus }],
+ filters: [
+
,
+ ],
+ filterActive: kind !== '',
});
- const { data, isLoading, error } = useQuery({
- queryKey: ['gyms'],
- queryFn: () => api<{ gyms: Gym[] }>('/admin/gyms'),
- });
- // live occupancy — osobny query (licznik „teraz” na kartach REAL)
- const { data: occupancyData } = useQuery({
- queryKey: ['gyms', 'occupancy'],
- queryFn: () => api<{ gyms: AdminOccupancyRow[] }>('/admin/gyms/occupancy'),
- });
- const occupancy = new Map((occupancyData?.gyms ?? []).map((o) => [o.gymId, o]));
- const query = useListSearch((s) => s.queries.gyms);
- const setQuery = useListSearch((s) => s.setQuery);
- const gyms = data?.gyms ?? [];
-
- const filtered = query
- ? gyms.filter((g) =>
- [g.name, g.location]
- .filter(Boolean)
- .some((s) => s!.toLowerCase().includes(query.toLowerCase())),
- )
- : gyms;
+ const { data, isLoading, error } = useAdminGymList(debounced, kind);
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('gyms', ''), [setQuery]);
+ const gyms = data?.gyms ?? [];
+
return (
<>
{isLoading &&
}
@@ -170,30 +146,48 @@ export default function GymsList() {
)}
- {!isLoading && !error && filtered.length > 0 && (
+ {!isLoading && !error && gyms.length > 0 && (
<>
-
- {filtered.map((g) => (
-
- ))}
+
+
+
+
+ |
+ {t('colName')}
+ |
+
+ {t('colLocation')}
+ |
+
+ {t('colOwners')}
+ |
+
+ {t('colMembers')}
+ |
+
+ {t('colOpenToday')}
+ |
+
+ {t('colCreatedAt')}
+ |
+
+
+
+ {gyms.map((g) => (
+
+ ))}
+
+
>
)}
- {!isLoading && !error && filtered.length === 0 && (
+ {!isLoading && !error && gyms.length === 0 && (
)}
diff --git a/admin/test/GymDetail.test.tsx b/admin/test/GymDetail.test.tsx
index dcf293c..34cfe4b 100644
--- a/admin/test/GymDetail.test.tsx
+++ b/admin/test/GymDetail.test.tsx
@@ -31,6 +31,7 @@ const G1: Gym = {
isPrivate: false,
equipment: [],
coverPhoto: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
_count: { memberships: 12 },
owners: [OWNER1],
};
@@ -69,6 +70,94 @@ const U1 = {
isAdmin: false,
} as unknown as User;
+const MEMBERS_PAGE_1 = {
+ members: [
+ {
+ membershipId: 'mem-1',
+ roles: ['OWNER'],
+ joinedAt: '2026-01-02T10:00:00.000Z',
+ checkedInNow: false,
+ user: {
+ id: 'u-owner',
+ firstName: 'Anna',
+ lastName: 'Kowalska',
+ email: 'anna@fitos.pl',
+ status: 'ACTIVE',
+ },
+ },
+ {
+ membershipId: 'mem-2',
+ roles: ['MEMBER', 'TRAINER'],
+ joinedAt: '2026-02-01T10:00:00.000Z',
+ checkedInNow: true,
+ user: {
+ id: 'u-mem',
+ firstName: 'Jan',
+ lastName: 'Nowak',
+ email: 'jan@fitos.pl',
+ status: 'SUSPENDED',
+ },
+ },
+ ],
+ total: 3,
+};
+
+const MEMBERS_PAGE_2 = {
+ members: [
+ {
+ membershipId: 'mem-3',
+ roles: ['MEMBER'],
+ joinedAt: '2026-03-01T10:00:00.000Z',
+ checkedInNow: false,
+ user: {
+ id: 'u-mem-2',
+ firstName: 'Ola',
+ lastName: 'Wajs',
+ email: 'ola@fitos.pl',
+ status: 'ACTIVE',
+ },
+ },
+ ],
+ total: 3,
+};
+
+const RELATED = {
+ claims: [
+ {
+ id: 'c1',
+ status: 'PENDING',
+ createdAt: '2026-03-05T12:00:00.000Z',
+ user: { id: 'u-mem', firstName: 'Jan', lastName: 'Nowak', email: 'jan@fitos.pl' },
+ documentCount: 1,
+ },
+ ],
+ invitations: [
+ {
+ id: 'i1',
+ status: 'PENDING',
+ invitedAt: '2026-03-06T12:00:00.000Z',
+ expiresAt: '2026-03-13T12:00:00.000Z',
+ user: { id: 'u-mem-2', firstName: 'Ola', lastName: 'Wajs', email: 'ola@fitos.pl' },
+ invitedBy: OWNER1,
+ },
+ ],
+};
+
+const LOGS_PAGE = {
+ logs: [
+ {
+ id: 'log-1',
+ createdAt: '2026-03-07T09:00:00.000Z',
+ action: 'gym.updated',
+ entityType: 'gym',
+ entityId: 'g1',
+ details: { name: 'Gym A' },
+ actor: { id: 'adm', firstName: 'Ada', lastName: 'Admin', email: 'ada@fitos.pl' },
+ },
+ ],
+ total: 7,
+};
+
type Call = { url: string; method?: string; body?: unknown };
function jsonResponse(status: number, body: unknown) {
@@ -78,7 +167,7 @@ function jsonResponse(status: number, body: unknown) {
});
}
-/** Wspólny mock: karta siłowni, katalog, wyjątki, użytkownicy i endpointy właścicieli. */
+/** Wspólny mock konsoli: karta siłowni, KPI, członkowie, related, logi, wyjątki, właściciele. */
function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) {
const gym = options.gym ?? G1;
const calls = options.calls ?? [];
@@ -88,20 +177,16 @@ function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) {
calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined });
if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] });
if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] });
- if (url.includes('/admin/gyms/g1/presence-stats'))
- return jsonResponse(200, {
- gym: { id: 'g1', name: gym.name, kind: gym.kind, capacity: gym.capacity },
- stats: {
- visits: 40,
- avgStayMinutes: 62,
- heatmap: [{ day: 1, hour: 18, count: 7 }],
- topGyms: [],
- peak: 7,
- topEquipment: [{ equipmentId: 'eq-1', name: 'sztanga', nameEn: null, count: 12 }],
- live: 3,
- visitsPerDay: 1.3,
- },
- });
+ if (url.includes('/memberships/') && method === 'PATCH')
+ return jsonResponse(200, { membership: {} });
+ if (url.includes('/memberships/') && method === 'DELETE') return jsonResponse(204, {});
+ if (url.includes('/admin/gyms/g1/members')) {
+ const offset = Number(new URL(`http://x${url}`).searchParams.get('offset') ?? 0);
+ if (offset > 0) return jsonResponse(200, MEMBERS_PAGE_2);
+ return jsonResponse(200, MEMBERS_PAGE_1);
+ }
+ if (url.includes('/admin/gyms/g1/related')) return jsonResponse(200, RELATED);
+ if (url.includes('/admin/gyms/g1/logs')) return jsonResponse(200, LOGS_PAGE);
if (url.includes('/admin/users')) return jsonResponse(200, { users: [U1] });
if (url.includes('/admin/announcements')) return jsonResponse(200, { announcements: [] });
if (url.includes('/equipment-usage'))
@@ -168,48 +253,199 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-describe('admin GymDetail page', () => {
- it('pokazuje szczegóły odczytu, kafelki sekcji i pojedynczą grupę menu „Zarządzaj”', async () => {
+describe('admin GymDetail (konsola)', () => {
+ it('renderuje konsolę: KPI, członków, właścicieli i powiązania; bez hero i kafelków apki', async () => {
stubGymFetch();
renderGymDetail();
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
- // hero bez chipa miasta i karty „Dane" — zostają liczniki członków/urządzeń
- expect(screen.getByText('12 członków')).toBeInTheDocument();
- // kafelki sekcji prowadzą do podstron (galeria/urządzenia/ogłoszenia + tablica nad bytnością)
- expect(screen.getByRole('link', { name: /Galeria zdjęć/ })).toBeInTheDocument();
- expect(screen.getByRole('link', { name: /Urządzenia/ })).toBeInTheDocument();
- expect(screen.getByRole('link', { name: /Ogłoszenia/ })).toBeInTheDocument();
- const boardTile = screen.getByRole('link', { name: /Tablica/ });
- expect(boardTile).toHaveAttribute('href', '/gyms/g1/board');
- const presenceHeading = await screen.findByText('Bytność');
- expect(
- boardTile.compareDocumentPosition(presenceHeading) & Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
+ // KPI z licznikami admina (bez zdjęcia okładki i chipów apki)
+ expect(screen.getByText('12/50')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { level: 3, name: /Członkowie/ })).toBeInTheDocument();
- // menu kontekstowe: JEDNA grupa „Zarządzaj” z akcjami strony (admin: + Właściciele)
+ // tabela członków: OWNER + MEMBER/TRAINER z pigułkami ról (bez kolumn Konto/Obecność/Akcje)
+ const table = await screen.findByRole('table');
+ expect(within(table).getByText('Anna Kowalska')).toBeInTheDocument();
+ const trainerRow = within(table).getByText('Jan Nowak').closest('tr');
+ expect(within(trainerRow as HTMLElement).getByText('Trener')).toBeInTheDocument();
+ // brak przycisków w tabeli — akcje członka dopiero w menu z kliknięcia wiersza
+ expect(within(table).queryAllByRole('button')).toHaveLength(0);
+
+ // powiązane wnioski/zaproszenia i podgląd logów
+ expect(screen.getByText('Wnioski i zaproszenia')).toBeInTheDocument();
+ expect(screen.getByText('Wnioski o weryfikację')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Wszystkie logi' })).toHaveAttribute(
+ 'href',
+ '/gyms/g1/logs',
+ );
+
+ // TOPBAR: tytuł = kategoria „Siłownia”, bez wyszukiwarki (wyjątek: kafelek członków), osobny przycisk „Otwórz w aplikacji”, grupa „Zarządzaj”
const config = useTopbarStore.getState().config;
+ expect(config?.title).toBe('Siłownia');
+ // nazwa siłowni w treści (h2) + przycisk powrotu na listę
+ expect(screen.getByRole('heading', { level: 2, name: 'Gym A' })).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Wróć' })).toBeInTheDocument();
+ expect(config?.search).toBeUndefined();
+ const openInApp = config?.actions?.find((a) => a.label === 'Otwórz w aplikacji');
+ expect(openInApp?.to).toBeUndefined();
+ expect(typeof openInApp?.onClick).toBe('function');
expect(config?.groups?.map((g) => g.id)).toEqual(['manage']);
- // akcje nigdy luzem na pasku — zebrane w kontrolce „Zarządzaj” (collapsed)
expect(config?.groups?.[0]?.collapsed).toBe(true);
expect(config?.groups?.[0]?.actions?.map((a) => a.label)).toEqual([
'Informacje',
'Galeria',
+ 'Tablica',
'Kod QR',
'Urządzenia',
'Ogłoszenia',
- 'Właściciele',
+ 'Logi',
'Usuń siłownię',
]);
- expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Galeria')?.to).toBe(
- '/gyms/g1/gallery',
+ expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Tablica')?.to).toBe(
+ '/gyms/g1/board',
);
- expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Urządzenia')?.to).toBe(
- '/gyms/g1/equipment',
+ });
+
+ it('dostraja listę członków przyciskiem „Pokaż kolejnych” (offset)', async () => {
+ const calls = stubGymFetch();
+ renderGymDetail();
+ await screen.findByRole('heading', { name: 'Gym A' });
+ const table = await screen.findByRole('table');
+ await within(table).findByText('Anna Kowalska');
+ expect(within(table).queryByText('Ola Wajs')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Pokaż kolejnego członka (1)' }));
+ await within(table).findByText('Ola Wajs');
+ expect(
+ calls.some((c) => c.url.includes('/members') && c.url.includes('offset=2')),
+ ).toBe(true);
+ });
+
+ it('wyszukiwarka w kafelek członków odpytuje API z q (serwerowo)', async () => {
+ const calls = stubGymFetch();
+ renderGymDetail();
+ await screen.findByRole('heading', { name: 'Gym A' });
+
+ fireEvent.change(screen.getByRole('searchbox', { name: 'Szukaj członka' }), {
+ target: { value: 'ola' },
+ });
+ await waitFor(() =>
+ expect(
+ calls.some((c) => c.url.includes('/admin/gyms/g1/members') && c.url.includes('q=ola')),
+ ),
);
- expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Ogłoszenia')?.to).toBe(
- '/gyms/g1/announcements',
+ });
+
+ it('klik w wiersz otwiera menu członka: zmiana ról wysyła PATCH z pełną listą', async () => {
+ const calls = stubGymFetch();
+ renderGymDetail();
+ const table = await screen.findByRole('table');
+
+ fireEvent.click(within(table).getByText('Jan Nowak'));
+ const dialog = await screen.findByRole('dialog');
+ expect(within(dialog).getByText('Role w siłowni')).toBeInTheDocument();
+
+ // do pełnej listy MEMBER+TRAINER dopisujemy OWNER
+ fireEvent.click(within(dialog).getByRole('checkbox', { name: 'Właściciel — Jan Nowak' }));
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Zapisz role' }));
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.method === 'PATCH' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
+ ),
+ ).toBe(true),
);
+ const patch = calls.find(
+ (c) => c.method === 'PATCH' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
+ );
+ expect(patch?.body).toEqual({ roles: ['MEMBER', 'TRAINER', 'OWNER'] });
+ });
+
+ it('wyrzucenie członka wymaga powodu i wysyła DELETE z powodem', async () => {
+ const calls = stubGymFetch();
+ renderGymDetail();
+ const table = await screen.findByRole('table');
+
+ fireEvent.click(within(table).getByText('Jan Nowak'));
+ const dialog = await screen.findByRole('dialog');
+
+ const removeBtn = within(dialog).getByRole('button', { name: 'Wyrzuć członka' });
+ expect(removeBtn).toBeDisabled();
+
+ fireEvent.change(within(dialog).getByRole('textbox', { name: 'Powód' }), {
+ target: { value: 'Wielokrotne łamanie regulaminu' },
+ });
+ fireEvent.click(removeBtn);
+ await waitFor(() =>
+ expect(
+ calls.some(
+ (c) =>
+ c.method === 'DELETE' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
+ ),
+ ).toBe(true),
+ );
+ const del = calls.find(
+ (c) => c.method === 'DELETE' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
+ );
+ expect(del?.body).toEqual({ reason: 'Wielokrotne łamanie regulaminu' });
+ });
+
+ it('siłownia bez właściciela: alert i picker przypisania w sekcji członków', async () => {
+ const calls = stubGymFetch({ gym: { ...G1, owners: [] } });
+ renderGymDetail();
+ expect(await screen.findByText('Brak właściciela')).toBeInTheDocument();
+
+ const picker = screen.getByRole('combobox', { name: 'Szukaj przyszłego właściciela' });
+ fireEvent.change(picker, { target: { value: 'jan' } });
+ fireEvent.click(await screen.findByRole('option', { name: /Jan Kowalski/ }));
+ fireEvent.click(screen.getByRole('button', { name: 'Przypisz właściciela' }));
+ await waitFor(() =>
+ expect(calls.some((c) => c.method === 'POST' && c.url.endsWith('/owners'))).toBe(true),
+ );
+ expect(calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners'))?.body).toEqual({
+ userId: 'u1',
+ });
+ });
+
+ it('filtr ról przy tabeli członków przekazuje parametr role do API', async () => {
+ const calls = stubGymFetch();
+ renderGymDetail();
+ await screen.findByRole('heading', { name: 'Gym A' });
+
+ fireEvent.change(screen.getByRole('combobox', { name: 'Filtruj role' }), {
+ target: { value: 'TRAINER' },
+ });
+ await waitFor(() =>
+ expect(calls.some((c) => c.url.includes('/members') && c.url.includes('role=TRAINER'))).toBe(
+ true,
+ ),
+ );
+ });
+
+ it('sekcja godzin: pasek tygodnia w treści; wyjątki w modalu „Informacje” (jak w apce)', async () => {
+ stubGymFetch();
+ renderGymDetail();
+ expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
+ expect(screen.getByText('Godziny otwarcia')).toBeInTheDocument();
+ expect(screen.getByText('6:00–22:00')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Dodaj' })).not.toBeInTheDocument();
+
+ fireEvent.click(actionButton('Informacje'));
+ const dialog = await screen.findByRole('dialog');
+ expect(within(dialog).getByText('Dodaj wyjątek — data i tryb dnia')).toBeInTheDocument();
+ expect(within(dialog).getByRole('button', { name: 'Dodaj' })).toBeInTheDocument();
+ });
+
+ it('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async () => {
+ stubGymFetch();
+ renderGymDetail();
+ expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
+
+ fireEvent.click(actionButton('Kod QR'));
+ const dialog = await screen.findByRole('dialog');
+ expect(within(dialog).getByRole('img', { name: 'Gym A' })).toBeInTheDocument();
+ expect(within(dialog).getByText(/\/gyms\/g1\/checkin/)).toBeInTheDocument();
});
it('podstrona urządzeń: mapa ciepła godzinowa + edycja modalem z menu', async () => {
@@ -251,77 +487,4 @@ describe('admin GymDetail page', () => {
).toEqual({ equipmentId: 'eq-2', quantity: 1, spec: { minKg: 2.5, maxKg: 25 } });
expect(calls.some((c) => c.method === 'PATCH')).toBe(false);
});
-
- it('grants and revokes gym owners via admin-only owner endpoints', async () => {
- const calls = stubGymFetch();
- renderGymDetail();
- expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
-
- fireEvent.click(actionButton('Właściciele'));
- const dialog = await screen.findByRole('dialog');
- expect(within(dialog).getByText('Anna Kowalska')).toBeInTheDocument();
-
- // odebranie roli = DELETE /admin/gyms/:id/owners/:userId
- fireEvent.click(within(dialog).getByRole('button', { name: 'Odbierz rolę' }));
- await waitFor(() =>
- expect(
- calls.find((c) => c.method === 'DELETE' && c.url.endsWith('/owners/u-owner')),
- ).toBeTruthy(),
- );
-
- // nadanie roli = POST /admin/gyms/:id/owners { userId }
- const picker = within(dialog).getByRole('combobox', { name: 'Szukaj przyszłego właściciela' });
- fireEvent.change(picker, { target: { value: 'jan' } });
- fireEvent.click(await within(dialog).findByRole('option', { name: /Jan Kowalski/ }));
- fireEvent.click(within(dialog).getByRole('button', { name: 'Nadaj właściciela' }));
- await waitFor(() =>
- expect(calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners'))).toBeTruthy(),
- );
- expect(calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners'))?.body).toEqual({
- userId: 'u1',
- });
- });
-
- it('pokazuje telemetrię bytności dla siłowni REAL', async () => {
- stubGymFetch();
- renderGymDetail();
- expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
-
- expect(await screen.findByText('Bytność')).toBeInTheDocument();
- expect(screen.getByText('teraz w środku')).toBeInTheDocument();
- expect(screen.getByText('40')).toBeInTheDocument(); // wizyty (30 dni)
- expect(
- screen.getByText((_, el) => el?.tagName === 'DD' && el.textContent === '62 min'),
- ).toBeInTheDocument();
- expect(screen.getByText('1.3')).toBeInTheDocument(); // wizyt/dzień (jak w apce: surowa wartość)
- expect(screen.getByText('sztanga · 12')).toBeInTheDocument();
- });
-
- it('telemetria bytności pyta presence-stats ze stałego zakresu 30 dni (bez filtra okresu)', async () => {
- const calls = stubGymFetch();
- renderGymDetail();
- expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
-
- await screen.findByText('teraz w środku');
- // brak filtra okresu w topbarze — widok ogólny zawsze 30 dni
- expect(screen.queryByRole('combobox', { name: 'Zakres dat bytności' })).not.toBeInTheDocument();
-
- const last = calls.filter((c) => c.url.includes('presence-stats')).at(-1);
- expect(last).toBeTruthy();
- const from = new Date(String(new URL(`http://x${last!.url}`).searchParams.get('from')));
- const days = (Date.now() - from.getTime()) / 86_400_000;
- expect(days).toBeGreaterThan(28);
- expect(days).toBeLessThan(32);
- });
-
- it('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async () => {
- stubGymFetch();
- renderGymDetail();
- expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
-
- fireEvent.click(actionButton('Kod QR'));
- const dialog = await screen.findByRole('dialog');
- expect(within(dialog).getByRole('img', { name: 'Gym A' })).toBeInTheDocument();
- expect(within(dialog).getByText(/\/gyms\/g1\/checkin/)).toBeInTheDocument();
- });
});
diff --git a/admin/test/GymLogsPage.test.tsx b/admin/test/GymLogsPage.test.tsx
new file mode 100644
index 0000000..8dc1ade
--- /dev/null
+++ b/admin/test/GymLogsPage.test.tsx
@@ -0,0 +1,130 @@
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes, useParams } from 'react-router-dom';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import GymLogsPage from '../src/pages/gyms/GymLogsPage';
+import { setAccessToken } from '../src/api/client';
+import type { ActivityLog } from '../src/api/types';
+
+const GYM = {
+ id: 'g1',
+ name: 'Gym A',
+ location: 'Warszawa',
+ availability: null,
+ capacity: null,
+ kind: 'REAL',
+ isPrivate: false,
+ equipment: [],
+ _count: { memberships: 3 },
+};
+
+const LOG1: ActivityLog = {
+ id: 'log-1',
+ action: 'gym.created',
+ entityType: 'gym',
+ entityId: 'g1',
+ details: { actorId: 'admin-1', name: 'Gym A' },
+ createdAt: '2026-08-20T10:00:00.000Z',
+ actor: { id: 'admin-1', email: 'admin@fitos.pl', firstName: 'Ada', lastName: 'Admin' },
+};
+
+const LOG2: ActivityLog = {
+ id: 'log-2',
+ action: 'membership.created',
+ entityType: 'membership',
+ entityId: 'user-9',
+ details: { actorId: 'admin-1', userId: 'user-9', gymId: 'g1', roles: ['MEMBER'] },
+ createdAt: '2026-08-21T11:00:00.000Z',
+ actor: { id: 'admin-1', email: 'admin@fitos.pl', firstName: 'Ada', lastName: 'Admin' },
+};
+
+function jsonResponse(status: number, body: unknown) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+function DetailStub() {
+ const { id } = useParams();
+ return
GYM-DETAIL-{id}
;
+}
+
+function renderPage() {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+
+
+
+ } />
+ } />
+
+
+ ,
+ );
+}
+
+beforeEach(() => {
+ setAccessToken('admin-tok');
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('admin GymLogsPage', () => {
+ it('renderuje wspólną tabelę logów z operacjami siłowni', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes('/logs')) {
+ return jsonResponse(200, { logs: [LOG2, LOG1], total: 2 });
+ }
+ return jsonResponse(200, GYM);
+ }),
+ );
+ renderPage();
+ expect(await screen.findByText('Siłownia utworzona')).toBeInTheDocument();
+ expect(screen.getAllByText('Ada Admin').length).toBeGreaterThan(0);
+ // szczegóły membership: powiązanie z siłownią widoczne w kolumnie szczegółów
+ expect(await screen.findByText('siłownia: g1')).toBeInTheDocument();
+ // powrót na detal siłowni
+ expect(screen.getByRole('link', { name: /Wstecz/ })).toHaveAttribute('href', '/gyms/g1');
+ });
+
+ it('pusty stan, gdy brak operacji powiązanych z siłownią', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes('/logs')) return jsonResponse(200, { logs: [], total: 0 });
+ return jsonResponse(200, GYM);
+ }),
+ );
+ renderPage();
+ expect(await screen.findByText('Brak operacji powiązanych z tą siłownią.')).toBeInTheDocument();
+ });
+
+ it('„Pokaż jeszcze” dokłada limit i odpytuje API', async () => {
+ const urls: string[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ urls.push(url);
+ if (url.includes('/logs'))
+ return jsonResponse(200, {
+ logs: [LOG1],
+ total: 60,
+ });
+ return jsonResponse(200, GYM);
+ }),
+ );
+ const user = userEvent.setup();
+ renderPage();
+ await user.click(await screen.findByRole('button', { name: 'Pokaż jeszcze 59 wpisów' }));
+ await vi.waitFor(() => expect(urls.some((u) => u.includes('limit=100'))).toBe(true));
+ });
+});
diff --git a/admin/test/GymsList.test.tsx b/admin/test/GymsList.test.tsx
index d4a88cb..0b32cb4 100644
--- a/admin/test/GymsList.test.tsx
+++ b/admin/test/GymsList.test.tsx
@@ -6,16 +6,33 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import GymsList from '../src/pages/gyms/GymsList';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
-import type { Gym } from '../src/api/types';
+import type { AdminGymListItem } from '../src/api/types';
-const G1: Gym = {
+const G1: AdminGymListItem = {
id: 'g1',
name: 'Gym A',
location: 'Warszawa',
- availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
+ addressLine1: 'Bobrowiecka 12',
+ addressLine2: null,
+ postalCode: '02-847',
+ city: 'Warszawa',
+ countryCode: 'PL',
+ availability: [
+ { start: '06:00', end: '22:00' },
+ { start: '06:00', end: '22:00' },
+ { start: '06:00', end: '22:00' },
+ { start: '06:00', end: '22:00' },
+ { start: '06:00', end: '22:00' },
+ { start: '06:00', end: '22:00' },
+ { start: '06:00', end: '22:00' },
+ ],
capacity: 50,
- equipment: [],
+ kind: 'REAL',
+ isPrivate: false,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
_count: { memberships: 12 },
+ owners: [{ id: 'u1', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' }],
};
function jsonResponse(status: number, body: unknown) {
@@ -40,6 +57,11 @@ function DetailStub() {
return
GYM-DETAIL-{id}
;
}
+function UserStub() {
+ const { id } = useParams();
+ return
USER-{id}
;
+}
+
function renderGyms() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
@@ -48,6 +70,7 @@ function renderGyms() {
} />
} />
+ } />
,
@@ -64,47 +87,67 @@ afterEach(() => {
});
describe('admin GymsList page', () => {
- it('lists gyms fetched from the API', async () => {
+ it('lists gyms fetched from the API with admin data (address, owners, today; no app column)', async () => {
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
renderGyms();
expect(await screen.findByText('Gym A')).toBeInTheDocument();
- expect(screen.getByText('Warszawa')).toBeInTheDocument();
- expect(screen.getByText('12/50 członków')).toBeInTheDocument();
+ expect(screen.getByText('Bobrowiecka 12, 02-847 Warszawa')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Anna Kowalska' })).toHaveAttribute(
+ 'href',
+ '/users/u1',
+ );
+ // komórek licznika bez duplikowania nagłówka „Członkowie”
+ expect(screen.getByText('12/50')).toBeInTheDocument();
+ expect(screen.getByText('6:00–22:00')).toBeInTheDocument();
+ // kolumna Aplikacja usunięta — do apki prowadzi akcja z topbara konsoli
+ expect(screen.queryByRole('link', { name: 'Otwórz w aplikacji' })).not.toBeInTheDocument();
});
- it('clicking a gym opens the detail page', async () => {
+ it('klik w dowolnym miejscu wiersza otwiera konsolę siłowni', async () => {
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
const user = userEvent.setup();
renderGyms();
- await user.click(await screen.findByRole('link', { name: 'Gym A' }));
+ await user.click(await screen.findByText('Bobrowiecka 12, 02-847 Warszawa'));
expect(await screen.findByText('GYM-DETAIL-g1')).toBeInTheDocument();
});
- it('filters gyms by the search box', async () => {
+ it('klik w link właściciela prowadzi do profilu usera, nie do konsoli', async () => {
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
+ const user = userEvent.setup();
renderGyms();
- expect(await screen.findByText('Gym A')).toBeInTheDocument();
- // wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
- act(() => useListSearch.getState().setQuery('gyms', 'kraków'));
- expect(screen.queryByText('Gym A')).not.toBeInTheDocument();
- expect(screen.getByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument();
+ await user.click(await screen.findByRole('link', { name: 'Anna Kowalska' }));
+ expect(await screen.findByText('USER-u1')).toBeInTheDocument();
+ expect(screen.queryByText('GYM-DETAIL-g1')).not.toBeInTheDocument();
});
- it('karty REAL pokazują licznik „teraz” z endpointu occupancy', async () => {
- const realGym: Gym = { ...G1, kind: 'REAL' };
- vi.stubGlobal(
- 'fetch',
- vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- if (url.includes('/admin/gyms/occupancy'))
- return jsonResponse(200, {
- gyms: [{ gymId: 'g1', name: 'Gym A', capacity: 50, count: 3 }],
- });
- return jsonResponse(200, { gyms: [realGym] });
- }),
- );
+ it('search queries the API with the q parameter (server-side)', async () => {
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes('?q=')) return jsonResponse(200, { gyms: [] });
+ return jsonResponse(200, { gyms: [G1] });
+ });
+ vi.stubGlobal('fetch', fetchMock);
renderGyms();
expect(await screen.findByText('Gym A')).toBeInTheDocument();
- expect(await screen.findByText('teraz: 3 osoby (50)')).toBeInTheDocument();
+ // wyszukiwarka jest w menu kontekstowym (Layout) — zapytanie ustawiamy przez store
+ act(() => useListSearch.getState().setQuery('gyms', 'kraków'));
+ await vi.waitFor(
+ () => {
+ const urls = fetchMock.mock.calls.map((c) => String(c[0]));
+ expect(urls.some((u) => u.includes('/admin/gyms?q=krak%C3%B3w'))).toBe(true);
+ },
+ { timeout: 3000 },
+ );
+ expect(await screen.findByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument();
+ // klient-side filtrowanie nie istnieje: bez q pełna lista znów jest w zapytaniu
+ const urls = fetchMock.mock.calls.map((c) => String(c[0]));
+ expect(urls.some((u) => u.endsWith('/admin/gyms'))).toBe(true);
+ });
+
+ it('brak właścicieli sygnalizowany w kolumnie Właściciele', async () => {
+ mockFetchSequence(jsonResponse(200, { gyms: [{ ...G1, owners: [] }] }));
+ renderGyms();
+ expect(await screen.findByText('Gym A')).toBeInTheDocument();
+ expect(screen.getByText('brak')).toBeInTheDocument();
});
});
diff --git a/admin/test/e2e/admin.spec.ts b/admin/test/e2e/admin.spec.ts
index 0358404..4aca294 100644
--- a/admin/test/e2e/admin.spec.ts
+++ b/admin/test/e2e/admin.spec.ts
@@ -19,17 +19,32 @@ test('sidebar zawiera link „Aplikacja” prowadzący do aplikacji użytkownika
await expect(link).toHaveAttribute('href', /:5173\/?$/);
});
-test('kliknięcie w siłownię otwiera podstronę z detalami', async ({ page }) => {
+test('kliknięcie w siłownię otwiera konsolę z KPI, godzinami i członkami', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
- await expect(page.getByRole('heading', { name: 'Fit Factory' })).toBeVisible();
- // pasek godzin pod hero: forma zegarowa z minutami + wyjątek harmonogramu
- await expect(page.locator('span:visible', { hasText: '6:00–22:00' })).toBeVisible();
- await expect(page.getByText('10:00–14:00')).toBeVisible();
+ // topbar = kategoria „Siłownia”, nazwa siłowni dopiero w treści (h2)
+ await expect(page.getByRole('heading', { level: 1, name: 'Siłownia' })).toBeVisible();
+ await expect(page.getByRole('heading', { level: 2, name: 'Fit Factory' })).toBeVisible();
+ // konsola admina: KPI członków (licznik/pojemność) i tabela członków
+ await expect(page.getByText('12/120')).toBeVisible();
+ await expect(page.getByRole('heading', { level: 3, name: /Członkowie/ })).toBeVisible();
+ await expect(page.getByRole('table')).toBeVisible();
+ // pasek godzin w sekcji godzin: forma zegarowa z minutami
+ await expect(page.getByText('6:00–22:00', { exact: true })).toBeVisible();
+ // wyjątki harmonogramu edytowane w modalu „Informacje” (jak w apce)
+ await page.getByRole('button', { name: 'Zarządzaj' }).click();
+ await page.getByRole('button', { name: 'Informacje' }).click();
+ const infoDialog = page.getByRole('dialog');
+ await expect(infoDialog.getByText('Dodaj wyjątek — data i tryb dnia')).toBeVisible();
+ await expect(infoDialog.getByText('10:00–14:00')).toBeVisible();
+ await page.keyboard.press('Escape');
// menu kontekstowe podstrony detalu nie dziedziczy akcji ze strony listy (brak ikony ➕)
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
+ // przycisk „← Wróć” w nagłówku treści → lista wszystkich siłowni
+ await page.getByRole('link', { name: 'Wróć' }).click();
+ await expect(page).toHaveURL(/\/gyms$/);
});
test('ponowne dodanie tego samego typu tworzy osobną instancję (bez inkrementacji ilości)', async ({
@@ -39,12 +54,12 @@ test('ponowne dodanie tego samego typu tworzy osobną instancję (bez inkrementa
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
- await expect(page.getByText('Dywan ×3')).toBeVisible();
// akcja „Urządzenia" w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje) → podstrona urządzeń; edycja modalem z menu
await page.getByRole('button', { name: 'Zarządzaj' }).click();
await page.getByRole('button', { name: 'Urządzenia' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1\/equipment$/);
+ await expect(page.getByText('Dywan ×3')).toBeVisible();
await page.getByRole('button', { name: 'Edytuj urządzenia' }).click();
const addReq = page.waitForRequest(
(req) => req.url().endsWith('/admin/gyms/gym-1/equipment') && req.method() === 'POST',
@@ -82,36 +97,58 @@ test('dodanie urządzenia z własnymi parametrami wysyła spec w POST', async ({
});
});
-test('admin zarządza właścicielami siłowni z menu kontekstowego', async ({ page }) => {
+test('rola członka edytowana z menu wiersza — zapis wysyła PATCH z pełną listą ról', async ({
+ page,
+}) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
- // modal Właściciele z rozwijanego „Zarządzaj” (desktop: kontrolka zbiera akcje)
- // (karta „Dane" usunięta — lista właścicieli dostępna tylko w modalu)
- await page.getByRole('button', { name: 'Zarządzaj' }).click();
- await page.locator('button[data-slot="button"]', { hasText: 'Właściciele' }).click();
+ // klik w wiersz członka otwiera jego menu (brak kolumny akcji w tabeli)
+ const janRow = page.locator('tr', { hasText: 'Jan Kowalski' });
+ await janRow.click();
const dialog = page.getByRole('dialog');
- await expect(dialog.getByText('Anna Kowalska')).toBeVisible();
+ await expect(dialog.getByText('Role w siłowni')).toBeVisible();
- // nadanie roli = POST /admin/gyms/gym-1/owners { userId }
- const addReq = page.waitForRequest(
- (req) => req.url().includes('/admin/gyms/gym-1/owners') && req.method() === 'POST',
+ // do pełnej listy MEMBER+TRAINER dopisujemy OWNER → PATCH z pełną listą
+ await dialog.getByRole('checkbox', { name: 'Właściciel — Jan Kowalski' }).click();
+ const patchReq = page.waitForRequest(
+ (req) =>
+ req.url().includes('/admin/users/user-1/memberships/gym-1') && req.method() === 'PATCH',
);
- await dialog.getByRole('combobox', { name: 'Szukaj przyszłego właściciela' }).fill('jan');
- await page.getByRole('option', { name: /Jan Kowalski/ }).click();
- await dialog.getByRole('button', { name: 'Nadaj właściciela' }).click();
- expect((await addReq).postDataJSON()).toEqual({ userId: 'user-1' });
- await expect(dialog.getByText('Jan Kowalski')).toBeVisible();
+ await dialog.getByRole('button', { name: 'Zapisz role' }).click();
+ const roles = (await patchReq).postDataJSON().roles as string[];
+ expect(roles).toEqual(expect.arrayContaining(['MEMBER', 'TRAINER', 'OWNER']));
+ await expect(janRow.getByText('Właściciel', { exact: true })).toBeVisible();
+});
- // odebranie roli = DELETE /admin/gyms/gym-1/owners/:userId
+test('wyrzucenie członka z siłowni — wymagalny powód i DELETE z powodem w ciele', async ({
+ page,
+}) => {
+ mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
+ await loginAsAdmin(page);
+ await page.getByRole('link', { name: 'Fit Factory' }).click();
+ await expect(page).toHaveURL(/\/gyms\/gym-1$/);
+
+ const janRow = page.locator('tr', { hasText: 'Jan Kowalski' });
+ await janRow.click();
+ const dialog = page.getByRole('dialog');
+
+ // bez powodu usunięcie zablokowane
+ const removeBtn = dialog.getByRole('button', { name: 'Wyrzuć członka' });
+ await expect(removeBtn).toBeDisabled();
+
+ await dialog.getByRole('textbox', { name: 'Powód' }).fill('Wielokrotne łamanie regulaminu');
const delReq = page.waitForRequest(
- (req) => req.url().includes('/admin/gyms/gym-1/owners/user-owner') && req.method() === 'DELETE',
+ (req) =>
+ req.url().includes('/admin/users/user-1/memberships/gym-1') && req.method() === 'DELETE',
);
- await dialog.getByRole('button', { name: 'Odbierz rolę' }).first().click();
- await delReq;
- await expect(dialog.getByText('Anna Kowalska')).toHaveCount(0);
+ await removeBtn.click();
+ expect((await delReq).postDataJSON()).toEqual({ reason: 'Wielokrotne łamanie regulaminu' });
+
+ // stan mocka: członek znika z tabeli po refetchu
+ await expect(page.locator('tr', { hasText: 'Jan Kowalski' })).toHaveCount(0);
});
test('kliknięcie w użytkownika otwiera przegląd profilu (wzór z apki)', async ({ page }) => {
@@ -521,7 +558,46 @@ test('wyszukiwarka w menu kontekstowym filtruje listę siłowni', async ({ page
// po logowaniu jesteśmy na /gyms
await expect(page.getByText('Fit Factory')).toBeVisible();
await expect(page.getByText('Mega Gym')).toBeVisible();
+ // wyszukiwanie jest po stronie API — żądanie niesie parametr q
+ const qRequest = page.waitForRequest(
+ (req) => req.url().includes('/api/v1/admin/gyms?') && req.url().includes('q=krak'),
+ );
await page.getByRole('searchbox', { name: 'Szukaj siłowni' }).fill('kraków');
await expect(page.getByText('Fit Factory')).not.toBeVisible();
await expect(page.getByText('Mega Gym')).toBeVisible();
+ await expect(qRequest).resolves.toBeTruthy();
+});
+
+test('logi siłowni: akcja „Logi” w menu prowadzi na podstronę z tabelą operacji', async ({
+ page,
+}) => {
+ mockApi(page, { gyms: { gyms: [TEST_GYM] } });
+ await loginAsAdmin(page);
+ await page.getByRole('link', { name: 'Fit Factory' }).click();
+ await expect(page).toHaveURL(/\/gyms\/gym-1$/);
+ // akcja „Logi" w rozwijanym „Zarządzaj" → podstrona logów
+ await page.getByRole('button', { name: 'Zarządzaj' }).click();
+ await page.getByRole('button', { name: 'Logi' }).click();
+ await expect(page).toHaveURL(/\/gyms\/gym-1\/logs$/);
+ // wspólna tabela logów: kolumny i wpisy
+ await expect(page.getByRole('columnheader', { name: 'Data' })).toBeVisible();
+ await expect(page.getByRole('heading', { level: 1, name: 'Logi siłowni' })).toBeVisible();
+});
+
+test('akcja „Otwórz w aplikacji” otwiera widok siłowni z perspektywy usera', async ({ page }) => {
+ mockApi(page, { gyms: { gyms: [TEST_GYM] } });
+ await loginAsAdmin(page);
+ await page.getByRole('link', { name: 'Fit Factory' }).click();
+ await expect(page).toHaveURL(/\/gyms\/gym-1$/);
+ // aplikacja usera nie działa w tym teście — podstawiamy stub pod jej origin,
+ // żeby popup zatrzymał się na docelowym URL zamiast chrome-error
+ await page.context().route('http://localhost:5173/**', (route) =>
+ route.fulfill({ contentType: 'text/html', body: '
app' }),
+ );
+ // osobny przycisk w topbarze konsoli (dodatek, nie główna ścieżka) — popup na APP_URL
+ const popupPromise = page.waitForEvent('popup');
+ await page.getByRole('button', { name: 'Otwórz w aplikacji' }).click();
+ const popup = await popupPromise;
+ // dev (vite 5174) → port aplikacji 5173 wg mapowania z src/config.ts
+ await expect(popup).toHaveURL(/:5173\/gyms\/gym-1$/);
});
diff --git a/admin/test/e2e/gym-gallery.spec.ts b/admin/test/e2e/gym-gallery.spec.ts
index b3fe366..91cc3c4 100644
--- a/admin/test/e2e/gym-gallery.spec.ts
+++ b/admin/test/e2e/gym-gallery.spec.ts
@@ -20,10 +20,10 @@ test('admin zarządza galerią zdjęć siłowni REAL (upload/okładka/usuwanie)'
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
- await expect(page.getByRole('link', { name: /Galeria zdjęć/ })).toBeVisible();
- // kafelek galerii → podstrona galerii (read-only)
- await page.getByRole('link', { name: /Galeria zdjęć/ }).click();
+ // akcja „Galeria" w rozwijanym „Zarządzaj” → podstrona galerii (read-only)
+ await page.getByRole('button', { name: 'Zarządzaj' }).click();
+ await page.getByRole('button', { name: 'Galeria' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1\/gallery$/);
await expect(page.getByRole('heading', { name: 'Galeria zdjęć' })).toBeVisible();
diff --git a/admin/test/e2e/gym-qr.spec.ts b/admin/test/e2e/gym-qr.spec.ts
new file mode 100644
index 0000000..8b14896
--- /dev/null
+++ b/admin/test/e2e/gym-qr.spec.ts
@@ -0,0 +1,26 @@
+import type { Page } from '@playwright/test';
+import { test, expect } from './fixtures';
+import { mockApi, TEST_GYM } from './mock-api';
+
+async function loginAsAdmin(page: Page) {
+ await page.goto('/login');
+ await page.locator('input[type="email"]').fill('admin@fitos.pl');
+ await page.locator('input[type="password"]').fill('haslo123');
+ await page.getByRole('button', { name: 'Zaloguj' }).click();
+ await expect(page).toHaveURL(/\/gyms$/);
+}
+
+test('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async ({ page }) => {
+ mockApi(page, { gyms: { gyms: [TEST_GYM] } });
+ await loginAsAdmin(page);
+ await page.getByRole('link', { name: 'Fit Factory' }).click();
+ await expect(page).toHaveURL(/\/gyms\/gym-1$/);
+
+ // akcja „Kod QR” w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje)
+ await page.getByRole('button', { name: 'Zarządzaj' }).click();
+ await page.getByRole('button', { name: 'Kod QR' }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog.getByRole('heading', { name: 'Kod QR siłowni' })).toBeVisible();
+ await expect(dialog.getByRole('img', { name: 'Fit Factory' })).toBeVisible();
+ await expect(dialog.getByText(/\/gyms\/gym-1\/checkin/)).toBeVisible();
+});
diff --git a/admin/test/e2e/mock-api.ts b/admin/test/e2e/mock-api.ts
index 78acbcb..33b1c4a 100644
--- a/admin/test/e2e/mock-api.ts
+++ b/admin/test/e2e/mock-api.ts
@@ -86,7 +86,10 @@ export const TEST_GYM: Gym = {
],
coverPhoto: '/gyms/gym-1/photos/photo-1',
photos: TEST_GYM_PHOTOS,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-05T00:00:00.000Z',
_count: { memberships: 12 },
+ owners: [{ id: 'user-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' }],
};
export const TEST_GYM_2: Gym = {
@@ -99,7 +102,10 @@ export const TEST_GYM_2: Gym = {
isPrivate: false,
equipment: [],
coverPhoto: null,
+ createdAt: '2026-02-01T00:00:00.000Z',
+ updatedAt: '2026-02-05T00:00:00.000Z',
_count: { memberships: 4 },
+ owners: [],
};
/** Właściciele (OWNER) siłowni gym-1 — tylko w odpowiedzi GET /admin/gyms/gym-1. */
@@ -107,6 +113,36 @@ export const TEST_GYM_OWNERS = [
{ id: 'user-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' },
];
+/** Członkowie siłowni gym-1 — GET /admin/gyms/gym-1/members (tabela w konsoli detalu). */
+export const TEST_GYM_MEMBERS = [
+ {
+ membershipId: 'membership-1',
+ roles: ['OWNER'],
+ joinedAt: '2026-01-02T10:00:00.000Z',
+ checkedInNow: false,
+ user: {
+ id: 'user-owner',
+ firstName: 'Anna',
+ lastName: 'Kowalska',
+ email: 'anna@fitos.pl',
+ status: 'ACTIVE',
+ },
+ },
+ {
+ membershipId: 'membership-2',
+ roles: ['MEMBER', 'TRAINER'],
+ joinedAt: '2026-02-01T10:00:00.000Z',
+ checkedInNow: true,
+ user: {
+ id: 'user-1',
+ firstName: 'Jan',
+ lastName: 'Kowalski',
+ email: 'jan@fitos.pl',
+ status: 'ACTIVE',
+ },
+ },
+];
+
/** Wniosek o weryfikację wirtualnej siłowni (PENDING, z dokumentem). */
export const TEST_CLAIM_VERIFICATION: GymClaim = {
id: 'claim-v1',
@@ -440,6 +476,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
let photoSeq = TEST_GYM_PHOTOS.length;
// Stateful: właściciele siłowni gym-1 — nadawanie/odbieranie roli OWNER.
const gymOwnersState = TEST_GYM_OWNERS.map((o) => ({ ...o }));
+ // Stateful: członkowie gym-1 — menu członka (PATCH ról / DELETE z powodem).
+ const membersState = TEST_GYM_MEMBERS.map((m) => ({ ...m, roles: [...m.roles] }));
const coverOf = (photos: typeof gymPhotosState) =>
photos.length ? `/gyms/gym-1/photos/${photos[0].id}` : null;
const gymDetailBody = () =>
@@ -456,41 +494,6 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() }),
);
- // Live occupancy listy siłowni (GET /admin/gyms/occupancy) — licznik „teraz” na kartach REAL.
- page.route('**/api/v1/admin/gyms/occupancy', (route) =>
- route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({
- gyms: [{ gymId: 'gym-1', name: TEST_GYM.name, capacity: TEST_GYM.capacity, count: 7 }],
- }),
- }),
- );
-
- // Telemetria bytności (GET /admin/gyms/gym-1/presence-stats).
- page.route('**/api/v1/admin/gyms/*/presence-stats*', (route) =>
- route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({
- gym: { id: 'gym-1', name: TEST_GYM.name, kind: 'REAL', capacity: TEST_GYM.capacity },
- stats: {
- visits: 96,
- avgStayMinutes: 63,
- heatmap: [
- { day: 1, hour: 18, count: 9 },
- { day: 4, hour: 19, count: 6 },
- ],
- topGyms: [{ gymId: 'gym-1', name: TEST_GYM.name, count: 96 }],
- peak: 9,
- topEquipment: [{ equipmentId: 'eq-1', name: 'ławka', nameEn: 'Bench', count: 41 }],
- live: 7,
- visitsPerDay: 3.2,
- },
- }),
- }),
- );
-
// POST /gyms/gym-1/photos — upload (multipart, pole `photos`).
page.route('**/api/v1/gyms/*/photos', (route) => {
const req = route.request();
@@ -541,24 +544,91 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
});
});
- page.route('**/api/v1/admin/gyms', (route) => {
- const list = (gyms as { gyms?: Array
> } | null)?.gyms;
- const body =
- list && gyms
- ? {
- ...gyms,
- gyms: list.map((g) =>
- g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g,
- ),
- }
- : gyms;
+ // Lista siłowni (bez `/gym-1`) — wyszukiwanie i filtr `kind` po stronie „API”.
+ page.route(
+ (url) => /\/api\/v1\/admin\/gyms(\?.*)?$/.test(url.pathname + (url.search ?? '')),
+ (route) => {
+ const raw = (gyms as { gyms?: Array> } | null)?.gyms ?? [];
+ const params = new URL(route.request().url()).searchParams;
+ const q = (params.get('q') ?? '').trim().toLowerCase();
+ const kind = params.get('kind');
+ const filtered = raw.filter((g) => {
+ if (kind && g.kind !== kind) return false;
+ if (!q) return true;
+ const hay = [
+ String(g.name ?? ''),
+ String(g.location ?? ''),
+ String(g.city ?? ''),
+ String(g.addressLine1 ?? ''),
+ String(g.postalCode ?? ''),
+ ...(Array.isArray(g.owners)
+ ? (g.owners as Array>).flatMap((o) => [
+ String(o.firstName ?? ''),
+ String(o.lastName ?? ''),
+ String(o.email ?? ''),
+ ])
+ : []),
+ ]
+ .join(' ')
+ .toLowerCase();
+ return hay.includes(q);
+ });
+ const body =
+ gyms != null
+ ? {
+ ...gyms,
+ gyms: filtered.map((g) =>
+ g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g,
+ ),
+ }
+ : gyms;
+ return route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(body),
+ });
+ },
+ );
+
+ // Logi pojedynczej siłowni (GET /admin/gyms/:id/logs).
+ page.route('**/api/v1/admin/gyms/*/logs*', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(logs),
+ }),
+ );
+
+ // Członkowie pojedynczej siłowni (GET /admin/gyms/:id/members) — q i role po stronie „API";
+ // role żyją w membersState (menu członka PATCH/DELETE aktualizuje je na bieżąco).
+ page.route('**/api/v1/admin/gyms/*/members*', (route) => {
+ const params = new URL(route.request().url()).searchParams;
+ const q = (params.get('q') ?? '').trim().toLowerCase();
+ const role = params.get('role');
+ const list = membersState.filter(
+ (m) =>
+ (!role || m.roles.includes(role)) &&
+ (!q ||
+ `${m.user.firstName ?? ''} ${m.user.lastName ?? ''} ${m.user.email}`
+ .toLowerCase()
+ .includes(q)),
+ );
return route.fulfill({
status: 200,
contentType: 'application/json',
- body: JSON.stringify(body),
+ body: JSON.stringify({ members: list, total: list.length }),
});
});
+ // Wnioski i zaproszenia pojedynczej siłowni (GET /admin/gyms/:id/related).
+ page.route('**/api/v1/admin/gyms/*/related*', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ claims: [], invitations: [] }),
+ }),
+ );
+
// POST = zawsze NOWA instancja; PATCH/DELETE po id instancji (GymEquipment.id).
page.route('**/api/v1/admin/gyms/*/equipment', (route) => {
const req = route.request();
@@ -613,7 +683,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
return route.fulfill({ status: 204 });
});
- // Właściciele (OWNER): POST nadaje / DELETE odbiera rolę — stanowo (gymOwnersState).
+ // Właściciele (OWNER): POST nadaje / DELETE odbiera rolę — stanowo (gymOwnersState + membersState).
page.route('**/api/v1/admin/gyms/*/owners**', (route) => {
const req = route.request();
if (req.method() === 'POST') {
@@ -627,6 +697,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
lastName: u.lastName,
email: u.email,
});
+ const m = membersState.find((x) => x.user.id === u.id);
+ if (m && !m.roles.includes('OWNER')) m.roles.push('OWNER');
}
return route.fulfill({
status: 200,
@@ -638,6 +710,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
const userId = req.url().match(/owners\/([^/?]+)/)?.[1];
const idx = gymOwnersState.findIndex((o) => o.id === userId);
if (idx >= 0) gymOwnersState.splice(idx, 1);
+ const m = userId ? membersState.find((x) => x.user.id === userId) : undefined;
+ if (m) m.roles = m.roles.filter((r) => r !== 'OWNER');
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405 });
@@ -769,13 +843,27 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
}),
);
- page.route('**/api/v1/admin/users/*/memberships/*', (route) =>
- route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({ membership: {} }),
- }),
- );
+ // PATCH ról / DELETE członkostwa (menu członka w konsoli siłowni) — stanowo (membersState).
+ page.route('**/api/v1/admin/users/*/memberships/*', (route) => {
+ const req = route.request();
+ const userId = decodeURIComponent(req.url().match(/users\/([^/]+)\/memberships\//)?.[1] ?? '');
+ if (req.method() === 'PATCH') {
+ const body = JSON.parse(req.postData() || '{}');
+ const m = membersState.find((x) => x.user.id === userId);
+ if (m && Array.isArray(body.roles)) m.roles = body.roles;
+ return route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ membership: { userId, gymId: 'gym-1', roles: m?.roles ?? [] } }),
+ });
+ }
+ if (req.method() === 'DELETE') {
+ const idx = membersState.findIndex((x) => x.user.id === userId);
+ if (idx >= 0) membersState.splice(idx, 1);
+ return route.fulfill({ status: 204 });
+ }
+ return route.fulfill({ status: 405 });
+ });
// ---------- gym claims (verifications) ----------
// Kolejność rejestracji: list (catch-all) najpierw, potem coraz bardziej
diff --git a/admin/test/e2e/presence.spec.ts b/admin/test/e2e/presence.spec.ts
deleted file mode 100644
index 323c42b..0000000
--- a/admin/test/e2e/presence.spec.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import type { Page } from '@playwright/test';
-import { test, expect } from './fixtures';
-import { mockApi, TEST_GYM } from './mock-api';
-
-async function loginAsAdmin(page: Page) {
- await page.goto('/login');
- await page.locator('input[type="email"]').fill('admin@fitos.pl');
- await page.locator('input[type="password"]').fill('haslo123');
- await page.getByRole('button', { name: 'Zaloguj' }).click();
- await expect(page).toHaveURL(/\/gyms$/);
-}
-
-test('lista siłowni pokazuje licznik „teraz” na karcie REAL', async ({ page }) => {
- mockApi(page, { gyms: { gyms: [TEST_GYM] } });
- await loginAsAdmin(page);
- await expect(page.getByText('teraz: 7 osób (120)')).toBeVisible();
-});
-
-test('detal REAL pokazuje kartę bytności z telemetrią', async ({ page }) => {
- mockApi(page, { gyms: { gyms: [TEST_GYM] } });
- await loginAsAdmin(page);
- await page.getByRole('link', { name: 'Fit Factory' }).click();
- await expect(page).toHaveURL(/\/gyms\/gym-1$/);
-
- await expect(page.getByRole('heading', { name: 'Bytność' })).toBeVisible();
- await expect(page.getByText('teraz w środku')).toBeVisible();
- await expect(page.getByText('7', { exact: true })).toBeVisible();
- await expect(page.getByText('wizyty (30 dni)')).toBeVisible();
- await expect(page.getByText('96', { exact: true })).toBeVisible();
- await expect(page.getByText('ławka · 41')).toBeVisible();
-});
-
-test('widok ogólny bytności ma stały zakres 30 dni (bez filtra okresu)', async ({ page }) => {
- mockApi(page, { gyms: { gyms: [TEST_GYM] } });
- await loginAsAdmin(page);
- await page.getByRole('link', { name: 'Fit Factory' }).click();
- await expect(page.getByText('wizyty (30 dni)')).toBeVisible();
- await expect(page.getByRole('combobox', { name: 'Zakres dat bytności' })).toHaveCount(0);
-});
-
-test('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async ({ page }) => {
- mockApi(page, { gyms: { gyms: [TEST_GYM] } });
- await loginAsAdmin(page);
- await page.getByRole('link', { name: 'Fit Factory' }).click();
- await expect(page).toHaveURL(/\/gyms\/gym-1$/);
-
- // akcja „Kod QR” w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje)
- await page.getByRole('button', { name: 'Zarządzaj' }).click();
- await page.getByRole('button', { name: 'Kod QR' }).click();
- const dialog = page.getByRole('dialog');
- await expect(dialog.getByRole('heading', { name: 'Kod QR siłowni' })).toBeVisible();
- await expect(dialog.getByRole('img', { name: 'Fit Factory' })).toBeVisible();
- await expect(dialog.getByText(/\/gyms\/gym-1\/checkin/)).toBeVisible();
-});