import { act, render, screen, within } 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 UserForm from '../src/pages/users/UserForm'; import { setAccessToken } from '../src/api/client'; import { useAuth } from '../src/store/auth'; import { API_BASE } from '../src/config'; import type { Gym, PlatformRole, User } from '../src/api/types'; const GYM_A: Gym = { id: 'gym-a', name: 'Fit Factory', location: 'Warszawa', availability: null, capacity: 10, kind: 'REAL', isPrivate: false, equipment: [], coverPhoto: null, }; const GYM_B: Gym = { id: 'gym-b', name: 'Steel Gym', location: 'Kraków', availability: null, capacity: null, kind: 'REAL', isPrivate: false, equipment: [], coverPhoto: null, }; function emptyUser(over: Partial): User { return { id: 'u1', email: 'x@test.local', firstName: null, lastName: null, nickname: null, socialMedia: null, birthDate: null, heightCm: null, phone: null, platformRoles: [], availability: null, priorities: null, exclusions: null, developMuscles: [], canDoMuscles: [], difficultMuscles: [], avoidMuscles: [], status: 'ACTIVE', suspensionUntil: null, restrictionReason: null, createdAt: '2026-08-01T10:00:00.000Z', memberships: [], ...over, }; } const CREATED: User = emptyUser({ id: 'u9', email: 'nowy3@test.local', firstName: 'Nowy' }); const EDITED: User = emptyUser({ id: 'u1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski', birthDate: '1996-05-05T00:00:00.000Z', platformRoles: ['ADMIN'], memberships: [{ gymId: 'gym-a', roles: ['MEMBER'], gym: GYM_A }], }); const ROLE_ADMIN: PlatformRole = { id: 'role-admin', key: 'ADMIN', permissions: ['users:read', 'users:manage', 'pii:read', 'roles:manage', 'logs:view'], isSystem: true, grantCount: 1, }; const ADMIN_SESSION: User = { ...emptyUser({ id: 'me-1', email: 'ada@test.local', firstName: 'Ada' }), platformRoles: ['ADMIN'], permissions: [ 'users:read', 'users:manage', 'pii:read', 'roles:manage', 'catalog:manage', 'gyms:manage', 'announcements:manage', 'verifications:view', 'logs:view', ], }; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, }); } /** Mock wg fragmentu URL + metody; pierwsze pasujące (specyficzne przed ogólnymi). */ function mockRoutes(handlers: Array<{ method?: string; match: string; reply: () => unknown }>) { const calls: { url: string; init?: RequestInit }[] = []; const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { calls.push({ url, init }); const method = (init?.method ?? 'GET').toUpperCase(); const idx = handlers.findIndex( (h) => (!h.method || h.method === method) && url.includes(h.match), ); if (idx === -1) throw new Error(`No mocked route for ${method} ${url}`); return jsonResponse(200, handlers[idx].reply()); }); vi.stubGlobal('fetch', fetchMock); return calls; } function ParamId() { const { id } = useParams(); return <>{id}; } function renderForm(path: string) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); return render( } /> } /> DETAIL- } /> , ); } beforeEach(() => { setAccessToken('admin-tok'); useAuth.setState({ user: ADMIN_SESSION, ready: true }); }); afterEach(() => { vi.unstubAllGlobals(); useAuth.setState({ user: null, ready: false }); }); /** Zapis via menu kontekstowe (topbar) nie istnieje w jednostkowym renderze — * wymuszamy submit formularza dokładnie tak, jak robi to akcja „Zapisz”. * Czekamy na pełny łańcuch async (PATCH → DELETE → nawigacja). */ async function submitForm() { const form = document.querySelector('form'); if (!form) throw new Error('Brak formularza w DOM'); await act(async () => { form.requestSubmit(); // czekaj na pełny łańcuch async: PATCH konta → DELETE/PATCH członkostw → nawigacja for (let i = 0; i < 10; i++) await Promise.resolve(); }); } describe('admin UserForm — kreator tworzenia', () => { it('startuje bez siłowni (zachęta do pierwszej), a rola domyślnie niezaznaczona', async () => { mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/users', reply: () => ({ users: [] }) }, ]); const user = userEvent.setup(); renderForm('/users/new'); // stan pusty: brak wierszy, żadna rola, zachęta do dodania pierwszej siłowni expect(await screen.findByText('Jeszcze bez siłowni')).toBeInTheDocument(); expect(screen.queryByRole('checkbox', { name: /siłownia 1/ })).not.toBeInTheDocument(); await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' })); expect(screen.getByText(/wybierz rolę, aby zobaczyć/i)).toBeInTheDocument(); await user.click(screen.getByRole('checkbox', { name: 'Ćwiczący — siłownia 1' })); expect( screen.getByText('Zwykły członek siłowni — trenuje i korzysta z planów.'), ).toBeInTheDocument(); // wyjaśnienie przełącza się na rolę Właściciel (stały panel pod pigułkami) await user.click(screen.getByRole('checkbox', { name: 'Właściciel — siłownia 1' })); expect( screen.getByText('Zarządza siłownią — to uprawnienie, nie samo członkostwo.'), ).toBeInTheDocument(); }); it('tworzy użytkownika i przypisuje mu rolę w wybranej siłowni', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) }, { method: 'POST', match: '/memberships', reply: () => ({ membership: {} }) }, ]); const user = userEvent.setup(); const { container } = renderForm('/users/new'); await user.type(container.querySelector('input[type="email"]')!, 'nowy3@test.local'); await user.type(container.querySelector('input[type="password"]')!, 'Password123!'); await user.type(container.querySelectorAll('input[type="password"]')[1], 'Password123!'); // wybierz siłownię (placeholder „Szukaj siłowni…”) i zaznacz rolę Trener await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' })); const gymBox = container.querySelector('input[role="combobox"]')!; await user.click(gymBox); await user.click(await screen.findByRole('option', { name: /Steel Gym/ })); await user.click(await screen.findByRole('checkbox', { name: 'Trener — Steel Gym' })); await submitForm(); expect(await screen.findByText('DETAIL-u9')).toBeInTheDocument(); const post = calls.find( (c) => c.init?.method === 'POST' && c.url === `${API_BASE}/admin/users`, ); expect(JSON.parse(post?.init?.body as string)).toMatchObject({ email: 'nowy3@test.local', password: 'Password123!', }); // bez platformy w formularzu — zero żądań PUT o role expect(calls.some((c) => c.init?.method === 'PUT')).toBe(false); const mem = calls.find( (c) => c.init?.method === 'POST' && c.url.includes('/admin/users/u9/memberships'), ); expect(JSON.parse(mem?.init?.body as string)).toEqual({ gymId: 'gym-b', roles: ['TRAINER'], }); }); it('blokuje zapis, gdy rola jest zaznaczona bez wybranej siłowni (modal)', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) }, { method: 'POST', match: '/memberships', reply: () => ({ membership: {} }) }, ]); const user = userEvent.setup(); const { container } = renderForm('/users/new'); await user.type(container.querySelector('input[type="email"]')!, 'nowy4@test.local'); await user.type(container.querySelector('input[type="password"]')!, 'Password123!'); await user.type(container.querySelectorAll('input[type="password"]')[1], 'Password123!'); await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' })); await user.click(screen.getByRole('checkbox', { name: 'Właściciel — siłownia 1' })); await submitForm(); const dialog = await screen.findByRole('dialog'); expect(dialog).toHaveTextContent(/siłowni/); expect(dialog).toHaveTextContent(/nie można zapisać/i); // zapis zablokowany — żadne żądanie nie poszło expect(calls.filter((c) => c.init?.method === 'POST')).toHaveLength(0); }); it('blokuje zapis, gdy siłownia jest wybrana bez roli (modal)', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) }, { method: 'POST', match: '/memberships', reply: () => ({ membership: {} }) }, ]); const user = userEvent.setup(); const { container } = renderForm('/users/new'); await user.type(container.querySelector('input[type="email"]')!, 'nowy5@test.local'); await user.type(container.querySelector('input[type="password"]')!, 'Password123!'); await user.type(container.querySelectorAll('input[type="password"]')[1], 'Password123!'); await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' })); await user.click(container.querySelector('input[role="combobox"]')!); await user.click(await screen.findByRole('option', { name: /Steel Gym/ })); await submitForm(); const dialog = screen.getByRole('dialog'); expect(dialog).toHaveTextContent(/bez roli/i); expect(calls.filter((c) => c.init?.method === 'POST')).toHaveLength(0); await user.click(within(dialog).getByRole('button', { name: 'Rozumiem' })); expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); }); it('blokuje zapis, gdy powtórzone hasło różni się od hasła', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A] }) }, { method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) }, ]); const user = userEvent.setup(); const { container } = renderForm('/users/new'); const pw = container.querySelectorAll('input[type="password"]'); await user.type(container.querySelector('input[type="email"]')!, 'nowy6@test.local'); await user.type(pw[0], 'Password123!'); await user.type(pw[1], 'InneHaslo123!'); await submitForm(); expect(await screen.findByText('Podane hasła muszą być takie same.')).toBeInTheDocument(); expect(calls.filter((c) => c.init?.method === 'POST')).toHaveLength(0); }); }); describe('admin UserForm — kreator edycji', () => { it('wypełnia formularz danymi konta, rolami i członkostwami (edytor w wizardzie)', async () => { mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) }, { match: '/admin/users', reply: () => ({ users: [EDITED] }) }, ]); const { container } = renderForm('/users/u1/edit'); // dane i członkostwo wczytane z użytkownika — krok 3 jest też w edycji expect(await screen.findByDisplayValue('Jan')).toBeInTheDocument(); // z pii:read e-mail i data urodzenia są edytowalne (pełne wartości z DTO) const emailInput = container.querySelector('input[type="email"]') as HTMLInputElement; expect(emailInput.value).toBe('jan@test.local'); expect(screen.getByDisplayValue('1996-05-05')).toBeInTheDocument(); // rola platformowa z grantu jest zaznaczona const adminCheck = screen.getByRole('checkbox', { name: /Administrator/ }) as HTMLInputElement; expect(adminCheck.checked).toBe(true); expect(await screen.findByText('Członkostwa w siłowniach')).toBeInTheDocument(); expect(screen.getByDisplayValue('Fit Factory')).toBeInTheDocument(); }); it('zapis edycji bez zmian członkostw PATCHuje tylko konto', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) }, { method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) }, { match: '/admin/users', reply: () => ({ users: [EDITED] }) }, ]); const user = userEvent.setup(); renderForm('/users/u1/edit'); await screen.findByDisplayValue('Jan'); // edycja = tożsamość/dostęp: zmiana nazwiska; skłon ról bez zmian = zero żądań członkostw const inputs = document.querySelectorAll('input'); await user.clear(inputs[1]); await user.type(inputs[1], 'Nowak'); await submitForm(); expect(await screen.findByText('DETAIL-u1')).toBeInTheDocument(); const accountPatch = calls.find( (c) => c.init?.method === 'PATCH' && c.url === `${API_BASE}/admin/users/u1`, ); // z pii:read pełny e-mail i data trafiają do PATCH; role platformowe bez zmian → brak PUT expect(JSON.parse(accountPatch?.init?.body as string)).toMatchObject({ lastName: 'Nowak', email: 'jan@test.local', birthDate: '1996-05-05', }); expect(JSON.parse(String(accountPatch?.init?.body))).not.toHaveProperty('isAdmin'); expect(calls.some((c) => c.init?.method === 'PUT')).toBe(false); expect(calls.some((c) => c.url.includes('/memberships'))).toBe(false); }); it('zapis edycji PATCHuje konto i zmianę roli członkostwa', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) }, { method: 'PATCH', match: '/memberships/gym-a', reply: () => ({ membership: {} }) }, { method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) }, { match: '/admin/users', reply: () => ({ users: [EDITED] }) }, ]); const user = userEvent.setup(); renderForm('/users/u1/edit'); await screen.findByDisplayValue('Fit Factory'); // dołóż rolę Właściciel do istniejącego członkostwa (MEMBER → MEMBER + OWNER) await user.click(screen.getByRole('checkbox', { name: 'Właściciel — Fit Factory' })); await submitForm(); expect(await screen.findByText('DETAIL-u1')).toBeInTheDocument(); const accountPatch = calls.find( (c) => c.init?.method === 'PATCH' && c.url === `${API_BASE}/admin/users/u1`, ); expect(JSON.parse(accountPatch?.init?.body as string)).not.toHaveProperty('isAdmin'); expect(calls.some((c) => c.init?.method === 'PUT')).toBe(false); const memPatch = calls.find( (c) => c.init?.method === 'PATCH' && c.url.includes('/memberships/gym-a'), ); expect(JSON.parse(memPatch?.init?.body as string)).toEqual({ roles: ['MEMBER', 'OWNER'] }); }); it('zmiana ról platformowych w edycji wysyła PUT /users/:id/roles', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) }, { method: 'PUT', match: '/users/u1/roles', reply: () => ({ roles: [] }) }, { method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) }, { match: '/admin/users', reply: () => ({ users: [EDITED] }) }, ]); const user = userEvent.setup(); renderForm('/users/u1/edit'); await screen.findByDisplayValue('Jan'); // odznacz Administratora (grant usunięty w formularzu) await user.click(screen.getByRole('checkbox', { name: /Administrator/ })); await submitForm(); expect(await screen.findByText('DETAIL-u1')).toBeInTheDocument(); const rolesPut = calls.find((c) => c.init?.method === 'PUT' && c.url.includes('/roles')); expect(rolesPut).toBeDefined(); expect(JSON.parse(String(rolesPut?.init?.body))).toEqual({ roles: [] }); }); it('usunięcie wiersza członkostwa wysyła DELETE', async () => { const calls = mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/roles', reply: () => ({ roles: [ROLE_ADMIN] }) }, { method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) }, { method: 'DELETE', match: '/memberships/gym-a', reply: () => ({}) }, { match: '/admin/users', reply: () => ({ users: [EDITED] }) }, ]); const user = userEvent.setup(); renderForm('/users/u1/edit'); await screen.findByDisplayValue('Fit Factory'); await user.click(screen.getByRole('button', { name: 'Usuń Fit Factory' })); await submitForm(); const del = calls.find( (c) => c.init?.method === 'DELETE' && c.url.includes('/memberships/gym-a'), ); expect(del).toBeDefined(); }); });