469 lines
17 KiB
TypeScript
469 lines
17 KiB
TypeScript
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';
|
|
import type { Gym, GymRole, User } from '../../api/types';
|
|
import { ADMIN_ROLE_META, GYM_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,
|
|
Label,
|
|
Loading,
|
|
Modal,
|
|
} 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>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Kreator tworzenia/edycji użytkownika. Role siłowni w wierszach wzorowane na
|
|
* `/users/:id/memberships`: nazwa siłowni + piguły ról pod spodem.
|
|
*/
|
|
export default function UserForm() {
|
|
const { id } = useParams();
|
|
const isEdit = Boolean(id);
|
|
const navigate = useNavigate();
|
|
const { user, isLoading } = useAdminUser(id);
|
|
const { data: gymsData } = useUserGyms();
|
|
const formRef = useRef<HTMLFormElement>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
|
|
// Zapis jako akcja w menu kontekstowym (topbar) — formularz bywa długi,
|
|
// przycisk zapisu powinien być dostępny zawsze, nie tylko na dole strony.
|
|
const submitFromMenu = () => {
|
|
formRef.current?.requestSubmit();
|
|
};
|
|
|
|
useTopbar({
|
|
title: 'Użytkownicy',
|
|
back: isEdit && id ? `/users/${id}` : '/users',
|
|
actions: [
|
|
{
|
|
label: busy ? 'Zapisywanie…' : 'Zapisz',
|
|
icon: Check,
|
|
onClick: submitFromMenu,
|
|
disabled: busy,
|
|
},
|
|
],
|
|
alwaysInlineActions: true,
|
|
flatActionsMobile: true,
|
|
});
|
|
|
|
const gyms: Gym[] = gymsData?.gyms ?? [];
|
|
|
|
const [form, setForm] = useState({
|
|
firstName: '',
|
|
lastName: '',
|
|
password: '',
|
|
password2: '',
|
|
email: '',
|
|
age: '',
|
|
isAdmin: false,
|
|
});
|
|
const [adminExplain, setAdminExplain] = useState(false);
|
|
// domyślnie zero wierszy — pierwszą siłownię dodaje admin (mile widziana w stanie pustym)
|
|
const [rows, setRows] = useState<MembershipRow[]>([]);
|
|
const [error, setError] = useState('');
|
|
// niekompletny wiersz członkostwa (rola bez siłowni / siłownia bez roli) — modal blokuje zapis
|
|
const [rowError, setRowError] = useState<string | null>(null);
|
|
|
|
// 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({
|
|
firstName: user.firstName ?? '',
|
|
lastName: user.lastName ?? '',
|
|
password: '',
|
|
password2: '',
|
|
email: user.email,
|
|
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: [], 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.';
|
|
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.';
|
|
// w edycji oba pola mogą zostać puste (bez zmiany hasła); w tworzeniu muszą się zgadzać
|
|
if (form.password !== form.password2) return 'Podane hasła muszą być takie same.';
|
|
return '';
|
|
};
|
|
|
|
// Wiersz członkostwa musi być kompletny: rola ⇔ siłownia. Niekompletny = zapis wzbroniony.
|
|
const validateRows = (): string => {
|
|
for (const r of rows) {
|
|
if (r.gymId && r.roles.length === 0) {
|
|
const name = gyms.find((g) => g.id === r.gymId)?.name ?? 'tego';
|
|
return `Nie wolno dodać kogoś do siłowni bez roli. Zaznacz rolę dla „${name}” albo usuń ten wiersz.`;
|
|
}
|
|
if (!r.gymId && r.roles.length > 0) {
|
|
const labels = r.roles.map((x) => GYM_ROLE_META[x].label).join(', ');
|
|
return `Role (${labels}) wymagają wybranej siłowni. Wybierz siłownię albo odznacz role.`;
|
|
}
|
|
}
|
|
return '';
|
|
};
|
|
|
|
const submit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
const validation = validate();
|
|
if (validation) {
|
|
setError(validation);
|
|
return;
|
|
}
|
|
const rowsProblem = validateRows();
|
|
if (rowsProblem) {
|
|
setRowError(rowsProblem);
|
|
return;
|
|
}
|
|
setError('');
|
|
setBusy(true);
|
|
try {
|
|
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 {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
if (isEdit && (isLoading || !user)) return <Loading />;
|
|
|
|
// licznik przy sekcji = tylko wiersze z wybraną siłownią (nie puste szkice)
|
|
const filledCount = rows.filter((r) => r.gymId).length;
|
|
|
|
return (
|
|
<>
|
|
<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 ref={formRef} 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="Imię">
|
|
<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 })}
|
|
/>
|
|
</Field>
|
|
<Field label={isEdit ? 'Nowe hasło (opcjonalnie)' : 'Hasło (min. 8)'}>
|
|
<Input
|
|
type="password"
|
|
autoComplete="new-password"
|
|
value={form.password}
|
|
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
|
minLength={8}
|
|
required={!isEdit}
|
|
placeholder={isEdit ? '••••••••' : undefined}
|
|
/>
|
|
</Field>
|
|
<Field label={isEdit ? 'Powtórz nowe hasło' : 'Powtórz hasło'}>
|
|
<Input
|
|
type="password"
|
|
autoComplete="new-password"
|
|
value={form.password2}
|
|
onChange={(e) => setForm({ ...form, password2: e.target.value })}
|
|
minLength={8}
|
|
required={!isEdit}
|
|
placeholder={isEdit ? '••••••••' : undefined}
|
|
/>
|
|
</Field>
|
|
<Field label="E-mail">
|
|
<Input
|
|
type="email"
|
|
value={form.email}
|
|
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
|
required
|
|
/>
|
|
</Field>
|
|
<Field label="Wiek">
|
|
<Input
|
|
type="number"
|
|
value={form.age}
|
|
onChange={(e) => setForm({ ...form, age: e.target.value })}
|
|
/>
|
|
</Field>
|
|
</div>
|
|
</Card>
|
|
|
|
{/* Krok 2 — role w panelu */}
|
|
<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</H3>
|
|
<p className="text-[0.8125rem] text-dim">
|
|
Co użytkownik może robić w panelu FitOS — opcjonalnie.
|
|
</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>
|
|
</Card>
|
|
|
|
{/* Krok 3 — członkostwa w siłowniach */}
|
|
<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">
|
|
<div>
|
|
<H3 className="mb-0">Członkostwa w siłowniach</H3>
|
|
<p className="text-[0.8125rem] text-dim">
|
|
Dostęp do poszczególnych siłowni i role w nich — trenowanie, prowadzenie,
|
|
zarządzanie.
|
|
</p>
|
|
</div>
|
|
{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>
|
|
</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>
|
|
|
|
{error && <ErrorText>{error}</ErrorText>}
|
|
</form>
|
|
|
|
{/* zapis wzbroniony, dopóki wiersz członkostwa jest niekompletny */}
|
|
<Modal open={rowError !== null} onClose={() => setRowError(null)} title="Nie można zapisać">
|
|
<p className="text-[0.95rem] text-dim">{rowError}</p>
|
|
<div className="mt-5 flex justify-end">
|
|
<Button onClick={() => setRowError(null)}>Rozumiem</Button>
|
|
</div>
|
|
</Modal>
|
|
</>
|
|
);
|
|
}
|