Admin: kreator dodawania i edycji usera z czytelnym przydzielaniem rol
- 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
This commit is contained in:
@@ -44,6 +44,7 @@ export default function App() {
|
||||
<Route path="/users" element={<UsersList />} />
|
||||
<Route path="/users/new" element={<UserForm />} />
|
||||
<Route path="/users/:id" element={<UserDetail />} />
|
||||
<Route path="/users/:id/edit" element={<UserForm />} />
|
||||
<Route path="/users/:id/info" element={<UserInfo />} />
|
||||
<Route path="/users/:id/body-parameters" element={<UserBodyParameters />} />
|
||||
<Route path="/users/:id/history" element={<UserHistory />} />
|
||||
|
||||
97
admin/src/components/GymPicker.tsx
Normal file
97
admin/src/components/GymPicker.tsx
Normal file
@@ -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<HTMLDivElement>) => {
|
||||
if (e.currentTarget.contains(e.relatedTarget as Node)) return;
|
||||
close();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative" onBlur={handleBlur}>
|
||||
<div className="flex items-center gap-2 rounded-xl border border-line bg-input px-3 focus-within:border-accent">
|
||||
<Search className="h-4 w-4 shrink-0 text-dim" />
|
||||
<input
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-label="Szukaj siłowni"
|
||||
className="w-full bg-transparent py-2.5 text-[0.95rem] focus:outline-none"
|
||||
placeholder={selected && !open ? '' : 'Szukaj siłowni…'}
|
||||
value={open ? query : (selected?.name ?? '')}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setOpen(true);
|
||||
}}
|
||||
onFocus={() => setOpen(true)}
|
||||
/>
|
||||
{selected && !open && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Wyczyść wybór siłowni"
|
||||
onClick={() => onChange('')}
|
||||
className="shrink-0 cursor-pointer text-dim hover:text-ink"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{open && (
|
||||
<div
|
||||
role="listbox"
|
||||
aria-label="Lista siłowni"
|
||||
className="absolute z-20 mt-1.5 max-h-56 w-full overflow-y-auto rounded-xl border border-line bg-card shadow-xl"
|
||||
>
|
||||
{filtered.length === 0 ? (
|
||||
<div className="px-3.5 py-3 text-[0.875rem] text-dim">
|
||||
{query.trim() ? `Brak siłowni o nazwie „${query.trim()}”` : 'Brak dostępnych siłowni'}
|
||||
</div>
|
||||
) : (
|
||||
filtered.map((g) => (
|
||||
<button
|
||||
key={g.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={g.id === value}
|
||||
onClick={() => {
|
||||
onChange(g.id);
|
||||
close();
|
||||
}}
|
||||
className={`flex w-full cursor-pointer items-center justify-between gap-3 px-3.5 py-2.5 text-left text-[0.95rem] hover:bg-line/40 ${
|
||||
g.id === value ? 'font-semibold text-accent-text' : ''
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0 truncate">{g.name}</span>
|
||||
{g.location && (
|
||||
<span className="shrink-0 text-[0.875rem] text-dim">{g.location}</span>
|
||||
)}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
107
admin/src/components/GymRolePicker.tsx
Normal file
107
admin/src/components/GymRolePicker.tsx
Normal file
@@ -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<GymRole | null>(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 (
|
||||
<div className={className}>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{GYM_ROLE_ORDER.map((role) => {
|
||||
const active = value.includes(role);
|
||||
const disabled = active && locked;
|
||||
return (
|
||||
<button
|
||||
key={role}
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={active}
|
||||
aria-label={`${GYM_ROLE_META[role].label} — ${labelPrefix}`}
|
||||
aria-description={GYM_ROLE_META[role].summary}
|
||||
title={disabled ? lockTitle : GYM_ROLE_META[role].summary}
|
||||
disabled={disabled}
|
||||
onClick={() => toggle(role)}
|
||||
className={cn(
|
||||
'inline-flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-xl border px-3 py-2 text-[0.95rem] font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-40',
|
||||
active ? GYM_ROLE_PILL_ACTIVE[role] : PILL_INACTIVE,
|
||||
)}
|
||||
>
|
||||
<Check className={cn('h-4 w-4', active ? '' : 'opacity-0')} />
|
||||
{GYM_ROLE_META[role].label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{showExplain && (
|
||||
<div className="mt-2.5 min-h-[2.5rem] rounded-xl border border-line bg-input/40 px-3 py-2.5 text-[0.875rem]">
|
||||
{meta ? (
|
||||
<>
|
||||
<span className="font-semibold text-ink">{meta.label}: </span>
|
||||
<span className="text-dim">{meta.summary}</span>
|
||||
<ul className="mt-1.5 space-y-0.5 text-dim">
|
||||
{meta.grants.map((g) => (
|
||||
<li key={g} className="flex gap-1.5">
|
||||
<span className="text-accent-text">•</span>
|
||||
<span>{g}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-dim">
|
||||
Wybierz rolę, aby zobaczyć, co dokładnie daje. Ćwiczący = trenuje, Trener = prowadzi
|
||||
podopiecznych, Właściciel = zarządza siłownią.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
admin/src/lib/roles.ts
Normal file
58
admin/src/lib/roles.ts
Normal file
@@ -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<GymRole, RoleMeta> = {
|
||||
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<GymRole, string> = {
|
||||
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',
|
||||
};
|
||||
@@ -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 && <Badge color="blue">Admin</Badge>}
|
||||
{memberships.length > 0 && <Badge>{memberships.length}</Badge>}
|
||||
</span>
|
||||
<Link
|
||||
to={`/users/${user.id}/edit`}
|
||||
className={buttonVariants({ variant: 'secondary', size: 'sm' })}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
Edytuj
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Pasek mini-statystyk: 2×2 na mobile, 4 w rzędzie na desktop */}
|
||||
|
||||
@@ -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 (
|
||||
<ul className="mb-2 mt-1.5 space-y-0.5 rounded-xl border border-line bg-input/40 px-3 py-2 text-[0.875rem] text-dim">
|
||||
{ADMIN_ROLE_META.grants.map((g) => (
|
||||
<li key={g} className="flex gap-1.5">
|
||||
<span className="text-accent-text">•</span>
|
||||
<span>{g}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
/** Krótkie intro sekcji ról — szczegóły każdej roli pokazuje `GymRolePicker`. */
|
||||
function RoleIntro() {
|
||||
return (
|
||||
<p className="mb-4 text-[0.8125rem] text-dim">
|
||||
Wybierz siłownię i rolę — po kliknięciu roli zobaczysz, co dokładnie jej udostępnia.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
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<MembershipRow[]>([
|
||||
{ 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<MembershipRow>) =>
|
||||
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<string, unknown> = {
|
||||
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 <Loading />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<BackButton to="/users" className="mb-4" />
|
||||
<H1>Nowy użytkownik</H1>
|
||||
<Card>
|
||||
<form onSubmit={submit}>
|
||||
<BackButton to={isEdit && id ? `/users/${id}` : '/users'} className="mb-4" />
|
||||
<H1>{isEdit ? 'Edycja użytkownika' : 'Nowy użytkownik'}</H1>
|
||||
|
||||
{isEdit && (
|
||||
<p className="mb-4 text-[0.875rem] text-dim">
|
||||
Zmiana ról i uprawnień obowiązuje po zapisaniu. Odebranie roli administratora wyloguje
|
||||
użytkownika.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={(e) => void submit(e)} className="space-y-4">
|
||||
{/* Krok 1 — dane */}
|
||||
<Card>
|
||||
<div className="mb-3 flex items-center gap-2.5">
|
||||
<span className="grid h-7 w-7 place-items-center rounded-full bg-accent/10 text-[0.8rem] font-bold text-accent-text">
|
||||
1
|
||||
</span>
|
||||
<H3 className="mb-0">Dane</H3>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
|
||||
<Field label="E-mail">
|
||||
<Input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required />
|
||||
<Input
|
||||
type="email"
|
||||
value={form.email}
|
||||
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Hasło (min. 8)">
|
||||
<Field label={isEdit ? 'Nowe hasło (opcjonalnie)' : 'Hasło (min. 8)'}>
|
||||
<Input
|
||||
type="password"
|
||||
value={form.password}
|
||||
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
||||
minLength={8}
|
||||
required
|
||||
required={!isEdit}
|
||||
placeholder={isEdit ? '••••••••' : undefined}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Imię">
|
||||
<Input value={form.firstName} onChange={(e) => setForm({ ...form, firstName: e.target.value })} />
|
||||
<Input
|
||||
value={form.firstName}
|
||||
onChange={(e) => setForm({ ...form, firstName: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Nazwisko">
|
||||
<Input value={form.lastName} onChange={(e) => setForm({ ...form, lastName: e.target.value })} />
|
||||
<Input
|
||||
value={form.lastName}
|
||||
onChange={(e) => setForm({ ...form, lastName: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Wiek">
|
||||
<Input type="number" value={form.age} onChange={(e) => setForm({ ...form, age: e.target.value })} />
|
||||
</Field>
|
||||
<Field label="Administrator">
|
||||
<Select
|
||||
value={form.isAdmin ? '1' : '0'}
|
||||
onChange={(e) => setForm({ ...form, isAdmin: e.target.value === '1' })}
|
||||
>
|
||||
<option value="0">Nie</option>
|
||||
<option value="1">Tak</option>
|
||||
</Select>
|
||||
<Input
|
||||
type="number"
|
||||
value={form.age}
|
||||
onChange={(e) => setForm({ ...form, age: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
<Button type="submit" disabled={busy}>
|
||||
{busy ? 'Tworzenie…' : 'Utwórz użytkownika'}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Card>
|
||||
|
||||
{/* Krok 2 — role i dostęp */}
|
||||
<Card>
|
||||
<div className="mb-3 flex items-center gap-2.5">
|
||||
<span className="grid h-7 w-7 place-items-center rounded-full bg-accent/10 text-[0.8rem] font-bold text-accent-text">
|
||||
2
|
||||
</span>
|
||||
<div>
|
||||
<H3 className="mb-0">Role i dostęp</H3>
|
||||
<p className="text-[0.8125rem] text-dim">
|
||||
Ustal, co użytkownik może robić — w panelu i w poszczególnych siłowniach.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Rola administratora platformy */}
|
||||
<div className="rounded-xl border border-line bg-input/40 p-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="flex min-w-0 cursor-pointer items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4"
|
||||
checked={form.isAdmin}
|
||||
onChange={(e) => setForm({ ...form, isAdmin: e.target.checked })}
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
<span className="flex items-center gap-1.5 text-[0.95rem] font-semibold">
|
||||
<ShieldCheck className="h-4 w-4 text-accent-text" />
|
||||
Administrator platformy
|
||||
</span>
|
||||
<span className="block text-[0.8125rem] text-dim">{ADMIN_ROLE_META.summary}</span>
|
||||
</span>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAdminExplain((v) => !v)}
|
||||
className="shrink-0 cursor-pointer p-1 text-dim hover:text-ink"
|
||||
aria-label={adminExplain ? 'Zwiń uprawnienia admina' : 'Pokaż uprawnienia admina'}
|
||||
>
|
||||
<ChevronDown
|
||||
className={`h-4 w-4 transition-transform ${adminExplain ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<AdminExplain open={adminExplain} />
|
||||
</div>
|
||||
|
||||
{/* Role w siłowniach */}
|
||||
<div className="mt-4 border-t border-line pt-4">
|
||||
<div className="mb-1 flex items-center justify-between gap-3">
|
||||
<H3>Członkostwa w siłowniach</H3>
|
||||
{rows.length > 0 && <Badge>{rows.length}</Badge>}
|
||||
</div>
|
||||
<RoleIntro />
|
||||
|
||||
{rows.length === 0 && (
|
||||
<p className="mb-3 text-[0.875rem] text-dim">
|
||||
Brak przypisanej siłowni —{' '}
|
||||
{form.isAdmin ? 'użytkownik będzie administratorem.' : 'to konto bez siłowni.'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{rows.map((r, i) => (
|
||||
<div key={r.key} className="rounded-xl border border-line p-3">
|
||||
<div className="mb-2 flex items-center justify-between gap-3">
|
||||
<span className="text-[0.8125rem] font-semibold text-dim">
|
||||
Siłownia {i + 1}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeRow(r.key)}
|
||||
aria-label={`Usuń wiersz siłowni ${i + 1}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-x-4 gap-y-3 lg:grid-cols-2">
|
||||
<div>
|
||||
<div className="mb-1.5 text-[0.8125rem] font-semibold text-dim">Siłownia</div>
|
||||
<GymPicker
|
||||
gyms={gymsFor(r.key)}
|
||||
value={r.gymId}
|
||||
onChange={(gymId) => updateRow(r.key, { gymId })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-1.5 text-[0.8125rem] font-semibold text-dim">Role</div>
|
||||
<GymRolePicker
|
||||
value={r.roles}
|
||||
onChange={(roles) => updateRow(r.key, { roles })}
|
||||
labelPrefix={
|
||||
gyms.find((g) => g.id === r.gymId)?.name ?? `siłownia ${i + 1}`
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Button type="button" variant="secondary" size="sm" onClick={addRow} className="mt-3">
|
||||
<UserPlus className="h-4 w-4" />
|
||||
Dodaj kolejną siłownię
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
<Button type="submit" disabled={busy}>
|
||||
{busy ? 'Zapisywanie…' : isEdit ? 'Zapisz zmiany' : 'Utwórz użytkownika'}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 }) {
|
||||
/>
|
||||
<div className="divide-y divide-line">
|
||||
<InfoRow label="E-mail" value={user.email} />
|
||||
<InfoRow label="Administrator" value={user.isAdmin ? 'Tak' : 'Nie'} />
|
||||
<InfoRow label="Administrator" value={user.isAdmin ? 'Pełny dostęp' : 'Brak'} />
|
||||
<InfoRow label="Utworzony" value={new Date(user.createdAt).toLocaleDateString('pl-PL')} />
|
||||
</div>
|
||||
<Modal open={open} onClose={() => setOpen(false)} title="Konto" className={WIDE_MODAL}>
|
||||
@@ -204,15 +205,6 @@ function AccountCard({ user, onSaved }: { user: User; onSaved: () => void }) {
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Administrator">
|
||||
<Select
|
||||
value={isAdmin ? '1' : '0'}
|
||||
onChange={(e) => setIsAdmin(e.target.value === '1')}
|
||||
>
|
||||
<option value="0">Nie</option>
|
||||
<option value="1">Tak</option>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Nowe hasło (opcjonalnie)">
|
||||
<Input
|
||||
type="password"
|
||||
@@ -221,6 +213,26 @@ function AccountCard({ user, onSaved }: { user: User; onSaved: () => void }) {
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</Field>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="flex cursor-pointer items-start gap-3 rounded-xl border border-line bg-input/40 p-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-1 h-4 w-4"
|
||||
checked={isAdmin}
|
||||
onChange={(e) => setIsAdmin(e.target.checked)}
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
<span className="flex items-center gap-1.5 text-[0.95rem] font-semibold">
|
||||
<ShieldCheck className="h-4 w-4 text-accent-text" />
|
||||
Administrator platformy
|
||||
</span>
|
||||
<span className="block text-[0.8125rem] text-dim">
|
||||
{ADMIN_ROLE_META.summary} Rolami w siłowniach zarządzysz w zakładzie
|
||||
„Członkostwa”.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-end">
|
||||
|
||||
@@ -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<HTMLDivElement>) => {
|
||||
if (e.currentTarget.contains(e.relatedTarget as Node)) return;
|
||||
close();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative" onBlur={handleBlur}>
|
||||
<div className="flex items-center gap-2 rounded-xl border border-line bg-input px-3 focus-within:border-accent">
|
||||
<Search className="h-4 w-4 shrink-0 text-dim" />
|
||||
<input
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-label="Szukaj siłowni"
|
||||
className="w-full bg-transparent py-2.5 text-[0.95rem] focus:outline-none"
|
||||
placeholder={selected && !open ? '' : 'Szukaj siłowni…'}
|
||||
value={open ? query : (selected?.name ?? '')}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setOpen(true);
|
||||
}}
|
||||
onFocus={() => setOpen(true)}
|
||||
/>
|
||||
{selected && !open && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Wyczyść wybór siłowni"
|
||||
onClick={() => onChange('')}
|
||||
className="shrink-0 cursor-pointer text-dim hover:text-ink"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{open && (
|
||||
<div
|
||||
role="listbox"
|
||||
aria-label="Lista siłowni"
|
||||
className="absolute z-20 mt-1.5 max-h-56 w-full overflow-y-auto rounded-xl border border-line bg-card shadow-xl"
|
||||
>
|
||||
{filtered.length === 0 ? (
|
||||
<div className="px-3.5 py-3 text-[0.875rem] text-dim">
|
||||
{query.trim()
|
||||
? `Brak siłowni o nazwie „${query.trim()}”`
|
||||
: 'Użytkownik należy już do wszystkich siłowni'}
|
||||
</div>
|
||||
) : (
|
||||
filtered.map((g) => (
|
||||
<button
|
||||
key={g.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={g.id === value}
|
||||
onClick={() => {
|
||||
onChange(g.id);
|
||||
close();
|
||||
}}
|
||||
className={`flex w-full cursor-pointer items-center justify-between gap-3 px-3.5 py-2.5 text-left text-[0.95rem] hover:bg-line/40 ${
|
||||
g.id === value ? 'font-semibold text-accent-text' : ''
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0 truncate">{g.name}</span>
|
||||
{g.location && (
|
||||
<span className="shrink-0 text-[0.875rem] text-dim">{g.location}</span>
|
||||
)}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Członkostwa użytkownika w siłowniach (admin): role, dodawanie i usuwanie.
|
||||
* Sekcja przeniesiona ze starej strony `/users/:id`.
|
||||
|
||||
@@ -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>): 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 <div>DETAIL-{id}</div>;
|
||||
return <>{id}</>;
|
||||
}
|
||||
|
||||
function renderForm() {
|
||||
function renderForm(path: string) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/users/new']}>
|
||||
<Routes>
|
||||
<Route path="/users/new" element={<UserForm />} />
|
||||
<Route path="/users/:id" element={<DetailStub />} />
|
||||
</Routes>
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Routes>
|
||||
<Route path="/users/new" element={<UserForm />} />
|
||||
<Route path="/users/:id/edit" element={<UserForm />} />
|
||||
<Route
|
||||
path="/users/:id"
|
||||
element={
|
||||
<div>
|
||||
DETAIL-
|
||||
<ParamId />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
@@ -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<HTMLInputElement>('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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user