From 320682d37f2755f2dbfd352290f0f9f8422c7251 Mon Sep 17 00:00:00 2001 From: Tilumca Date: Thu, 15 Oct 2026 00:02:40 +0200 Subject: [PATCH] Admin: panel silowni jak w apce + wyznaczanie wlasciciela (grupowane menu kontekstowe z modalami, sekcja Wlasciciele) --- admin/src/api/types.ts | 9 + admin/src/components/UserPicker.tsx | 109 +++++ admin/src/pages/gyms/GymDetail.tsx | 673 +++++++++++++++++++--------- admin/src/pages/gyms/GymForm.tsx | 39 +- admin/src/topbar/GroupButton.tsx | 76 +++- admin/src/topbar/Topbar.tsx | 71 ++- admin/src/topbar/index.ts | 2 +- admin/src/topbar/store.ts | 8 +- admin/src/topbar/types.ts | 28 ++ admin/test/GymDetail.test.tsx | 137 ++++-- admin/test/e2e/admin.spec.ts | 39 +- admin/test/e2e/gym-gallery.spec.ts | 3 + admin/test/e2e/mock-api.ts | 47 ++ 13 files changed, 973 insertions(+), 268 deletions(-) create mode 100644 admin/src/components/UserPicker.tsx diff --git a/admin/src/api/types.ts b/admin/src/api/types.ts index 4fafb4c..a8a4ee3 100644 --- a/admin/src/api/types.ts +++ b/admin/src/api/types.ts @@ -152,6 +152,15 @@ export interface Gym { coverPhoto: string | null; photos?: GymPhoto[]; _count?: { memberships: number }; + /** Właściciele (rola OWNER) — tylko odpowiedź GET /admin/gyms/:id. */ + owners?: GymOwner[]; +} + +export interface GymOwner { + id: string; + firstName: string | null; + lastName: string | null; + email: string; } export type ClaimStatus = 'PENDING' | 'APPROVED' | 'REJECTED'; diff --git a/admin/src/components/UserPicker.tsx b/admin/src/components/UserPicker.tsx new file mode 100644 index 0000000..9574718 --- /dev/null +++ b/admin/src/components/UserPicker.tsx @@ -0,0 +1,109 @@ +import { useState } from 'react'; +import { Search, X } from 'lucide-react'; +import type { User } from '../api/types'; + +export function userLabel(u: User): string { + return [u.firstName, u.lastName].filter(Boolean).join(' ') || u.email; +} + +/** Przeszukiwalny wybór użytkownika (listę pobiera strona) — wzór: GymPicker z członkostw. */ +export function UserPicker({ + users, + value, + onChange, + ariaLabel = 'Szukaj użytkownika', + listLabel = 'Lista użytkowników', + emptyLabel = 'Brak użytkowników', +}: { + users: User[]; + value: string; + onChange: (id: string) => void; + ariaLabel?: string; + listLabel?: string; + emptyLabel?: string; +}) { + const [query, setQuery] = useState(''); + const [open, setOpen] = useState(false); + const selected = users.find((u) => u.id === value); + const q = query.trim().toLowerCase(); + const filtered = q + ? users.filter( + (u) => userLabel(u).toLowerCase().includes(q) || u.email.toLowerCase().includes(q), + ) + : users; + + const close = () => { + setOpen(false); + setQuery(''); + }; + + const handleBlur = (e: React.FocusEvent) => { + if (e.currentTarget.contains(e.relatedTarget as Node)) return; + close(); + }; + + return ( +
+
+ + { + setQuery(e.target.value); + setOpen(true); + }} + onFocus={() => setOpen(true)} + /> + {selected && !open && ( + + )} +
+ {open && ( +
+ {filtered.length === 0 ? ( +
+ {q ? `Brak użytkowników dla „${query.trim()}”` : emptyLabel} +
+ ) : ( + filtered.map((u) => ( + + )) + )} +
+ )} +
+ ); +} diff --git a/admin/src/pages/gyms/GymDetail.tsx b/admin/src/pages/gyms/GymDetail.tsx index faf0ce8..49cf08b 100644 --- a/admin/src/pages/gyms/GymDetail.tsx +++ b/admin/src/pages/gyms/GymDetail.tsx @@ -1,10 +1,22 @@ import { useState } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { Dumbbell, ImagePlus, MapPin, Star, Users, X } from 'lucide-react'; -import { useTopbar } from '../../topbar'; +import { + Dumbbell, + Image as ImageIcon, + MapPin, + Pencil, + ShieldCheck, + Star, + Users, + Wrench, + X, +} from 'lucide-react'; +import { useTopbar, type TopbarCustomGroup } from '../../topbar'; import { api } from '../../api/client'; import { AuthImage } from '../../components/AuthImage'; +import { UserPicker } from '../../components/UserPicker'; +import { useAdminUsers } from '../users/user-queries'; import type { Equipment, Gym, GymException, GymPhoto } from '../../api/types'; import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment'; import { @@ -12,10 +24,16 @@ import { Button, Card, Chip, + ConfirmDialog, ErrorText, Field, + H3, Input, + Label, + ListRow, Loading, + Modal, + Muted, SectionHeader, Select, SuccessText, @@ -56,14 +74,234 @@ function HoursList({ gym }: { gym: Gym }) { ); } -const PHOTO_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp']; -const MAX_PHOTO_FILES = 10; -const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024; +/* Mozaika galerii (odczyt): pierwsze zdjęcie duże, reszta siatką, „+N” na końcu — jak w apce. */ +function GalleryMosaic({ gym }: { gym: Gym }) { + const photos = gym.photos ?? []; + if (photos.length === 0) { + return

Brak zdjęć.

; + } + const [first, ...rest] = photos; + return ( +
+
+ +
+ {rest.slice(0, 3).map((p) => ( +
+ +
+ ))} + {rest.length > 3 && ( +
+ +{rest.length - 3} zdjęć +
+ )} +
+ ); +} -async function uploadGymPhotos(gymId: string, files: File[]): Promise { - const form = new FormData(); - for (const file of files) form.append('photos', file); - return api(`/gyms/${gymId}/photos`, { method: 'POST', body: form }); +/* Kafle urządzeń (odczyt) — jak w apce; zarządzanie w modalu z grupy „Urządzenia”. */ +function EquipmentTiles({ gym }: { gym: Gym }) { + if (gym.equipment.length === 0) { + return

Brak urządzeń.

; + } + return ( +
+ {gym.equipment.map((e) => ( +
+ {formatGymEquipment(e)} +
+ ))} +
+ ); +} + +/* Wyjątki (admin): komposer (data + tryb + godziny) — jak w apce. */ +function ExceptionsComposer({ gymId }: { gymId: string }) { + const queryClient = useQueryClient(); + const [date, setDate] = useState(''); + const [closed, setClosed] = useState(true); + const [start, setStart] = useState('18:00'); + const [end, setEnd] = useState('20:00'); + const [error, setError] = useState(''); + const [busy, setBusy] = useState(false); + + const add = async () => { + setError(''); + setBusy(true); + try { + await api(`/admin/gyms/${gymId}/exceptions`, { + method: 'POST', + body: { date, availability: closed ? null : { start, end } }, + }); + setDate(''); + await queryClient.invalidateQueries({ queryKey: ['gym-exceptions', gymId] }); + } catch (err) { + setError(err instanceof Error ? err.message : 'Błąd'); + } finally { + setBusy(false); + } + }; + + return ( +
+
+ Dodaj wyjątek — data i tryb dnia +
+ {/* wiersz 1: data + tryb; na wąskich ekranach każde przechodzi na pełną szerokość */} +
+ setDate(e.target.value)} + aria-label="Data wyjątku" + className="w-full min-w-0 sm:w-44 sm:flex-none" + required + /> +
+ + +
+
+ {/* wiersz 2: godziny + akcja; selecty dzielą miejsce po równo, nigdy się nie łamią */} + {!closed && ( +
+ + + +
+ )} + {closed && ( +
+ +
+ )} + {error && {error}} +
+ ); +} + +/* Lista wyjątków z usuwaniem (admin może zarządzać każdym dniem). */ +function ExceptionsList({ gymId }: { gymId: string }) { + const queryClient = useQueryClient(); + const { data, isLoading } = useQuery({ + queryKey: ['gym-exceptions', gymId], + queryFn: () => api<{ exceptions: GymException[] }>(`/admin/gyms/${gymId}/exceptions`), + }); + const exceptions = data?.exceptions ?? []; + + const remove = async (exceptionId: string) => { + try { + await api(`/admin/gyms/${gymId}/exceptions/${exceptionId}`, { method: 'DELETE' }); + await queryClient.invalidateQueries({ queryKey: ['gym-exceptions', gymId] }); + } catch (err) { + alert(err instanceof Error ? err.message : 'Błąd'); + } + }; + + if (isLoading) return ; + if (exceptions.length === 0) { + return

Brak wyjątków.

; + } + return ( +
+ {exceptions.map((ex) => ( +
+ + {new Date(ex.date).toLocaleDateString('pl-PL')} + + + {ex.availability ? `${ex.availability.start}–${ex.availability.end}` : 'zamknięte'} + + +
+ ))} +
+ ); +} + +/* Wyjątki w modalu edycji: komposer + lista istniejących (jak ExceptionsBlock w apce). */ +function ExceptionsEditor({ gymId }: { gymId: string }) { + const { data } = useQuery({ + queryKey: ['gym-exceptions', gymId], + queryFn: () => api<{ exceptions: GymException[] }>(`/admin/gyms/${gymId}/exceptions`), + }); + const has = (data?.exceptions ?? []).length > 0; + return ( + <> + + {has && ( +
+ +
+ )} + + ); } function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void }) { @@ -139,6 +377,98 @@ function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void }) { ); } +/* Właściciele siłowni (admin-only): lista + nadawanie i odbieranie roli OWNER. */ +function OwnersSection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) { + const { data: usersData } = useAdminUsers(); + const owners = gym.owners ?? []; + const [pick, setPick] = useState(''); + const [error, setError] = useState(''); + const [busy, setBusy] = useState(false); + + const availableUsers = (usersData?.users ?? []).filter((u) => !owners.some((o) => o.id === u.id)); + + const add = async () => { + if (!pick) return; + setError(''); + setBusy(true); + try { + await api(`/admin/gyms/${gym.id}/owners`, { method: 'POST', body: { userId: pick } }); + setPick(''); + onChanged(); + } catch (err) { + setError(err instanceof Error ? err.message : 'Błąd'); + } finally { + setBusy(false); + } + }; + + const remove = async (userId: string) => { + setError(''); + setBusy(true); + try { + await api(`/admin/gyms/${gym.id}/owners/${userId}`, { method: 'DELETE' }); + onChanged(); + } catch (err) { + setError(err instanceof Error ? err.message : 'Błąd'); + } finally { + setBusy(false); + } + }; + + return ( + <> + +
+ {owners.length === 0 && ( + Brak właściciela — wyznacz go, aby użytkownik mógł zarządzać siłownią. + )} + {owners.map((o) => ( + void remove(o.id)} + > + Odbierz rolę + + } + /> + ))} +
+
+

Nadaj właściciela

+
+
+ + +
+
+ +
+
+ {error && {error}} +
+ + ); +} + export default function GymDetail() { const { id } = useParams(); const navigate = useNavigate(); @@ -153,24 +483,73 @@ export default function GymDetail() { enabled: !!id, }); + const [editOpen, setEditOpen] = useState(false); + const [galleryOpen, setGalleryOpen] = useState(false); + const [equipmentOpen, setEquipmentOpen] = useState(false); + const [ownersOpen, setOwnersOpen] = useState(false); + const [confirmOpen, setConfirmOpen] = useState(false); + const [busy, setBusy] = useState(false); + + const invalidate = () => + Promise.all([ + queryClient.invalidateQueries({ queryKey: ['gyms'] }), + queryClient.invalidateQueries({ queryKey: ['gym', id] }), + ]); + const remove = async () => { if (!gym) return; - if (!confirm('Usunąć siłownię? Członkostwa zostaną usunięte, plany użytkowników zachowane.')) - return; + setBusy(true); try { await api(`/admin/gyms/${gym.id}`, { method: 'DELETE' }); await queryClient.invalidateQueries({ queryKey: ['gyms'] }); navigate('/gyms'); } catch (err) { alert(err instanceof Error ? err.message : 'Błąd'); + } finally { + setBusy(false); } }; - // operacje stronicowe w menu kontekstowym (standard topmenu) + // Operacje admina pogrupowane tematycznie w menu kontekstowym (topbar) — jak w apce; + // dodatkowo grupa „Właściciele” (niedostępna dla zwykłych userów). + const groups: TopbarCustomGroup[] | undefined = gym + ? [ + { + id: 'edit', + label: 'Edycja', + icon: Pencil, + actions: [{ label: 'Dane, godziny i wyjątki', onClick: () => setEditOpen(true) }], + }, + ...(gym.kind === 'REAL' + ? [ + { + id: 'gallery', + label: 'Galeria', + icon: ImageIcon, + actions: [{ label: 'Zarządzaj galerią', onClick: () => setGalleryOpen(true) }], + } as TopbarCustomGroup, + ] + : []), + { + id: 'equipment', + label: 'Urządzenia', + icon: Wrench, + actions: [{ label: 'Zarządzaj urządzeniami', onClick: () => setEquipmentOpen(true) }], + }, + { + id: 'owners', + label: 'Właściciele', + icon: ShieldCheck, + actions: [{ label: 'Zarządzaj właścicielami', onClick: () => setOwnersOpen(true) }], + }, + ] + : undefined; + useTopbar({ title: 'Siłownie', back: '/gyms', - actions: [{ label: 'Usuń siłownię', variant: 'danger', onClick: remove }], + groups, + actions: [{ label: 'Usuń siłownię', variant: 'danger', onClick: () => setConfirmOpen(true) }], }); if (isLoading) return ; @@ -184,6 +563,10 @@ export default function GymDetail() { ); } + const ownerNames = (gym.owners ?? []).map( + (o) => [o.firstName, o.lastName].filter(Boolean).join(' ') || o.email, + ); + return ( <> {/* HERO: okładka (zdjęcie lub placeholder) + nazwa + chipy metadanych */} @@ -253,27 +636,21 @@ export default function GymDetail() { - {/* DWIE KOLUMNY */} + {/* DWIE KOLUMNY (widok odczytu identyczny jak w apce; edycja w grupach menu) */}
{gym.kind === 'REAL' && ( - {}} /> + + )} - - - - - { - void queryClient.invalidateQueries({ queryKey: ['gyms'] }); - void queryClient.invalidateQueries({ queryKey: ['gym', gym.id] }); - }} + +
@@ -284,7 +661,7 @@ export default function GymDetail() {
Wyjątki
- + @@ -295,16 +672,64 @@ export default function GymDetail() { {gym.isPrivate ? 'tak' : 'nie'} Pojemność {gym.capacity ?? '—'} + Właściciele + {ownerNames.length > 0 ? ownerNames.join(', ') : '—'}
+ + {/* MODALE operacji (otwierane z grup menu kontekstowego) */} + setEditOpen(false)} + title="Dane, godziny i wyjątki" + className="max-w-2xl" + > + { + void invalidate(); + }} + /> +
+ + +
+
+ setGalleryOpen(false)} title="Zarządzaj galerią"> + void invalidate()} /> + + setEquipmentOpen(false)} + title="Zarządzaj urządzeniami" + > + void invalidate()} /> + + setOwnersOpen(false)} title="Zarządzaj właścicielami"> + void invalidate()} /> + + + setConfirmOpen(false)} + onConfirm={() => void remove()} + title="Usuń siłownię" + description="Usunąć siłownię? Członkostwa zostaną usunięte, plany użytkowników zachowane." + confirmLabel="Usuń" + danger + busy={busy} + /> ); } -function EquipmentSection({ gym }: { gym: Gym }) { - const queryClient = useQueryClient(); +function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) { const { data: eqData, isLoading } = useQuery({ queryKey: ['equipment'], queryFn: () => api<{ equipment: Equipment[] }>('/admin/equipment'), @@ -317,12 +742,6 @@ function EquipmentSection({ gym }: { gym: Gym }) { const [addId, setAddId] = useState(''); const [addQty, setAddQty] = useState('1'); - const invalidate = () => - Promise.all([ - queryClient.invalidateQueries({ queryKey: ['gyms'] }), - queryClient.invalidateQueries({ queryKey: ['gym', gym.id] }), - ]); - const add = async () => { if (!addId) return; const quantity = parseInt(addQty, 10) || 1; @@ -343,7 +762,7 @@ function EquipmentSection({ gym }: { gym: Gym }) { } setAddId(''); setAddQty('1'); - await invalidate(); + onChanged(); } catch (err) { setError(err instanceof Error ? err.message : 'Błąd'); } finally { @@ -357,7 +776,7 @@ function EquipmentSection({ gym }: { gym: Gym }) { method: 'PATCH', body: { quantity }, }); - await invalidate(); + onChanged(); } catch (err) { alert(err instanceof Error ? err.message : 'Błąd'); } @@ -366,7 +785,7 @@ function EquipmentSection({ gym }: { gym: Gym }) { const remove = async (equipmentId: string) => { try { await api(`/admin/gyms/${gym.id}/equipment/${equipmentId}`, { method: 'DELETE' }); - await invalidate(); + onChanged(); } catch (err) { alert(err instanceof Error ? err.message : 'Błąd'); } @@ -450,180 +869,21 @@ function EquipmentSection({ gym }: { gym: Gym }) { ); } -/* Wyjątki: kompaktowy komposer (data + tryb + godziny) i lista w stylu aplikacji. */ -function ExceptionsBlock({ gymId }: { gymId: string }) { - const queryClient = useQueryClient(); - const { data, isLoading } = useQuery({ - queryKey: ['gym-exceptions', gymId], - queryFn: () => api<{ exceptions: GymException[] }>(`/admin/gyms/${gymId}/exceptions`), - }); - const exceptions = data?.exceptions ?? []; +const PHOTO_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp']; +const MAX_PHOTO_FILES = 10; +const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024; - const [date, setDate] = useState(''); - const [closed, setClosed] = useState(true); - const [start, setStart] = useState('18:00'); - const [end, setEnd] = useState('20:00'); - const [error, setError] = useState(''); - const [busy, setBusy] = useState(false); - - const add = async () => { - setError(''); - setBusy(true); - try { - await api(`/admin/gyms/${gymId}/exceptions`, { - method: 'POST', - body: { date, availability: closed ? null : { start, end } }, - }); - setDate(''); - await queryClient.invalidateQueries({ queryKey: ['gym-exceptions', gymId] }); - } catch (err) { - setError(err instanceof Error ? err.message : 'Błąd'); - } finally { - setBusy(false); - } - }; - - const remove = async (exceptionId: string) => { - try { - await api(`/admin/gyms/${gymId}/exceptions/${exceptionId}`, { method: 'DELETE' }); - await queryClient.invalidateQueries({ queryKey: ['gym-exceptions', gymId] }); - } catch (err) { - alert(err instanceof Error ? err.message : 'Błąd'); - } - }; - - return ( - <> -
-
- Dodaj wyjątek — data i tryb dnia -
- {/* wiersz 1: data + tryb; na wąskich ekranach każde przechodzi na pełną szerokość */} -
- setDate(e.target.value)} - aria-label="Data wyjątku" - className="w-full min-w-0 sm:w-44 sm:flex-none" - required - /> -
- - -
-
- {/* wiersz 2: godziny + akcja; selecty dzielą miejsce po równo, nigdy się nie łamią */} - {!closed && ( -
- - - -
- )} - {closed && ( -
- -
- )} - {error && {error}} -
- - {isLoading ? ( - - ) : ( - exceptions.length > 0 && ( -
- {exceptions.map((ex) => ( -
- - {new Date(ex.date).toLocaleDateString('pl-PL')} - - - {ex.availability - ? `${ex.availability.start}–${ex.availability.end}` - : 'zamknięte'} - - -
- ))} -
- ) - )} - - ); +async function uploadGymPhotos(gymId: string, files: File[]): Promise { + const form = new FormData(); + for (const file of files) form.append('photos', file); + return api(`/gyms/${gymId}/photos`, { method: 'POST', body: form }); } function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) { - const queryClient = useQueryClient(); const photos = gym.photos ?? []; const [error, setError] = useState(''); const [busy, setBusy] = useState(false); - const invalidate = () => { - void queryClient.invalidateQueries({ queryKey: ['gyms'] }); - void queryClient.invalidateQueries({ queryKey: ['gym', gym.id] }); - }; - const onPick = async (e: React.ChangeEvent) => { const files = Array.from(e.target.files ?? []); e.target.value = ''; @@ -644,7 +904,6 @@ function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) try { await uploadGymPhotos(gym.id, valid); onChanged(); - await invalidate(); } catch (err) { setError(err instanceof Error ? err.message : 'Błąd'); } finally { @@ -657,7 +916,6 @@ function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) try { await api(`/gyms/${gym.id}/photos/${photo.id}`, { method: 'DELETE' }); onChanged(); - await invalidate(); } catch (err) { alert(err instanceof Error ? err.message : 'Błąd'); } @@ -667,7 +925,6 @@ function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) try { await api(`/gyms/${gym.id}/photos/${photo.id}/cover`, { method: 'PATCH' }); onChanged(); - await invalidate(); } catch (err) { alert(err instanceof Error ? err.message : 'Błąd'); } @@ -725,7 +982,7 @@ function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void })