Files
FitOS/admin/test/GymDetail.test.tsx

491 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { render, screen, fireEvent, waitFor, within } 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 GymDetail from '../src/pages/gyms/GymDetail';
import GymEquipmentPage from '../src/pages/gyms/GymEquipmentPage';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import { Topbar } from '../src/topbar';
import type { Equipment, Gym, User } from '../src/api/types';
// QR generowany przez stub — w jsdom canvas może być niedostępny
vi.mock('qrcode', () => ({
toDataURL: vi.fn(async () => 'data:image/png;base64,MOCK'),
}));
const OWNER1 = { id: 'u-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' };
const G1: Gym = {
id: 'g1',
name: 'Gym A',
location: 'Polna 4, 00-001 Warszawa',
addressLine1: 'Polna 4',
addressLine2: null,
postalCode: '00-001',
city: 'Warszawa',
countryCode: 'PL',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 50,
kind: 'REAL',
isPrivate: false,
equipment: [],
coverPhoto: null,
createdAt: '2026-01-01T00:00:00.000Z',
_count: { memberships: 12 },
owners: [OWNER1],
};
const EQ1: Equipment = {
id: 'eq-1',
name: 'sztanga',
kind: 'BARBELL',
spec: { maxLoadKg: 100 },
description: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};
const EQ2: Equipment = {
id: 'eq-2',
name: 'hantle',
kind: 'DUMBBELL',
spec: { minKg: 2.5, maxKg: 25 },
description: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};
const G1_EQ: Gym = {
...G1,
equipment: [{ id: 'ge-2', gymId: 'g1', equipmentId: 'eq-2', quantity: 2, equipment: EQ2 }],
};
const U1 = {
id: 'u1',
email: 'jan@fitos.pl',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
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) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
/** 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 ?? [];
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method ?? 'GET';
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('/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'))
return jsonResponse(200, {
equipment: [
{
equipmentId: 'eq-2',
name: 'hantle',
nameEn: null,
cells: [{ hour: 18, count: 3 }],
peak: 3,
},
],
});
if (url.endsWith('/admin/gyms/g1/equipment') && method === 'POST') {
return jsonResponse(200, {
gym: G1_EQ,
instance: { id: 'ge-9', gymId: 'g1', equipmentId: 'eq-2', quantity: 1, spec: null },
});
}
if (url.includes('/admin/gyms/g1/equipment/ge-2') && method === 'PATCH') {
return jsonResponse(200, { gym: G1_EQ });
}
if (url.includes('/admin/gyms/g1/owners') && method === 'POST') {
return jsonResponse(200, { membership: { gymId: 'g1', roles: ['OWNER'] } });
}
if (url.includes('/admin/gyms/g1/owners') && method === 'DELETE') return jsonResponse(204, {});
if (url.includes('/admin/gyms/g1')) return jsonResponse(200, gym);
throw new Error(`Unexpected fetch: ${method} ${url}`);
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
/** Akcja grupowa w topbarze (ikona grupy ma ten sam label — wybieramy po data-slot Buttona). */
function actionButton(label: string): HTMLElement {
const btn = Array.from(document.querySelectorAll('button[data-slot="button"]')).find(
(b) => b.textContent?.trim() === label,
);
if (!btn) throw new Error(`Brak akcji w menu: ${label}`);
return btn;
}
function renderGymDetail(initialPath = '/gyms/g1') {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={[initialPath]}>
<QueryClientProvider client={queryClient}>
<Topbar />
<Routes>
<Route path="/gyms/:id" element={<GymDetail />} />
<Route path="/gyms/:id/equipment" element={<GymEquipmentPage />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
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();
// 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();
// 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']);
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',
'Logi',
'Usuń siłownię',
]);
expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Tablica')?.to).toBe(
'/gyms/g1/board',
);
});
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')),
),
);
});
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 () => {
const calls = stubGymFetch({ gym: G1_EQ });
renderGymDetail();
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
fireEvent.click(actionButton('Urządzenia'));
expect(await screen.findByText('Korzystanie z urządzeń (godziny)')).toBeInTheDocument();
expect(await screen.findByTitle('18:00 — 3 użycia')).toBeInTheDocument();
fireEvent.click(actionButton('Edytuj urządzenia'));
const dialog = await screen.findByRole('dialog');
// select pokazuje cały katalog — sprzęt już dodany jest oznaczony bieżącą ilością
expect(
await within(dialog).findByRole('option', { name: 'hantle (na stanie: 2)' }),
).toBeInTheDocument();
fireEvent.change(within(dialog).getByRole('combobox', { name: 'Dodaj urządzenie' }), {
target: { value: 'eq-2' },
});
// pozycja z katalogu DUMBBELL wymaga własnych parametrów — zawsze wpisywanych przez admina
fireEvent.change(within(dialog).getByRole('spinbutton', { name: 'Min. obciążenie (kg)' }), {
target: { value: '2.5' },
});
fireEvent.change(within(dialog).getByRole('spinbutton', { name: 'Max. obciążenie (kg)' }), {
target: { value: '25' },
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Dodaj', exact: true }));
// każde dodanie = POST tworzący NOWĄ instancję (bez PATCH-a ilości istniejącej)
await waitFor(() =>
expect(
calls.find((c) => c.method === 'POST' && c.url.endsWith('/admin/gyms/g1/equipment')),
).toBeTruthy(),
);
expect(
calls.find((c) => c.method === 'POST' && c.url.endsWith('/admin/gyms/g1/equipment'))?.body,
).toEqual({ equipmentId: 'eq-2', quantity: 1, spec: { minKg: 2.5, maxKg: 25 } });
expect(calls.some((c) => c.method === 'PATCH')).toBe(false);
});
});