diff --git a/admin/src/pages/users/UserMemberships.tsx b/admin/src/pages/users/UserMemberships.tsx
index 9eac3ab..729b625 100644
--- a/admin/src/pages/users/UserMemberships.tsx
+++ b/admin/src/pages/users/UserMemberships.tsx
@@ -1,10 +1,11 @@
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
-import { Check, Search, X } from 'lucide-react';
+import { Check } from 'lucide-react';
import { useTopbar } from '../../topbar';
import { api } from '../../api/client';
-import type { Gym, GymRole } from '../../api/types';
+import type { GymRole } from '../../api/types';
+import { GymPicker } from '../../components/GymPicker';
import {
BackButton,
Badge,
@@ -76,98 +77,6 @@ function RolePill({
);
}
-function GymPicker({
- gyms,
- value,
- onChange,
-}: {
- gyms: Gym[];
- value: string;
- onChange: (id: string) => void;
-}) {
- const [query, setQuery] = useState('');
- const [open, setOpen] = useState(false);
- const selected = gyms.find((g) => g.id === value);
- const filtered = gyms.filter((g) => g.name.toLowerCase().includes(query.trim().toLowerCase()));
-
- const close = () => {
- setOpen(false);
- setQuery('');
- };
-
- const handleBlur = (e: React.FocusEvent
) => {
- if (e.currentTarget.contains(e.relatedTarget as Node)) return;
- close();
- };
-
- return (
-
-
-
- {
- setQuery(e.target.value);
- setOpen(true);
- }}
- onFocus={() => setOpen(true)}
- />
- {selected && !open && (
-
- )}
-
- {open && (
-
- {filtered.length === 0 ? (
-
- {query.trim()
- ? `Brak siłowni o nazwie „${query.trim()}”`
- : 'Użytkownik należy już do wszystkich siłowni'}
-
- ) : (
- filtered.map((g) => (
-
- ))
- )}
-
- )}
-
- );
-}
-
/**
* Członkostwa użytkownika w siłowniach (admin): role, dodawanie i usuwanie.
* Sekcja przeniesiona ze starej strony `/users/:id`.
diff --git a/admin/test/UserForm.test.tsx b/admin/test/UserForm.test.tsx
index 2483b8f..0f72fc1 100644
--- a/admin/test/UserForm.test.tsx
+++ b/admin/test/UserForm.test.tsx
@@ -1,32 +1,73 @@
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 UserForm from '../src/pages/users/UserForm';
import { setAccessToken } from '../src/api/client';
import { API_BASE } from '../src/config';
-import type { User } from '../src/api/types';
+import type { Gym, User } from '../src/api/types';
-const U3: User = {
- id: 'u3',
- email: 'nowy3@test.local',
- firstName: 'Nowy',
- lastName: null,
- age: null,
- heightCm: null,
- phone: null,
- isAdmin: false,
+const GYM_A: Gym = {
+ id: 'gym-a',
+ name: 'Fit Factory',
+ location: 'Warszawa',
availability: null,
- priorities: null,
- exclusions: null,
- developMuscles: [],
- canDoMuscles: [],
- difficultMuscles: [],
- avoidMuscles: [],
- createdAt: '2026-08-03T10:00:00.000Z',
- memberships: [],
+ 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,
+ age: null,
+ heightCm: null,
+ phone: null,
+ isAdmin: false,
+ availability: null,
+ priorities: null,
+ exclusions: null,
+ developMuscles: [],
+ canDoMuscles: [],
+ difficultMuscles: [],
+ avoidMuscles: [],
+ 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',
+ age: 30,
+ isAdmin: true,
+ memberships: [{ gymId: 'gym-a', roles: ['MEMBER'], gym: GYM_A }],
+});
+
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
@@ -34,30 +75,46 @@ function jsonResponse(status: number, body: unknown) {
});
}
-function mockFetchSequence(...responses: Response[]) {
+/** 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 next = responses.shift();
- if (!next) throw new Error(`No more mocked responses for url: ${url}`);
- return next;
+ 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 DetailStub() {
+function ParamId() {
const { id } = useParams();
- return DETAIL-{id}
;
+ return <>{id}>;
}
-function renderForm() {
+function renderForm(path: string) {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
-
-
- } />
- } />
-
+
+
+
+ } />
+ } />
+
+ DETAIL-
+
+
+ }
+ />
+
+
,
);
}
@@ -70,23 +127,133 @@ afterEach(() => {
vi.unstubAllGlobals();
});
-describe('admin UserForm page', () => {
- it('creates a user and opens the detail page', async () => {
- const calls = mockFetchSequence(jsonResponse(201, { user: U3 }));
+describe('admin UserForm — kreator tworzenia', () => {
+ it('wyjaśnia role i pokazuje uprawnienia administratora po rozwinięciu', async () => {
+ mockRoutes([
+ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
+ { match: '/admin/users', reply: () => ({ users: [] }) },
+ ]);
const user = userEvent.setup();
- const { container } = renderForm();
- const email = container.querySelector('input[type="email"]') as HTMLInputElement;
- const password = container.querySelector('input[type="password"]') as HTMLInputElement;
- await user.type(email, 'nowy3@test.local');
- await user.type(password, 'Password123!');
+ renderForm('/users/new');
+ expect(await screen.findByRole('heading', { name: 'Nowy użytkownik' })).toBeInTheDocument();
+ // role siłowni opisane w domyślnie zaznaczonej roli (Ćwiczący)
+ expect(
+ screen.getByText('Zwykły członek siłowni — trenuje i korzysta z planów.'),
+ ).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /Pokaż uprawnienia admina/i }));
+ expect(
+ screen.getByText('Zarządzanie wszystkimi użytkownikami i siłowniami'),
+ ).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!');
+
+ // wybierz siłownię (placeholder „Szukaj siłowni…”) i dołóż rolę Trener
+ const gymBox = container.querySelector