Admin: edytor czlonkostw w wizardzie (edycja = diff POST/PATCH/DELETE), strona Czlonkostwa read-only
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { Building2, Check, ChevronDown, ShieldCheck, Trash2, UserPlus } from 'lucide-react';
|
||||
import { api } from '../../api/client';
|
||||
@@ -27,6 +27,8 @@ 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;
|
||||
@@ -48,9 +50,10 @@ function AdminExplain({ open }: { open: boolean }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Kreator tworzenia/edycji użytkownika.
|
||||
* Tworzenie: dane + role + członkostwa (krok 3). Edycja: wyłącznie konto
|
||||
* (tożsamość/dostęp) — członkostwa zarządza się na stronie „Członkostwa w siłowniach".
|
||||
* Kreator tworzenia/edycji użytkownika — jedyne miejsce edycji (także członkostw).
|
||||
* Tworzenie: dane + role + członkostwa (POST-y po utworzeniu konta).
|
||||
* Edycja: PATCH konta + porządkowanie członkostw (POST/PATCH/DELETE wg zmian w kroku 3);
|
||||
* strona „Członkostwa w siłowniach" jest tylko do odczytu.
|
||||
*/
|
||||
export default function UserForm() {
|
||||
const { id } = useParams();
|
||||
@@ -118,6 +121,14 @@ export default function UserForm() {
|
||||
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)
|
||||
@@ -129,7 +140,15 @@ export default function UserForm() {
|
||||
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: [] }]);
|
||||
const addRow = () =>
|
||||
setRows((rs) => [...rs, { key: nextKey(), gymId: '', roles: [], 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 => {
|
||||
if (!isEdit && !form.email.trim()) return 'Podaj adres e-mail.';
|
||||
@@ -163,12 +182,10 @@ export default function UserForm() {
|
||||
setError(validation);
|
||||
return;
|
||||
}
|
||||
if (!isEdit) {
|
||||
const rowsProblem = validateRows();
|
||||
if (rowsProblem) {
|
||||
setRowError(rowsProblem);
|
||||
return;
|
||||
}
|
||||
const rowsProblem = validateRows();
|
||||
if (rowsProblem) {
|
||||
setRowError(rowsProblem);
|
||||
return;
|
||||
}
|
||||
setError('');
|
||||
setBusy(true);
|
||||
@@ -202,7 +219,7 @@ export default function UserForm() {
|
||||
return;
|
||||
}
|
||||
|
||||
// EDYCJA: PATCH konta (tożsamość/dostęp) — członkostwa poza wizardem
|
||||
// EDYCJA: PATCH konta (tożsamość/dostęp), potem porządkowanie członkostw
|
||||
const patchBody: Record<string, unknown> = {
|
||||
email: form.email.trim(),
|
||||
firstName: form.firstName || null,
|
||||
@@ -212,6 +229,27 @@ export default function UserForm() {
|
||||
};
|
||||
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 rows.filter((x) => x.gymId)) {
|
||||
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');
|
||||
@@ -333,92 +371,78 @@ export default function UserForm() {
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Krok 3 — członkostwa w siłowniach (tylko tworzenie; edycja = strona członkostw) */}
|
||||
{!isEdit && (
|
||||
<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">
|
||||
3
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 items-center justify-between gap-3">
|
||||
<H3 className="mb-0">Członkostwa w siłowniach</H3>
|
||||
{filledCount > 0 && <Badge>{filledCount}</Badge>}
|
||||
</div>
|
||||
{/* Krok 3 — członkostwa w siłowniach (edytor: tworzenie POST, edycja POST/PATCH/DELETE) */}
|
||||
<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">
|
||||
3
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 items-center justify-between gap-3">
|
||||
<H3 className="mb-0">Członkostwa w siłowniach</H3>
|
||||
{filledCount > 0 && <Badge>{filledCount}</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{rows.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-line px-4 py-8 text-center">
|
||||
<Building2 className="mx-auto h-7 w-7 text-dim" aria-hidden />
|
||||
<p className="mt-2 text-[0.95rem] font-semibold">Jeszcze bez siłowni</p>
|
||||
<p className="mx-auto mt-1 max-w-md text-[0.875rem] text-dim">
|
||||
Dodaj pierwszą siłownię i zaznacz rolę — albo zdecyduj później, na stronie
|
||||
„Członkostwa w siłowniach” użytkownika.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={addRow}
|
||||
className="mt-4"
|
||||
>
|
||||
<UserPlus className="h-4 w-4" />
|
||||
Dodaj pierwszą siłownię
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
{rows.map((r, i) => {
|
||||
const gym = gyms.find((g) => g.id === r.gymId);
|
||||
return (
|
||||
<div key={r.key} className="space-y-4 rounded-xl border border-line p-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeRow(r.key)}
|
||||
aria-label={gym ? `Usuń ${gym.name}` : `Usuń siłownię ${i + 1}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Siłownia</Label>
|
||||
<GymPicker
|
||||
gyms={gymsFor(r.key)}
|
||||
value={r.gymId}
|
||||
onChange={(gymId) => updateRow(r.key, { gymId })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Role</Label>
|
||||
<GymRolePicker
|
||||
value={r.roles}
|
||||
onChange={(roles) => updateRow(r.key, { roles })}
|
||||
labelPrefix={gym?.name ?? `siłownia ${i + 1}`}
|
||||
minRoles={0}
|
||||
/>
|
||||
</div>
|
||||
{rows.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-line px-4 py-8 text-center">
|
||||
<Building2 className="mx-auto h-7 w-7 text-dim" aria-hidden />
|
||||
<p className="mt-2 text-[0.95rem] font-semibold">Jeszcze bez siłowni</p>
|
||||
<p className="mx-auto mt-1 max-w-md text-[0.875rem] text-dim">
|
||||
Dodaj pierwszą siłownię i zaznacz rolę — członkostwa nadajesz i zmieniasz tylko
|
||||
tutaj.
|
||||
</p>
|
||||
<Button type="button" variant="secondary" size="sm" onClick={addRow} className="mt-4">
|
||||
<UserPlus className="h-4 w-4" />
|
||||
Dodaj pierwszą siłownię
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
{rows.map((r, i) => {
|
||||
const gym = gyms.find((g) => g.id === r.gymId);
|
||||
return (
|
||||
<div key={r.key} className="space-y-4 rounded-xl border border-line p-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeRow(r.key)}
|
||||
aria-label={gym ? `Usuń ${gym.name}` : `Usuń siłownię ${i + 1}`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div>
|
||||
<Label>Siłownia</Label>
|
||||
<GymPicker
|
||||
gyms={gymsFor(r.key)}
|
||||
value={r.gymId}
|
||||
onChange={(gymId) => updateRow(r.key, { gymId })}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Role</Label>
|
||||
<GymRolePicker
|
||||
value={r.roles}
|
||||
onChange={(roles) => updateRow(r.key, { roles })}
|
||||
labelPrefix={gym?.name ?? `siłownia ${i + 1}`}
|
||||
minRoles={0}
|
||||
/>
|
||||
</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>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
<Button type="button" variant="secondary" size="sm" onClick={addRow} className="mt-3">
|
||||
<UserPlus className="h-4 w-4" />
|
||||
Dodaj kolejną siłownię
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
</form>
|
||||
|
||||
@@ -1,173 +1,30 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Check, Plus } from 'lucide-react';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { api } from '../../api/client';
|
||||
import type { GymRole } from '../../api/types';
|
||||
import { GymPicker } from '../../components/GymPicker';
|
||||
import { GYM_ROLE_META } from '../../lib/roles';
|
||||
import {
|
||||
BackButton,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
ConfirmDialog,
|
||||
ErrorText,
|
||||
Label,
|
||||
ListRow,
|
||||
Modal,
|
||||
Muted,
|
||||
PageHeader,
|
||||
SectionHeader,
|
||||
Skeleton,
|
||||
} from '../../components/ui';
|
||||
import { useAdminUser, useUserGyms } from './user-queries';
|
||||
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
OWNER: 'Właściciel',
|
||||
TRAINER: 'Trener',
|
||||
MEMBER: 'Ćwiczący',
|
||||
};
|
||||
|
||||
const ROLE_OPTIONS: Array<{ value: 'OWNER' | 'TRAINER' | 'MEMBER'; label: string }> = [
|
||||
{ value: 'MEMBER', label: 'Ćwiczący' },
|
||||
{ value: 'TRAINER', label: 'Trener' },
|
||||
{ value: 'OWNER', label: 'Właściciel' },
|
||||
];
|
||||
|
||||
const ROLE_PILL_ACTIVE: Record<string, 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',
|
||||
};
|
||||
|
||||
const ROLE_PILL_INACTIVE = 'bg-transparent text-dim border-line hover:text-ink hover:border-dim';
|
||||
|
||||
function RolePill({
|
||||
value,
|
||||
active,
|
||||
onToggle,
|
||||
ariaLabel,
|
||||
className = '',
|
||||
disabled = false,
|
||||
title,
|
||||
}: {
|
||||
value: GymRole;
|
||||
active: boolean;
|
||||
onToggle: () => void;
|
||||
ariaLabel: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
title?: string;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={active}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
title={title}
|
||||
onClick={onToggle}
|
||||
className={`inline-flex items-center justify-center gap-2 rounded-xl border px-3 py-2 text-[0.95rem] font-semibold cursor-pointer transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
|
||||
active ? ROLE_PILL_ACTIVE[value] : ROLE_PILL_INACTIVE
|
||||
} ${className}`.trim()}
|
||||
>
|
||||
<Check className={`h-4 w-4 ${active ? '' : 'opacity-0'}`} />
|
||||
{ROLE_LABELS[value]}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
import { useAdminUser } from './user-queries';
|
||||
|
||||
/**
|
||||
* Członkostwa użytkownika w siłowniach (admin): jedyne miejsce edycji członkostw
|
||||
* (role natychmiast, usuwanie przez potwierdzenie, dodawanie z menu kontekstowego).
|
||||
* Członkostwa użytkownika w siłowniach (admin): tylko do odczytu.
|
||||
* Edycja członkostw istnieje wyłącznie w edytorze (wizard „Nowy/Edycja
|
||||
* użytkownika") — zgodnie z zasadą: read-only wszędzie, czego admin nie edytuje
|
||||
* poza swoim edytorem.
|
||||
*/
|
||||
export default function UserMemberships() {
|
||||
const { id } = useParams();
|
||||
const queryClient = useQueryClient();
|
||||
const { user, isLoading, error } = useAdminUser(id);
|
||||
const { data: gymsData } = useUserGyms();
|
||||
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
|
||||
useTopbar({
|
||||
title: 'Członkostwa w siłowniach',
|
||||
back: id ? `/users/${id}` : '/users',
|
||||
actions: [{ label: 'Dodaj członkostwo', icon: Plus, onClick: () => setAddOpen(true) }],
|
||||
});
|
||||
|
||||
const [memGym, setMemGym] = useState('');
|
||||
const [memRoles, setMemRoles] = useState<GymRole[]>(['MEMBER']);
|
||||
const [busy, setBusy] = useState(false);
|
||||
// błąd akcji (dodanie/usunięcie/zmiana ról) — komunikat pod sekcją, nie alert()
|
||||
const [actionError, setActionError] = useState('');
|
||||
// usuwanie przez potwierdzenie (ConfirmDialog) — opis: role + nazwa siłowni
|
||||
const [removeTarget, setRemoveTarget] = useState<null | {
|
||||
gymId: string;
|
||||
gymName: string;
|
||||
roleLabels: string;
|
||||
}>(null);
|
||||
const [removeBusy, setRemoveBusy] = useState(false);
|
||||
|
||||
const refresh = () => queryClient.invalidateQueries({ queryKey: ['admin-users'] });
|
||||
|
||||
const addMembership = async () => {
|
||||
if (!user || !memGym || memRoles.length === 0) return;
|
||||
setBusy(true);
|
||||
setActionError('');
|
||||
try {
|
||||
await api(`/admin/users/${user.id}/memberships`, {
|
||||
method: 'POST',
|
||||
body: { gymId: memGym, roles: memRoles },
|
||||
});
|
||||
setMemGym('');
|
||||
setMemRoles(['MEMBER']);
|
||||
setAddOpen(false);
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
setActionError(err instanceof Error ? err.message : 'Błąd');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleAddRole = (role: GymRole) => {
|
||||
setMemRoles((prev) => (prev.includes(role) ? prev.filter((r) => r !== role) : [...prev, role]));
|
||||
};
|
||||
|
||||
const confirmRemove = async () => {
|
||||
if (!user || !removeTarget) return;
|
||||
const { gymId } = removeTarget;
|
||||
setRemoveTarget(null);
|
||||
setRemoveBusy(true);
|
||||
setActionError('');
|
||||
try {
|
||||
await api(`/admin/users/${user.id}/memberships/${gymId}`, { method: 'DELETE' });
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
setActionError(err instanceof Error ? err.message : 'Błąd');
|
||||
} finally {
|
||||
setRemoveBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMembershipRole = async (gymId: string, role: GymRole) => {
|
||||
if (!user) return;
|
||||
const current = user.memberships?.find((m) => m.gymId === gymId)?.roles ?? [];
|
||||
const next = current.includes(role) ? current.filter((r) => r !== role) : [...current, role];
|
||||
if (next.length === 0) return;
|
||||
setActionError('');
|
||||
try {
|
||||
await api(`/admin/users/${user.id}/memberships/${gymId}`, {
|
||||
method: 'PATCH',
|
||||
body: { roles: next },
|
||||
});
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
setActionError(err instanceof Error ? err.message : 'Błąd');
|
||||
}
|
||||
};
|
||||
useTopbar({ title: 'Członkostwa w siłowniach', back: id ? `/users/${id}` : '/users' });
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -180,9 +37,7 @@ export default function UserMemberships() {
|
||||
if (error) return <ErrorText>Błąd: {(error as Error).message}</ErrorText>;
|
||||
if (!user) return <ErrorText>Nie znaleziono użytkownika.</ErrorText>;
|
||||
|
||||
const gyms = gymsData?.gyms ?? [];
|
||||
const memberships = user.memberships ?? [];
|
||||
const availableGyms = gyms.filter((g) => !memberships.some((m) => m.gymId === g.id));
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -200,42 +55,12 @@ export default function UserMemberships() {
|
||||
{memberships.length > 0 ? (
|
||||
<div className="divide-y divide-line">
|
||||
{memberships.map((m) => (
|
||||
<ListRow
|
||||
key={m.gymId}
|
||||
title={m.gym.name}
|
||||
meta={m.gym.location || undefined}
|
||||
actions={
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
setRemoveTarget({
|
||||
gymId: m.gymId,
|
||||
gymName: m.gym.name,
|
||||
roleLabels: m.roles.map((r) => ROLE_LABELS[r] ?? r).join(', '),
|
||||
})
|
||||
}
|
||||
>
|
||||
Usuń
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="flex w-full flex-wrap gap-2 pt-1">
|
||||
{ROLE_OPTIONS.map((r) => (
|
||||
<RolePill
|
||||
key={r.value}
|
||||
value={r.value}
|
||||
active={m.roles.includes(r.value)}
|
||||
onToggle={() => void toggleMembershipRole(m.gymId, r.value)}
|
||||
ariaLabel={`${r.label} w ${m.gym.name}`}
|
||||
className="min-w-0 flex-1"
|
||||
disabled={m.roles.length === 1 && m.roles.includes(r.value)}
|
||||
title={
|
||||
m.roles.length === 1 && m.roles.includes(r.value)
|
||||
? 'Aby usunąć członkostwo użyj przycisku „Usuń”'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<ListRow key={m.gymId} title={m.gym.name} meta={m.gym.location || undefined}>
|
||||
<div className="flex flex-wrap gap-2 pt-1">
|
||||
{m.roles.map((r) => (
|
||||
<Badge key={r} color="gray">
|
||||
{GYM_ROLE_META[r].label}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</ListRow>
|
||||
@@ -244,55 +69,7 @@ export default function UserMemberships() {
|
||||
) : (
|
||||
<Muted>Brak członkostw.</Muted>
|
||||
)}
|
||||
{actionError && <ErrorText>{actionError}</ErrorText>}
|
||||
</Card>
|
||||
|
||||
<Modal open={addOpen} onClose={() => setAddOpen(false)} title="Dodaj członkostwo">
|
||||
<div className="mt-2 flex flex-col gap-4">
|
||||
<div>
|
||||
<Label>Siłownia</Label>
|
||||
<GymPicker gyms={availableGyms} value={memGym} onChange={setMemGym} />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Role</Label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{ROLE_OPTIONS.map((r) => (
|
||||
<RolePill
|
||||
key={r.value}
|
||||
value={r.value}
|
||||
active={memRoles.includes(r.value)}
|
||||
onToggle={() => toggleAddRole(r.value)}
|
||||
ariaLabel={`Dodaj: ${r.label}`}
|
||||
className="min-w-0 flex-1"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
onClick={() => void addMembership()}
|
||||
disabled={!memGym || memRoles.length === 0 || busy}
|
||||
>
|
||||
Przypisz
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<ConfirmDialog
|
||||
open={removeTarget != null}
|
||||
onClose={() => setRemoveTarget(null)}
|
||||
onConfirm={() => void confirmRemove()}
|
||||
title="Usunąć członkostwo?"
|
||||
description={
|
||||
removeTarget
|
||||
? `${removeTarget.gymName} (${removeTarget.roleLabels}) zostanie trwale usunięte.`
|
||||
: ''
|
||||
}
|
||||
confirmLabel="Usuń"
|
||||
danger
|
||||
busy={removeBusy}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -271,22 +271,21 @@ describe('admin UserForm — kreator tworzenia', () => {
|
||||
});
|
||||
|
||||
describe('admin UserForm — kreator edycji', () => {
|
||||
it('wypełnia formularz danymi konta i ukrywa krok członkostw', async () => {
|
||||
it('wypełnia formularz danymi konta i członkostwami (edytor w wizardzie)', async () => {
|
||||
mockRoutes([
|
||||
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
|
||||
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
|
||||
]);
|
||||
renderForm('/users/u1/edit');
|
||||
// dane konta wczytane z użytkownika
|
||||
// dane i członkostwo wczytane z użytkownika — krok 3 jest też w edycji
|
||||
expect(await screen.findByDisplayValue('jan@test.local')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('Jan')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('30')).toBeInTheDocument();
|
||||
// członkostwa nie należą do wizarda edycji (jedyne miejsce: strona członkostw)
|
||||
expect(screen.queryByText('Członkostwa w siłowniach')).not.toBeInTheDocument();
|
||||
expect(screen.queryByDisplayValue('Fit Factory')).not.toBeInTheDocument();
|
||||
expect(await screen.findByText('Członkostwa w siłowniach')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('Fit Factory')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('zapis edycji PATCHuje tylko konto — bez żądań członkostw', async () => {
|
||||
it('zapis edycji bez zmian członkostw PATCHuje tylko konto', async () => {
|
||||
const calls = mockRoutes([
|
||||
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
|
||||
{ method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
|
||||
@@ -296,7 +295,7 @@ describe('admin UserForm — kreator edycji', () => {
|
||||
renderForm('/users/u1/edit');
|
||||
await screen.findByDisplayValue('jan@test.local');
|
||||
|
||||
// edycja = tożsamość/dostęp: zmiana nazwiska
|
||||
// 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');
|
||||
@@ -312,4 +311,50 @@ describe('admin UserForm — kreator edycji', () => {
|
||||
});
|
||||
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] }) },
|
||||
{ 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)).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: '/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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { act, render, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import UserMemberships from '../src/pages/users/UserMemberships';
|
||||
import { setAccessToken } from '../src/api/client';
|
||||
import { API_BASE } from '../src/config';
|
||||
import { useTopbarStore } from '../src/topbar/store';
|
||||
import type { Gym, User } from '../src/api/types';
|
||||
|
||||
@@ -19,16 +17,6 @@ const G1: Gym = {
|
||||
_count: { memberships: 1 },
|
||||
};
|
||||
|
||||
const G2: Gym = {
|
||||
id: 'g2',
|
||||
name: 'Gym B',
|
||||
location: 'Kraków',
|
||||
availability: null,
|
||||
capacity: null,
|
||||
equipment: [],
|
||||
_count: { memberships: 0 },
|
||||
};
|
||||
|
||||
const U1: User = {
|
||||
id: 'u1',
|
||||
email: 'jan@test.local',
|
||||
@@ -51,15 +39,6 @@ const U1: User = {
|
||||
memberships: [{ gymId: 'g1', roles: ['OWNER', 'TRAINER'], gym: G1 }],
|
||||
};
|
||||
|
||||
const U2: User = {
|
||||
...U1,
|
||||
id: 'u2',
|
||||
email: 'anna@test.local',
|
||||
firstName: 'Anna',
|
||||
lastName: 'Nowak',
|
||||
memberships: [{ gymId: 'g1', roles: ['MEMBER'], gym: G1 }],
|
||||
};
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
@@ -68,15 +47,12 @@ function jsonResponse(status: number, body: unknown) {
|
||||
}
|
||||
|
||||
function mockFetchSequence(...responses: Response[]) {
|
||||
const calls: { url: string; init?: RequestInit }[] = [];
|
||||
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
calls.push({ url, init });
|
||||
const fetchMock = vi.fn(async (url: string) => {
|
||||
const next = responses.shift();
|
||||
if (!next) throw new Error(`No more mocked responses for url: ${url}`);
|
||||
return next;
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return calls;
|
||||
}
|
||||
|
||||
function renderMemberships(path: string) {
|
||||
@@ -100,126 +76,32 @@ afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
/**
|
||||
* Otwarcie modala „Dodaj członkostwo": w teście jednostkowym nie ma <Topbar>,
|
||||
* a `useTopbar` zapisuje tylko konfigurację do store'a — klikamy akcję stamtąd.
|
||||
*/
|
||||
function openAddModal() {
|
||||
act(() => {
|
||||
const action = useTopbarStore
|
||||
.getState()
|
||||
.config?.actions?.find((a) => a.label === 'Dodaj członkostwo');
|
||||
if (!action?.onClick) throw new Error('Brak akcji „Dodaj członkostwo" w konfiguracji topbara');
|
||||
action.onClick();
|
||||
});
|
||||
}
|
||||
|
||||
describe('admin UserMemberships page', () => {
|
||||
it('shows memberships with role checkboxes and hides joined gyms in the picker', async () => {
|
||||
mockFetchSequence(jsonResponse(200, { users: [U1] }), jsonResponse(200, { gyms: [G1, G2] }));
|
||||
const user = userEvent.setup();
|
||||
describe('admin UserMemberships page (tylko do odczytu)', () => {
|
||||
it('lists memberships with role badges and no editing controls', async () => {
|
||||
mockFetchSequence(jsonResponse(200, { users: [U1] }));
|
||||
renderMemberships('/users/u1/memberships');
|
||||
expect(
|
||||
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Gym A')).toBeInTheDocument();
|
||||
expect(screen.getByText('Warszawa')).toBeInTheDocument();
|
||||
// checkboxy ról członkostwa
|
||||
expect(screen.getByRole('checkbox', { name: 'Właściciel w Gym A' })).toBeChecked();
|
||||
expect(screen.getByRole('checkbox', { name: 'Trener w Gym A' })).toBeChecked();
|
||||
expect(screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' })).not.toBeChecked();
|
||||
// wyszukiwarka siłowni (modal z akcji topbara) ukrywa siłownie, do których user już należy
|
||||
openAddModal();
|
||||
await user.click(await screen.findByRole('combobox', { name: 'Szukaj siłowni' }));
|
||||
expect(screen.getByRole('option', { name: /Gym B/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('option', { name: /Gym A/ })).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Właściciel')).toBeInTheDocument();
|
||||
expect(screen.getByText('Trener')).toBeInTheDocument();
|
||||
|
||||
// read-only: brak kontrolek edycji (role są badge'ami, nie checkboxami)
|
||||
expect(screen.queryAllByRole('checkbox')).toHaveLength(0);
|
||||
expect(screen.queryByRole('button', { name: 'Usuń' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Dodaj członkostwo' })).not.toBeInTheDocument();
|
||||
// i w konfiguracji topbara żadnej akcji
|
||||
expect(useTopbarStore.getState().config?.actions ?? []).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('checking a role checkbox sends a PATCH with the full roles list', async () => {
|
||||
const calls = mockFetchSequence(
|
||||
jsonResponse(200, { users: [U1] }),
|
||||
jsonResponse(200, { gyms: [G1, G2] }),
|
||||
jsonResponse(200, { membership: { gymId: 'g1', roles: ['OWNER', 'TRAINER', 'MEMBER'] } }),
|
||||
jsonResponse(200, { users: [U1] }),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
it('shows an empty state when the user has no memberships', async () => {
|
||||
mockFetchSequence(jsonResponse(200, { users: [{ ...U1, memberships: [] }] }));
|
||||
renderMemberships('/users/u1/memberships');
|
||||
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' });
|
||||
await user.click(screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' }));
|
||||
const patch = calls.find(
|
||||
(c) => c.url === `${API_BASE}/admin/users/u1/memberships/g1` && c.init?.method === 'PATCH',
|
||||
);
|
||||
expect(patch).toBeDefined();
|
||||
expect(JSON.parse(patch?.init?.body as string)).toEqual({
|
||||
roles: ['OWNER', 'TRAINER', 'MEMBER'],
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the membership when the last role cannot be unchecked', async () => {
|
||||
const calls = mockFetchSequence(
|
||||
jsonResponse(200, { users: [U2] }),
|
||||
jsonResponse(200, { gyms: [G1, G2] }),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderMemberships('/users/u2/memberships');
|
||||
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' });
|
||||
|
||||
// jedyna aktywna rola jest zablokowana — odznaczenie zostawiłoby puste członkostwo
|
||||
const lastRole = screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' });
|
||||
expect(lastRole).toBeDisabled();
|
||||
expect(screen.getByRole('checkbox', { name: 'Trener w Gym A' })).toBeEnabled();
|
||||
await user.click(lastRole);
|
||||
expect(calls.some((c) => c.init?.method === 'DELETE' || c.init?.method === 'PATCH')).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('adds a membership via the modal opened from the topbar action', async () => {
|
||||
const calls = mockFetchSequence(
|
||||
jsonResponse(200, { users: [U1] }),
|
||||
jsonResponse(200, { gyms: [G1, G2] }),
|
||||
jsonResponse(201, { membership: { gymId: 'g2', roles: ['MEMBER'] } }),
|
||||
jsonResponse(200, { users: [U1] }),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderMemberships('/users/u1/memberships');
|
||||
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' });
|
||||
|
||||
openAddModal();
|
||||
const combobox = await screen.findByRole('combobox', { name: 'Szukaj siłowni' });
|
||||
await user.click(combobox);
|
||||
await user.type(combobox, 'Gym B');
|
||||
await user.click(screen.getByRole('option', { name: /Gym B/ }));
|
||||
await user.click(screen.getByRole('button', { name: 'Przypisz' }));
|
||||
|
||||
const post = calls.find(
|
||||
(c) => c.url === `${API_BASE}/admin/users/u1/memberships` && c.init?.method === 'POST',
|
||||
);
|
||||
expect(post).toBeDefined();
|
||||
expect(JSON.parse(post?.init?.body as string)).toEqual({ gymId: 'g2', roles: ['MEMBER'] });
|
||||
});
|
||||
|
||||
it('removes a membership only after confirming in ConfirmDialog', async () => {
|
||||
const calls = mockFetchSequence(
|
||||
jsonResponse(200, { users: [U1] }),
|
||||
jsonResponse(200, { gyms: [G1, G2] }),
|
||||
new Response(null, { status: 204 }),
|
||||
jsonResponse(200, { users: [{ ...U1, memberships: [] }] }),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderMemberships('/users/u1/memberships');
|
||||
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' });
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Usuń' }));
|
||||
// potwierdzenie: opis z rolami i nazwą siłowni, natychmiastowego DELETE nie ma
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(dialog).toHaveTextContent('Gym A (Właściciel, Trener)');
|
||||
expect(calls.some((c) => c.init?.method === 'DELETE')).toBe(false);
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Usuń' }));
|
||||
|
||||
const del = calls.find(
|
||||
(c) => c.init?.method === 'DELETE' && c.url === `${API_BASE}/admin/users/u1/memberships/g1`,
|
||||
);
|
||||
expect(del).toBeDefined();
|
||||
expect(
|
||||
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Brak członkostw.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,7 +86,9 @@ test('kliknięcie w użytkownika otwiera przegląd profilu (wzór z apki)', asyn
|
||||
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('odznaczenie checkboxa roli dodaje ją i wysyła PATCH z pełną listą', async ({ page }) => {
|
||||
test('strona członkostw jest tylko do odczytu — role jako badge, brak kontrolek edycji', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Użytkownicy' }).click();
|
||||
@@ -94,20 +96,43 @@ test('odznaczenie checkboxa roli dodaje ją i wysyła PATCH z pełną listą', a
|
||||
await page.getByRole('link', { name: /Członkostwa w siłowniach/ }).click();
|
||||
await expect(page).toHaveURL(/\/users\/user-1\/memberships$/);
|
||||
|
||||
// ostatnia rola jest zablokowana — usunięcie członkostwa wymaga przycisku „Usuń”
|
||||
await expect(page.getByRole('checkbox', { name: 'Ćwiczący w Fit Factory' })).toBeDisabled();
|
||||
// dane widoczne (nazwa siłowni + rola jako badge), ale żadnej kontroki edycji —
|
||||
// jedyne miejsce zmiany członkostw to kreator edycji
|
||||
await expect(page.getByText('Fit Factory')).toBeVisible();
|
||||
await expect(page.getByText('Ćwiczący')).toBeVisible();
|
||||
await expect(page.getByRole('checkbox')).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Dodaj członkostwo' })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Usuń', exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveCount(1);
|
||||
});
|
||||
|
||||
test('zmiana roli członkostwa w kreatorze edycji — zapis wysyła PATCH z pełną listą', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] }, 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('button', { name: 'Edytuj' }).click();
|
||||
await expect(page).toHaveURL(/\/users\/user-1\/edit$/);
|
||||
|
||||
// edycja = pełny edytor: członkostwa wczytane i edytowalne w kroku 3
|
||||
await expect(page.getByRole('heading', { name: 'Członkostwa w siłowniach' })).toBeVisible();
|
||||
await expect(page.getByRole('combobox', { name: 'Szukaj siłowni' })).toHaveValue('Fit Factory');
|
||||
|
||||
// dołóż rolę Właściciel (MEMBER → MEMBER + OWNER); zapis = żądania wg diffu
|
||||
await page.getByRole('checkbox', { name: 'Właściciel — Fit Factory' }).click();
|
||||
const patchPromise = page.waitForRequest(
|
||||
(req) =>
|
||||
req.url().includes('/admin/users/user-1/memberships/gym-1') && req.method() === 'PATCH',
|
||||
);
|
||||
// click (not .check): the mock is stateless, so the checkbox reverts after refetch
|
||||
await page.getByRole('checkbox', { name: 'Właściciel w Fit Factory' }).click();
|
||||
await page.getByRole('button', { name: 'Zapisz' }).click();
|
||||
const req = await patchPromise;
|
||||
expect(req.postDataJSON()).toEqual({ roles: ['MEMBER', 'OWNER'] });
|
||||
await expect(page).toHaveURL(/\/users\/user-1$/);
|
||||
});
|
||||
|
||||
test('dodawanie członkostwa z menu kontekstowego (modal) wysyła POST do API', async ({ page }) => {
|
||||
test('dodanie członkostwa w kreatorze edycji — zapis wysyła POST', async ({ page }) => {
|
||||
mockApi(page, {
|
||||
gyms: { gyms: [TEST_GYM, TEST_GYM_2] },
|
||||
users: { users: [TEST_USER] },
|
||||
@@ -115,41 +140,38 @@ test('dodawanie członkostwa z menu kontekstowego (modal) wysyła POST do API',
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Użytkownicy' }).click();
|
||||
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
|
||||
await page.getByRole('link', { name: /Członkostwa w siłowniach/ }).click();
|
||||
await page.getByRole('button', { name: 'Edytuj' }).click();
|
||||
|
||||
// nowy wiersz: siłownia już zajęta jest niedostępna, wybieramy Mega Gym + rolę
|
||||
await page.getByRole('button', { name: 'Dodaj kolejną siłownię' }).click();
|
||||
const picker = page.locator('input[aria-label="Szukaj siłowni"]').last();
|
||||
await picker.click();
|
||||
await expect(page.getByRole('option', { name: /Fit Factory/ })).toHaveCount(0);
|
||||
await page.getByRole('option', { name: /Mega Gym/ }).click();
|
||||
await page.getByRole('checkbox', { name: 'Ćwiczący — Mega Gym' }).click();
|
||||
|
||||
const postPromise = page.waitForRequest(
|
||||
(req) => req.url().includes('/admin/users/user-1/memberships') && req.method() === 'POST',
|
||||
);
|
||||
// tworzenie = akcja w menu kontekstowym (➕), nie przycisk w treści
|
||||
await page.getByRole('button', { name: 'Dodaj członkostwo' }).click();
|
||||
const dialog = page.getByRole('dialog', { name: 'Dodaj członkostwo' });
|
||||
await dialog.getByRole('combobox', { name: 'Szukaj siłowni' }).click();
|
||||
// siłownia, do której user już należy, jest ukryta na liście
|
||||
await expect(page.getByRole('option', { name: /Fit Factory/ })).not.toBeVisible();
|
||||
await page.getByRole('option', { name: /Mega Gym/ }).click();
|
||||
await dialog.getByRole('button', { name: 'Przypisz' }).click();
|
||||
await page.getByRole('button', { name: 'Zapisz' }).click();
|
||||
const req = await postPromise;
|
||||
expect(req.postDataJSON()).toEqual({ gymId: 'gym-2', roles: ['MEMBER'] });
|
||||
});
|
||||
|
||||
test('usunięcie członkostwa wymaga potwierdzenia i wysyła DELETE', async ({ page }) => {
|
||||
test('usunięcie członkostwa w kreatorze edycji — zapis wysyła DELETE', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] }, 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: /Członkostwa w siłowniach/ }).click();
|
||||
|
||||
await page.getByRole('button', { name: 'Usuń', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: 'Usunąć członkostwo?' });
|
||||
await expect(dialog).toBeVisible();
|
||||
// opis potwierdzenia: nazwa siłowni + rola
|
||||
await expect(dialog.getByText('Fit Factory (Ćwiczący)')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Edytuj' }).click();
|
||||
|
||||
await page.getByRole('button', { name: 'Usuń Fit Factory' }).click();
|
||||
const delPromise = page.waitForRequest(
|
||||
(req) => req.method() === 'DELETE' && req.url().includes('/memberships/gym-1'),
|
||||
);
|
||||
await dialog.getByRole('button', { name: 'Usuń', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Zapisz' }).click();
|
||||
await delPromise;
|
||||
await expect(page).toHaveURL(/\/users\/user-1$/);
|
||||
});
|
||||
|
||||
test('zakładka danych osobowych jest tylko do odczytu (brak kontrolek edycji)', async ({
|
||||
@@ -189,9 +211,7 @@ test('parametry ciała tylko do odczytu — brak kontrolek dodawania/usuwania po
|
||||
await expect(page.getByRole('heading', { level: 2, name: 'Parametry ciała' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('kreator edycji użytkownika zapisuje tylko dane konta (PATCH), bez członkostw', async ({
|
||||
page,
|
||||
}) => {
|
||||
test('kreator edycji: zapis bez zmian członkostw wysyła tylko PATCH konta', 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();
|
||||
@@ -203,11 +223,16 @@ test('kreator edycji użytkownika zapisuje tylko dane konta (PATCH), bez członk
|
||||
await expect(page).toHaveURL(/\/users\/user-1\/edit$/);
|
||||
await expect(page.getByRole('heading', { name: 'Edycja użytkownika' })).toBeVisible();
|
||||
await expect(page.locator('input[type="email"]')).toHaveValue('jan@fitos.pl');
|
||||
// edycja = wyłącznie konto — brak kroku członkostw (jedyne miejsce: strona członkostw)
|
||||
await expect(page.getByText('Członkostwa w siłowniach')).toHaveCount(0);
|
||||
await expect(page.locator('input[role="combobox"]')).toHaveCount(0);
|
||||
// pełny edytor: krok członkostw wczytany (skłon ról bez zmian = zero żądań członkostw)
|
||||
await expect(page.getByRole('heading', { name: 'Członkostwa w siłowniach' })).toBeVisible();
|
||||
await expect(page.getByRole('combobox', { name: 'Szukaj siłowni' })).toHaveValue('Fit Factory');
|
||||
|
||||
// zmiana nazwiska → PATCH konta (pole „Nazwisko” = drugi input formularza)
|
||||
const membershipCalls: string[] = [];
|
||||
page.on('request', (req) => {
|
||||
if (req.url().includes('/memberships')) membershipCalls.push(`${req.method()} ${req.url()}`);
|
||||
});
|
||||
|
||||
// zmiana nazwiska → PATCH konta (pole „Nazwisko" = drugi input formularza)
|
||||
const patchPromise = page.waitForRequest(
|
||||
(req) => req.method() === 'PATCH' && req.url().endsWith('/admin/users/user-1'),
|
||||
);
|
||||
@@ -216,6 +241,7 @@ test('kreator edycji użytkownika zapisuje tylko dane konta (PATCH), bez członk
|
||||
const req = await patchPromise;
|
||||
expect(req.postDataJSON()).toMatchObject({ lastName: 'Nowak', email: 'jan@fitos.pl' });
|
||||
await expect(page).toHaveURL(/\/users\/user-1$/);
|
||||
expect(membershipCalls).toEqual([]);
|
||||
});
|
||||
|
||||
test('przycisk w prawym górnym rogu prowadzi do formularza dodawania', async ({ page }) => {
|
||||
|
||||
Reference in New Issue
Block a user