From 268671b0d84b86a70f745dc49eddec2020e0c3ed Mon Sep 17 00:00:00 2001 From: tisachi Date: Fri, 16 Oct 2026 21:25:33 +0200 Subject: [PATCH] Admin: kreator dodawania i edycji usera z czytelnym przydzielaniem rol MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Uzytkownik: wspolny kreator (UserForm) dla /users/new i /users/:id/edit — krok Dane + krok Role i dostep - Role silowi (Cwiczacy/Trener/Wlasciciel) z widocznym wyjaśnieniem co daja (GymRolePicker), przy tworzeniu od razu tworzone czlonkostwa - Administrator: suwak zamiast Suchego Tak/Nie, z opisem uprawnien (AccountCard w UserInfo) - Wyodrebnione GymPicker i modul lib/roles.ts (opisy rol); wyczyszczone opisy w e2e (listitem/H1) Testy: 72 unit + 12 e2e admin zielone --- admin/src/App.tsx | 1 + admin/src/components/GymPicker.tsx | 97 ++++++ admin/src/components/GymRolePicker.tsx | 107 ++++++ admin/src/lib/roles.ts | 58 ++++ admin/src/pages/users/UserDetail.tsx | 9 + admin/src/pages/users/UserForm.tsx | 386 +++++++++++++++++++--- admin/src/pages/users/UserInfo.tsx | 34 +- admin/src/pages/users/UserMemberships.tsx | 97 +----- admin/test/UserForm.test.tsx | 249 +++++++++++--- admin/test/e2e/admin.spec.ts | 35 +- 10 files changed, 882 insertions(+), 191 deletions(-) create mode 100644 admin/src/components/GymPicker.tsx create mode 100644 admin/src/components/GymRolePicker.tsx create mode 100644 admin/src/lib/roles.ts diff --git a/admin/src/App.tsx b/admin/src/App.tsx index 7b144c5..672c9ac 100644 --- a/admin/src/App.tsx +++ b/admin/src/App.tsx @@ -44,6 +44,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/admin/src/components/GymPicker.tsx b/admin/src/components/GymPicker.tsx new file mode 100644 index 0000000..273655b --- /dev/null +++ b/admin/src/components/GymPicker.tsx @@ -0,0 +1,97 @@ +import { useState } from 'react'; +import { Search, X } from 'lucide-react'; +import type { Gym } from '../api/types'; + +/** + * Wyszukiwarka siłowni (combobox) — wybór jednej siłowni z listy. + * Wykorzystywana w kreatorze użytkownika i na stronie członkostw. + */ +export 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()}”` : 'Brak dostępnych siłowni'} +
+ ) : ( + filtered.map((g) => ( + + )) + )} +
+ )} +
+ ); +} diff --git a/admin/src/components/GymRolePicker.tsx b/admin/src/components/GymRolePicker.tsx new file mode 100644 index 0000000..9df48a0 --- /dev/null +++ b/admin/src/components/GymRolePicker.tsx @@ -0,0 +1,107 @@ +import { useState } from 'react'; +import { Check } from 'lucide-react'; +import type { GymRole } from '../api/types'; +import { GYM_ROLE_META, GYM_ROLE_ORDER, GYM_ROLE_PILL_ACTIVE } from '../lib/roles'; +import { cn } from '../lib/utils'; + +const PILL_INACTIVE = 'bg-transparent text-dim border-line hover:text-ink hover:border-dim'; + +interface GymRolePickerProps { + value: GymRole[]; + onChange: (roles: GymRole[]) => void; + /** Przedrostek aria-label pigułek (np. nazwa siłowni lub „Dodaj”), do testów i A11y. */ + labelPrefix: string; + /** Uniemożliwia odznaczenie, gdy została tylko `minRoles` (domyślnie 1). */ + minRoles?: number; + /** Tytuł blokady ostatniej roli (title na zablokowanej pigułce). */ + lockTitle?: string; + /** Pod pigułkami pokazuje wyjaśnienie wskazanej/ostatnio wybranej roli. Domyślnie true. */ + showExplain?: boolean; + className?: string; +} + +/** + * Wybór ról siłowni (Właściciel / Trener / Ćwiczący) z widocznym wyjaśnieniem, + * co daje każda z nich — żeby przydzielanie nie było zgadywanką. + */ +export function GymRolePicker({ + value, + onChange, + labelPrefix, + minRoles = 1, + lockTitle, + showExplain = true, + className, +}: GymRolePickerProps) { + const [explained, setExplained] = useState(null); + const locked = value.length <= minRoles; + + const toggle = (role: GymRole) => { + setExplained(role); + if (value.includes(role)) { + if (locked) return; + onChange(value.filter((r) => r !== role)); + } else { + onChange([...value, role]); + } + }; + + const shown = + explained ?? + (value.length > 0 ? (GYM_ROLE_ORDER.find((r) => value.includes(r)) ?? null) : null); + const meta = shown ? GYM_ROLE_META[shown] : null; + + return ( +
+
+ {GYM_ROLE_ORDER.map((role) => { + const active = value.includes(role); + const disabled = active && locked; + return ( + + ); + })} +
+ {showExplain && ( +
+ {meta ? ( + <> + {meta.label}: + {meta.summary} +
    + {meta.grants.map((g) => ( +
  • + • + {g} +
  • + ))} +
+ + ) : ( + + Wybierz rolę, aby zobaczyć, co dokładnie daje. Ćwiczący = trenuje, Trener = prowadzi + podopiecznych, Właściciel = zarządza siłownią. + + )} +
+ )} +
+ ); +} diff --git a/admin/src/lib/roles.ts b/admin/src/lib/roles.ts new file mode 100644 index 0000000..67824a1 --- /dev/null +++ b/admin/src/lib/roles.ts @@ -0,0 +1,58 @@ +import type { GymRole } from '../api/types'; + +/** Opis roli — używany wszędzie tam, gdzie admin przydziela rolę, żeby wybór był oczywisty. */ +export interface RoleMeta { + /** Etykieta ról (pigułka / nagłówek). */ + label: string; + /** Czym rola jest — jedno zdanie widoczne przy wyborze. */ + summary: string; + /** Co dokładnie daje — konkrety do wyświetlenia w wyjaśnieniu. */ + grants: string[]; +} + +/** Kolejność ról siłowni w interfejsie: od najniższej do najważniejszej. */ +export const GYM_ROLE_ORDER: GymRole[] = ['MEMBER', 'TRAINER', 'OWNER']; + +export const GYM_ROLE_META: Record = { + MEMBER: { + label: 'Ćwiczący', + summary: 'Zwykły członek siłowni — trenuje i korzysta z planów.', + grants: ['Tworzenie planów i prowadzenie treningów', 'Dostęp do feedu i statystyk siłowni'], + }, + TRAINER: { + label: 'Trener', + summary: 'Prowadzi podopiecznych i układa im plany treningowe.', + grants: [ + 'Zapraszanie podopiecznych i opieka nad nimi', + 'Tworzenie i edycja ich planów', + 'Wgląd w postępy podopiecznych', + ], + }, + OWNER: { + label: 'Właściciel', + summary: 'Pełne zarządzanie daną siłownią.', + grants: [ + 'Dane, godziny i adres siłowni', + 'Sprzęt, zdjęcia i grafik', + 'Zapraszanie ludzi i nadawanie im ról', + ], + }, +}; + +/** Rola administratora platformy (poza systemem ról siłowni). */ +export const ADMIN_ROLE_META: RoleMeta = { + label: 'Administrator', + summary: 'Dostęp do całego panelu administratora FitOS.', + grants: [ + 'Zarządzanie wszystkimi użytkownikami i siłowniami', + 'Weryfikacja zgłoszeń siłowni', + 'Katalogi, komunikaty i logi systemowe', + ], +}; + +/** Tona koloru pigułki aktywnej roli — spójna z `UserMemberships`. */ +export const GYM_ROLE_PILL_ACTIVE: Record = { + OWNER: 'bg-accent/15 text-accent-text border-accent/40', + TRAINER: 'bg-info/15 text-info border-info/40', + MEMBER: 'bg-dim/20 text-ink border-dim/50', +}; diff --git a/admin/src/pages/users/UserDetail.tsx b/admin/src/pages/users/UserDetail.tsx index 2fdd603..f084321 100644 --- a/admin/src/pages/users/UserDetail.tsx +++ b/admin/src/pages/users/UserDetail.tsx @@ -6,6 +6,7 @@ import { FileText, Flame, History, + Pencil, Scale, TrendingUp, User, @@ -15,6 +16,7 @@ import { import { useTopbar } from '../../topbar'; import { api } from '../../api/client'; import { Badge, Button, Card, ErrorText, Loading } from '../../components/ui'; +import { buttonVariants } from '../../components/ui/button'; import { Avatar } from '../../components/Avatar'; import { displayName, fmtDate, fmtVolume } from '../../lib/format'; import { @@ -199,6 +201,13 @@ export default function UserDetail() { {user.isAdmin && Admin} {memberships.length > 0 && {memberships.length}} + + + Edytuj + {/* Pasek mini-statystyk: 2×2 na mobile, 4 w rzędzie na desktop */} diff --git a/admin/src/pages/users/UserForm.tsx b/admin/src/pages/users/UserForm.tsx index f54c23c..20fd42c 100644 --- a/admin/src/pages/users/UserForm.tsx +++ b/admin/src/pages/users/UserForm.tsx @@ -1,12 +1,76 @@ -import { useState } from 'react'; -import { useNavigate } from 'react-router-dom'; +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useNavigate, useParams } from 'react-router-dom'; +import { ChevronDown, ShieldCheck, Trash2, UserPlus } from 'lucide-react'; import { api } from '../../api/client'; -import { BackButton, Button, Card, ErrorText, Field, H1, Input, Select } from '../../components/ui'; +import type { Gym, GymRole, User } from '../../api/types'; +import { ADMIN_ROLE_META } from '../../lib/roles'; +import { GymPicker } from '../../components/GymPicker'; +import { GymRolePicker } from '../../components/GymRolePicker'; +import { + BackButton, + Badge, + Button, + Card, + ErrorText, + Field, + H1, + H3, + Input, + Loading, +} from '../../components/ui'; import { useTopbar } from '../../topbar'; +import { useAdminUser, useUserGyms } from './user-queries'; + +/** Wiersz członkostwa w formularzu: tymczasowy klucz + wybrana siłownia + role. */ +interface MembershipRow { + key: number; + gymId: string; + roles: GymRole[]; + /** true = członkostwo istniało już w edycji (zmiana ról → PATCH), false = nowe (POST). */ + existing: boolean; +} + +let rowSeq = 0; +const nextKey = () => ++rowSeq; + +/** Wyjaśnienie roli administratora — rozwijane, żeby nie zaśmiecać formularza. */ +function AdminExplain({ open }: { open: boolean }) { + if (!open) return null; + return ( +
    + {ADMIN_ROLE_META.grants.map((g) => ( +
  • + • + {g} +
  • + ))} +
+ ); +} + +/** Krótkie intro sekcji ról — szczegóły każdej roli pokazuje `GymRolePicker`. */ +function RoleIntro() { + return ( +

+ Wybierz siłownię i rolę — po kliknięciu roli zobaczysz, co dokładnie jej udostępnia. +

+ ); +} export default function UserForm() { - useTopbar({ title: 'Użytkownicy', back: '/users' }); + const { id } = useParams(); + const isEdit = Boolean(id); const navigate = useNavigate(); + const { user, isLoading } = useAdminUser(id); + const { data: gymsData } = useUserGyms(); + + useTopbar({ + title: 'Użytkownicy', + back: isEdit && id ? `/users/${id}` : '/users', + }); + + const gyms: Gym[] = gymsData?.gyms ?? []; + const [form, setForm] = useState({ email: '', password: '', @@ -15,26 +79,132 @@ export default function UserForm() { age: '', isAdmin: false, }); + const [adminExplain, setAdminExplain] = useState(false); + const [rows, setRows] = useState([ + { key: nextKey(), gymId: '', roles: ['MEMBER'], existing: false }, + ]); const [error, setError] = useState(''); const [busy, setBusy] = useState(false); + // W edycji: wypełnij formularz danymi użytkownika (raz, po załadowaniu). + const seededRef = useRef(false); + useEffect(() => { + if (seededRef.current || !user) return; + seededRef.current = true; + setForm({ + email: user.email, + password: '', + firstName: user.firstName ?? '', + lastName: user.lastName ?? '', + age: user.age?.toString() ?? '', + isAdmin: user.isAdmin, + }); + setRows( + (user.memberships ?? []).map((m) => ({ + key: nextKey(), + gymId: m.gymId, + roles: m.roles, + existing: true, + })), + ); + }, [user]); + + // siłownie niedostępne w pozostałych wierszach (bez duplikatów w jednym formularzu) + const gymsFor = (rowKey: number): Gym[] => { + const taken = new Set(rows.filter((r) => r.key !== rowKey && r.gymId).map((r) => r.gymId)); + return gyms.filter((g) => !taken.has(g.id)); + }; + + const updateRow = (key: number, patch: Partial) => + setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch } : r))); + const removeRow = (key: number) => setRows((rs) => rs.filter((r) => r.key !== key)); + const addRow = () => + setRows((rs) => [...rs, { key: nextKey(), gymId: '', roles: ['MEMBER'], existing: false }]); + + // w edycji: siłownie usunięte względem stanu wyjściowego → DELETE + const removedGymIds = useMemo(() => { + if (!isEdit || !user) return [] as string[]; + const currentIds = new Set(rows.filter((r) => r.gymId).map((r) => r.gymId)); + return (user.memberships ?? []).map((m) => m.gymId).filter((gid) => !currentIds.has(gid)); + }, [rows, user, isEdit]); + + const validate = (): string => { + const chosen = rows.filter((r) => r.gymId); + if (!isEdit && !form.email.trim()) return 'Podaj adres e-mail.'; + if (!isEdit && form.password.length < 8) return 'Hasło musi mieć co najmniej 8 znaków.'; + if (isEdit && form.password && form.password.length < 8) + return 'Nowe hasło musi mieć co najmniej 8 znaków.'; + if (chosen.some((r) => r.roles.length === 0)) + return 'Każda siłownia musi mieć co najmniej jedną rolę.'; + return ''; + }; + const submit = async (e: React.FormEvent) => { e.preventDefault(); + const validation = validate(); + if (validation) { + setError(validation); + return; + } setError(''); setBusy(true); try { - const data = await api<{ user: { id: string } }>('/admin/users', { - method: 'POST', - body: { - email: form.email, - password: form.password, - firstName: form.firstName || undefined, - lastName: form.lastName || undefined, - age: form.age ? parseInt(form.age) : undefined, - isAdmin: form.isAdmin, - }, - }); - navigate(`/users/${data.user.id}`); + const chosen = rows.filter((r) => r.gymId); + if (!isEdit) { + const data = await api<{ user: User }>('/admin/users', { + method: 'POST', + body: { + email: form.email.trim(), + password: form.password, + firstName: form.firstName || undefined, + lastName: form.lastName || undefined, + age: form.age ? parseInt(form.age) : undefined, + isAdmin: form.isAdmin, + }, + }); + const createdId = data.user.id; + for (const r of chosen) { + await api(`/admin/users/${createdId}/memberships`, { + method: 'POST', + body: { gymId: r.gymId, roles: r.roles }, + }); + } + navigate(`/users/${createdId}`); + return; + } + + // EDYCJA: PATCH konta (tylko zmienione pola), potem porządkowanie członkostw + const patchBody: Record = { + email: form.email.trim(), + firstName: form.firstName || null, + lastName: form.lastName || null, + age: form.age ? parseInt(form.age) : null, + isAdmin: form.isAdmin, + }; + if (form.password) patchBody.password = form.password; + await api(`/admin/users/${id}`, { method: 'PATCH', body: patchBody }); + + for (const gid of removedGymIds) { + await api(`/admin/users/${id}/memberships/${gid}`, { method: 'DELETE' }); + } + for (const r of chosen) { + const original = user?.memberships?.find((m) => m.gymId === r.gymId); + if (!original || !r.existing) { + await api(`/admin/users/${id}/memberships`, { + method: 'POST', + body: { gymId: r.gymId, roles: r.roles }, + }); + } else if ( + original.roles.length !== r.roles.length || + original.roles.some((x) => !r.roles.includes(x)) + ) { + await api(`/admin/users/${id}/memberships/${r.gymId}`, { + method: 'PATCH', + body: { roles: r.roles }, + }); + } + } + navigate(`/users/${id}`); } catch (err) { setError(err instanceof Error ? err.message : 'Błąd'); } finally { @@ -42,50 +212,184 @@ export default function UserForm() { } }; + if (isEdit && (isLoading || !user)) return ; + return ( <> - -

Nowy użytkownik

- -
+ +

{isEdit ? 'Edycja użytkownika' : 'Nowy użytkownik'}

+ + {isEdit && ( +

+ Zmiana ról i uprawnień obowiązuje po zapisaniu. Odebranie roli administratora wyloguje + użytkownika. +

+ )} + + void submit(e)} className="space-y-4"> + {/* Krok 1 — dane */} + +
+ + 1 + +

Dane

+
- setForm({ ...form, email: e.target.value })} required /> + setForm({ ...form, email: e.target.value })} + required + /> - + setForm({ ...form, password: e.target.value })} minLength={8} - required + required={!isEdit} + placeholder={isEdit ? '••••••••' : undefined} /> - setForm({ ...form, firstName: e.target.value })} /> + setForm({ ...form, firstName: e.target.value })} + /> - setForm({ ...form, lastName: e.target.value })} /> + setForm({ ...form, lastName: e.target.value })} + /> - setForm({ ...form, age: e.target.value })} /> - - - + setForm({ ...form, age: e.target.value })} + />
- {error && {error}} - - -
+
+ + {/* Krok 2 — role i dostęp */} + +
+ + 2 + +
+

Role i dostęp

+

+ Ustal, co użytkownik może robić — w panelu i w poszczególnych siłowniach. +

+
+
+ + {/* Rola administratora platformy */} +
+
+ + +
+ +
+ + {/* Role w siłowniach */} +
+
+

Członkostwa w siłowniach

+ {rows.length > 0 && {rows.length}} +
+ + + {rows.length === 0 && ( +

+ Brak przypisanej siłowni —{' '} + {form.isAdmin ? 'użytkownik będzie administratorem.' : 'to konto bez siłowni.'} +

+ )} + +
+ {rows.map((r, i) => ( +
+
+ + Siłownia {i + 1} + + +
+
+
+
Siłownia
+ updateRow(r.key, { gymId })} + /> +
+
+
Role
+ updateRow(r.key, { roles })} + labelPrefix={ + gyms.find((g) => g.id === r.gymId)?.name ?? `siłownia ${i + 1}` + } + /> +
+
+
+ ))} +
+ + +
+
+ + {error && {error}} + + ); } diff --git a/admin/src/pages/users/UserInfo.tsx b/admin/src/pages/users/UserInfo.tsx index 5912fd4..3665061 100644 --- a/admin/src/pages/users/UserInfo.tsx +++ b/admin/src/pages/users/UserInfo.tsx @@ -1,9 +1,10 @@ import { useEffect, useRef, useState } from 'react'; import { useParams } from 'react-router-dom'; import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { Check, Pencil, Plus, Search, Trash2 } from 'lucide-react'; +import { Check, Pencil, Plus, Search, ShieldCheck, Trash2 } from 'lucide-react'; import { useTopbar } from '../../topbar'; import { api } from '../../api/client'; +import { ADMIN_ROLE_META } from '../../lib/roles'; import type { Availability, FocusArea, @@ -190,7 +191,7 @@ function AccountCard({ user, onSaved }: { user: User; onSaved: () => void }) { />
- +
setOpen(false)} title="Konto" className={WIDE_MODAL}> @@ -204,15 +205,6 @@ function AccountCard({ user, onSaved }: { user: User; onSaved: () => void }) { required /> - - - void }) { placeholder="••••••••" /> +
+ +
{error && {error}}
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('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 user.click(screen.getByRole('button', { name: 'Utwórz użytkownika' })); - expect(await screen.findByText('DETAIL-u3')).toBeInTheDocument(); - const post = calls.find((c) => c.init?.method === 'POST'); - expect(post?.url).toBe(`${API_BASE}/admin/users`); + + 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!', isAdmin: 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: ['MEMBER', 'TRAINER'], + }); + }); + + it('blokuje ostatnią rolę w wierszu (nie da się odznaczyć jedynej)', async () => { + mockRoutes([ + { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A] }) }, + { match: '/admin/users', reply: () => ({ users: [] }) }, + ]); + renderForm('/users/new'); + const member = await screen.findByRole('checkbox', { name: 'Ćwiczący — siłownia 1' }); + expect(member).toBeChecked(); + expect(member).toBeDisabled(); + }); +}); + +describe('admin UserForm — kreator edycji', () => { + it('wypełnia formularz danymi użytkownika i jego członkostwami', async () => { + mockRoutes([ + { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, + { match: '/admin/users', reply: () => ({ users: [EDITED] }) }, + ]); + renderForm('/users/u1/edit'); + expect(await screen.findByRole('heading', { name: 'Edycja użytkownika' })).toBeInTheDocument(); + // dane i członkostwo wczytane z użytkownika + expect(await screen.findByDisplayValue('jan@test.local')).toBeInTheDocument(); + expect(await screen.findByDisplayValue('Jan')).toBeInTheDocument(); + expect(screen.getByDisplayValue('Fit Factory')).toBeInTheDocument(); + }); + + it('zapis edycji PATCHuje konto i zmianę roli członkostwa', async () => { + const calls = mockRoutes([ + { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, + { 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 user.click(screen.getByRole('button', { name: 'Zapisz zmiany' })); + + 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)).toMatchObject({ isAdmin: true }); + 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('usunięcie wiersza członkostwa wysyła DELETE', async () => { + const calls = mockRoutes([ + { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, + { method: 'PATCH', match: '/memberships/gym-a', reply: () => ({ membership: {} }) }, + { 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ń wiersz siłowni 1' })); + await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' })); + + const del = calls.find( + (c) => c.init?.method === 'DELETE' && c.url.includes('/memberships/gym-a'), + ); + expect(del).toBeDefined(); }); }); diff --git a/admin/test/e2e/admin.spec.ts b/admin/test/e2e/admin.spec.ts index ec53bdf..779eb4a 100644 --- a/admin/test/e2e/admin.spec.ts +++ b/admin/test/e2e/admin.spec.ts @@ -50,8 +50,8 @@ test('admin zarządza właścicielami siłowni z menu kontekstowego', async ({ p await expect(dialog.getByText('Anna Kowalska')).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', + const addReq = page.waitForRequest( + (req) => req.url().includes('/admin/gyms/gym-1/owners') && req.method() === 'POST', ); await dialog.getByRole('combobox', { name: 'Szukaj przyszłego właściciela' }).fill('jan'); await page.getByRole('option', { name: /Jan Kowalski/ }).click(); @@ -60,8 +60,8 @@ test('admin zarządza właścicielami siłowni z menu kontekstowego', async ({ p await expect(dialog.getByText('Jan Kowalski')).toBeVisible(); // odebranie roli = DELETE /admin/gyms/gym-1/owners/:userId - const delReq = page.waitForRequest((req) => - req.url().includes('/admin/gyms/gym-1/owners/user-owner') && req.method() === 'DELETE', + const delReq = page.waitForRequest( + (req) => req.url().includes('/admin/gyms/gym-1/owners/user-owner') && req.method() === 'DELETE', ); await dialog.getByRole('button', { name: 'Odbierz rolę' }).first().click(); await delReq; @@ -174,6 +174,33 @@ test('karta konta pozwala zmienić e-mail (PATCH /admin/users/:id)', async ({ pa expect(req.postDataJSON()).toMatchObject({ email: 'nowy@fitos.pl' }); }); +test('kreator edycji użytkownika: wyjaśnia role i zapisuje zmianę roli PATCHem', async ({ + page, +}) => { + mockApi(page, { gyms: { gyms: [TEST_GYM, TEST_GYM_2] }, users: { users: [TEST_USER] } }); + await loginAsAdmin(page); + await page.getByRole('link', { name: 'Użytkownicy' }).click(); + await page.getByRole('link', { name: 'Jan Kowalski' }).click(); + await page.getByRole('link', { name: 'Edytuj' }).click(); + await expect(page).toHaveURL(/\/users\/user-1\/edit$/); + await expect(page.getByRole('heading', { name: 'Edycja użytkownika' })).toBeVisible(); + // dane i istniejące członkostwo wczytane + await expect(page.locator('input[type="email"]')).toHaveValue('jan@fitos.pl'); + await expect(page.locator('input[role="combobox"]')).toHaveValue('Fit Factory'); + // wyjaśnienie roli widoczne bez klikania + await expect(page.getByText(/Zwykły członek siłowni/)).toBeVisible(); + + // dołóż rolę Trener do istniejącego członkostwa i zapisz + const patchPromise = page.waitForRequest( + (req) => + req.method() === 'PATCH' && req.url().endsWith('/admin/users/user-1/memberships/gym-1'), + ); + await page.getByRole('checkbox', { name: 'Trener — Fit Factory' }).click(); + await page.getByRole('button', { name: 'Zapisz zmiany' }).click(); + const req = await patchPromise; + expect(req.postDataJSON()).toEqual({ roles: ['MEMBER', 'TRAINER'] }); +}); + test('przycisk w prawym górnym rogu prowadzi do formularza dodawania', async ({ page }) => { mockApi(page); await loginAsAdmin(page);