479 lines
18 KiB
TypeScript
479 lines
18 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
import { useNavigate, useParams } from 'react-router-dom';
|
|
import { useTranslation } from 'react-i18next';
|
|
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 { todayStr, maskEmail } from '../../lib/format';
|
|
import { GymPicker } from '../../components/GymPicker';
|
|
import { GymRolePicker } from '../../components/GymRolePicker';
|
|
import {
|
|
BackButton,
|
|
Badge,
|
|
Button,
|
|
Card,
|
|
ErrorText,
|
|
Field,
|
|
H3,
|
|
Input,
|
|
Label,
|
|
Loading,
|
|
Modal,
|
|
} from '../../components/ui';
|
|
import { useTopbar } from '../../topbar';
|
|
import { useAdminUser, useUserGyms } from './user-queries';
|
|
import { useAuth } from '../../store/auth';
|
|
|
|
/** 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, items }: { open: boolean; items: string[] }) {
|
|
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">
|
|
{items.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 — jedyne miejsce edycji danych i członkostw.
|
|
* Tworzenie: dane + role + członkostwa (POST-y po utworzeniu konta).
|
|
* Edycja: PATCH konta + porządkowanie członkostw (POST/PATCH/DELETE wg zmian);
|
|
* strona „Członkostwa w siłowniach" jest tylko do odczytu, a kary (zawieszenie/ban)
|
|
* nadaje się z menu kontekstowego strony użytkownika (UserRestrictionModal).
|
|
*/
|
|
export default function UserForm() {
|
|
const { t } = useTranslation('users');
|
|
const me = useAuth((s) => s.user);
|
|
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: isEdit ? t('editUser') : t('newUser'),
|
|
back: isEdit && id ? `/users/${id}` : '/users',
|
|
actions: [
|
|
{
|
|
label: busy ? t('common:saving') : t('common:save'),
|
|
icon: Check,
|
|
onClick: submitFromMenu,
|
|
disabled: busy,
|
|
},
|
|
],
|
|
alwaysInlineActions: true,
|
|
flatActionsMobile: true,
|
|
});
|
|
|
|
const gyms: Gym[] = gymsData?.gyms ?? [];
|
|
|
|
const [form, setForm] = useState({
|
|
firstName: '',
|
|
lastName: '',
|
|
password: '',
|
|
password2: '',
|
|
email: '',
|
|
birthDate: '',
|
|
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);
|
|
// utworzone w tej sesji konto + członkostwa — ponowny „Zapisz" po błędzie
|
|
// członkostwa ponawia tylko brakujące POST-y, bez drugiego konta
|
|
const createdIdRef = useRef<string | null>(null);
|
|
const doneGymIdsRef = useRef<Set<string>>(new Set());
|
|
|
|
// 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,
|
|
birthDate: user.birthDate ? user.birthDate.slice(0, 10) : '',
|
|
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 t('emailRequired');
|
|
if (!isEdit && form.password.length < 8) return t('passMin8');
|
|
if (isEdit && form.password && form.password.length < 8) return t('newPassMin8');
|
|
// w edycji oba pola mogą zostać puste (bez zmiany hasła); w tworzeniu muszą się zgadzać
|
|
if (form.password !== form.password2) return t('passMismatch');
|
|
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 ?? t('fallbackThis');
|
|
return t('roleNoGym', { name });
|
|
}
|
|
if (!r.gymId && r.roles.length > 0) {
|
|
const labels = r.roles.map((x) => t(`common:${GYM_ROLE_META[x].labelKey}`)).join(', ');
|
|
return t('rolesNeedGym', { labels });
|
|
}
|
|
}
|
|
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 {
|
|
if (!isEdit) {
|
|
let createdId = createdIdRef.current;
|
|
if (!createdId) {
|
|
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,
|
|
birthDate: form.birthDate || undefined,
|
|
isAdmin: form.isAdmin,
|
|
},
|
|
});
|
|
createdId = data.user.id;
|
|
createdIdRef.current = createdId;
|
|
}
|
|
for (const r of rows.filter((x) => x.gymId)) {
|
|
if (doneGymIdsRef.current.has(r.gymId)) continue;
|
|
await api(`/admin/users/${createdId}/memberships`, {
|
|
method: 'POST',
|
|
body: { gymId: r.gymId, roles: r.roles },
|
|
});
|
|
doneGymIdsRef.current.add(r.gymId);
|
|
}
|
|
navigate(`/users/${createdId}`);
|
|
return;
|
|
}
|
|
|
|
// EDYCJA: PATCH konta (tożsamość/dostęp), potem porządkowanie członkostw.
|
|
// E-mail w edycji jest ukryty (zna go tylko user) — PATCH przenosi niezmieniony adres.
|
|
const patchBody: Record<string, unknown> = {
|
|
email: form.email.trim(),
|
|
firstName: form.firstName || null,
|
|
lastName: form.lastName || null,
|
|
birthDate: form.birthDate || 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 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 : t('common:error'));
|
|
} 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" />
|
|
|
|
<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">{t('stepData')}</H3>
|
|
</div>
|
|
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
|
|
<Field label={t('firstName')}>
|
|
<Input
|
|
value={form.firstName}
|
|
onChange={(e) => setForm({ ...form, firstName: e.target.value })}
|
|
/>
|
|
</Field>
|
|
<Field label={t('lastName')}>
|
|
<Input
|
|
value={form.lastName}
|
|
onChange={(e) => setForm({ ...form, lastName: e.target.value })}
|
|
/>
|
|
</Field>
|
|
<Field label={isEdit ? t('newPasswordOpt') : t('passwordMin8')}>
|
|
<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 ? t('repeatNewPassword') : t('repeatPassword')}>
|
|
<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={t('auth:email')}>
|
|
{isEdit && id !== me?.id ? (
|
|
// cudzy e-mail: zamaskowany i tylko do odczytu (zna go tylko właściciel);
|
|
// PATCH poniżej przenosi niezmieniony, pełny adres z formularza
|
|
<Input value={maskEmail(form.email)} readOnly disabled />
|
|
) : (
|
|
<Input
|
|
type="email"
|
|
value={form.email}
|
|
onChange={(e) => setForm({ ...form, email: e.target.value })}
|
|
required
|
|
/>
|
|
)}
|
|
</Field>
|
|
<Field label={t('birthDate')}>
|
|
<Input
|
|
type="date"
|
|
max={todayStr()}
|
|
value={form.birthDate}
|
|
onChange={(e) => setForm({ ...form, birthDate: 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>
|
|
<H3 className="mb-0">{t('stepRoles')}</H3>
|
|
</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" />
|
|
{t('adminPlatformTitle')}
|
|
</span>
|
|
<span className="block text-[0.8125rem] text-dim">
|
|
{t(`common:${ADMIN_ROLE_META.summaryKey}`)}
|
|
</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 ? t('ariaHideAdmin') : t('ariaShowAdmin')}
|
|
>
|
|
<ChevronDown
|
|
className={`h-4 w-4 transition-transform ${adminExplain ? 'rotate-180' : ''}`}
|
|
/>
|
|
</button>
|
|
</div>
|
|
<AdminExplain
|
|
open={adminExplain}
|
|
items={ADMIN_ROLE_META.grantKeys.map((k) => t(`common:${k}`))}
|
|
/>
|
|
</div>
|
|
</Card>
|
|
|
|
{/* 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">
|
|
{isEdit ? 4 : 3}
|
|
</span>
|
|
<div className="flex min-w-0 flex-1 items-center justify-between gap-3">
|
|
<H3 className="mb-0">{t('membershipsTitle')}</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">{t('noGymsYet')}</p>
|
|
<p className="mx-auto mt-1 max-w-md text-[0.875rem] text-dim">{t('noGymsYetDesc')}</p>
|
|
<Button type="button" variant="secondary" size="sm" onClick={addRow} className="mt-4">
|
|
<UserPlus className="h-4 w-4" />
|
|
{t('addFirstGym')}
|
|
</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
|
|
? t('removeGymAria', { name: gym.name })
|
|
: t('removeGymRowAria', { n: i + 1 })
|
|
}
|
|
>
|
|
<Trash2 className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
<div>
|
|
<Label>{t('gymLabel')}</Label>
|
|
<GymPicker
|
|
gyms={gymsFor(r.key)}
|
|
value={r.gymId}
|
|
onChange={(gymId) => updateRow(r.key, { gymId })}
|
|
/>
|
|
</div>
|
|
<div>
|
|
<Label>{t('stepRoles')}</Label>
|
|
<GymRolePicker
|
|
value={r.roles}
|
|
onChange={(roles) => updateRow(r.key, { roles })}
|
|
labelPrefix={gym?.name ?? t('gymFallback', { n: 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" />
|
|
{t('addNextGym')}
|
|
</Button>
|
|
</>
|
|
)}
|
|
</Card>
|
|
|
|
{error && <ErrorText>{error}</ErrorText>}
|
|
</form>
|
|
|
|
{/* zapis wzbroniony, dopóki wiersz członkostwa jest niekompletny */}
|
|
<Modal open={rowError !== null} onClose={() => setRowError(null)} title={t('cannotSave')}>
|
|
<p className="text-[0.95rem] text-dim">{rowError}</p>
|
|
<div className="mt-5 flex justify-end">
|
|
<Button onClick={() => setRowError(null)}>{t('understand')}</Button>
|
|
</div>
|
|
</Modal>
|
|
</>
|
|
);
|
|
}
|