Admin: panel silowni jak w apce + wyznaczanie wlasciciela (grupowane menu kontekstowe z modalami, sekcja Wlasciciele)

This commit is contained in:
Tilumca
2026-10-15 00:02:40 +02:00
parent c82465ca69
commit 320682d37f
13 changed files with 973 additions and 268 deletions

View File

@@ -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';

View File

@@ -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<HTMLDivElement>) => {
if (e.currentTarget.contains(e.relatedTarget as Node)) return;
close();
};
return (
<div className="relative" onBlur={handleBlur}>
<div className="flex items-center gap-2 rounded-xl border border-line bg-input px-3 focus-within:border-accent">
<Search className="h-4 w-4 shrink-0 text-dim" />
<input
role="combobox"
aria-expanded={open}
aria-label={ariaLabel}
className="w-full bg-transparent py-2.5 text-[0.95rem] focus:outline-none"
placeholder={selected && !open ? '' : `${ariaLabel}…`}
value={open ? query : selected ? userLabel(selected) : ''}
onChange={(e) => {
setQuery(e.target.value);
setOpen(true);
}}
onFocus={() => setOpen(true)}
/>
{selected && !open && (
<button
type="button"
aria-label="Wyczyść wybór użytkownika"
onClick={() => onChange('')}
className="shrink-0 cursor-pointer text-dim hover:text-ink"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{open && (
<div
role="listbox"
aria-label={listLabel}
className="absolute z-20 mt-1.5 max-h-56 w-full overflow-y-auto rounded-xl border border-line bg-card shadow-xl"
>
{filtered.length === 0 ? (
<div className="px-3.5 py-3 text-[0.875rem] text-dim">
{q ? `Brak użytkowników dla „${query.trim()}”` : emptyLabel}
</div>
) : (
filtered.map((u) => (
<button
key={u.id}
type="button"
role="option"
aria-selected={u.id === value}
onClick={() => {
onChange(u.id);
close();
}}
className={`flex w-full cursor-pointer items-center justify-between gap-3 px-3.5 py-2.5 text-left text-[0.95rem] hover:bg-line/40 ${
u.id === value ? 'font-semibold text-accent-text' : ''
}`}
>
<span className="min-w-0 truncate">{userLabel(u)}</span>
{u.firstName && (
<span className="shrink-0 text-[0.875rem] text-dim">{u.email}</span>
)}
</button>
))
)}
</div>
)}
</div>
);
}

View File

@@ -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 <p className="text-[0.875rem] text-dim">Brak zdjęć.</p>;
}
const [first, ...rest] = photos;
return (
<div className="grid grid-cols-3 gap-2">
<div className="relative col-span-2 row-span-2 overflow-hidden rounded-[10px] border border-line bg-input">
<AuthImage src={first.url} alt={gym.name} className="h-full w-full object-cover" />
</div>
{rest.slice(0, 3).map((p) => (
<div
key={p.id}
className="relative overflow-hidden rounded-[10px] border border-line bg-input"
>
<AuthImage src={p.url} alt={gym.name} className="h-full min-h-20 w-full object-cover" />
</div>
))}
{rest.length > 3 && (
<div className="grid place-items-center rounded-[10px] border border-line bg-input text-[0.8rem] font-extrabold text-accent-text">
+{rest.length - 3} zdjęć
</div>
)}
</div>
);
}
async function uploadGymPhotos(gymId: string, files: File[]): Promise<unknown> {
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 <p className="text-[0.875rem] text-dim">Brak urządzeń.</p>;
}
return (
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
{gym.equipment.map((e) => (
<div
key={e.id}
className="flex items-center justify-between gap-2 rounded-[10px] border border-line bg-card/50 px-3 py-2.5 text-[0.85rem] font-semibold"
>
<span className="min-w-0 truncate">{formatGymEquipment(e)}</span>
</div>
))}
</div>
);
}
/* 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 (
<div className="rounded-xl border border-line bg-input/40 p-3.5">
<div className="mb-2.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
Dodaj wyjątek — data i tryb dnia
</div>
{/* wiersz 1: data + tryb; na wąskich ekranach każde przechodzi na pełną szerokość */}
<div className="flex flex-wrap gap-2.5">
<Input
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
aria-label="Data wyjątku"
className="w-full min-w-0 sm:w-44 sm:flex-none"
required
/>
<div className="flex h-10 w-full items-center gap-1 rounded-[10px] border border-line bg-card p-1 sm:w-auto">
<button
type="button"
aria-pressed={closed}
onClick={() => setClosed(true)}
className={`h-full flex-1 whitespace-nowrap rounded-[10px] px-3 text-[0.8125rem] font-semibold transition-colors sm:flex-none ${
closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
Zamknięte
</button>
<button
type="button"
aria-pressed={!closed}
onClick={() => setClosed(false)}
className={`h-full flex-1 whitespace-nowrap rounded-[10px] px-3 text-[0.8125rem] font-semibold transition-colors sm:flex-none ${
!closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
Inne godziny
</button>
</div>
</div>
{/* wiersz 2: godziny + akcja; selecty dzielą miejsce po równo, nigdy się nie łamią */}
{!closed && (
<div className="mt-2.5 flex flex-wrap items-center gap-2.5">
<Select
value={start}
onChange={(e) => setStart(e.target.value)}
aria-label="Od godziny"
className="min-w-0 flex-1 sm:flex-none sm:basis-28"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
<Select
value={end}
onChange={(e) => setEnd(e.target.value)}
aria-label="Do godziny"
className="min-w-0 flex-1 sm:flex-none sm:basis-28"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
<Button
type="button"
onClick={() => void add()}
disabled={busy || !date}
className="w-full sm:ml-auto sm:w-auto"
>
{busy ? 'Dodawanie…' : 'Dodaj'}
</Button>
</div>
)}
{closed && (
<div className="mt-2.5">
<Button
type="button"
onClick={() => void add()}
disabled={busy || !date}
className="w-full sm:w-auto"
>
{busy ? 'Dodawanie…' : 'Dodaj'}
</Button>
</div>
)}
{error && <ErrorText>{error}</ErrorText>}
</div>
);
}
/* 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 <Loading />;
if (exceptions.length === 0) {
return <p className="text-[0.875rem] text-dim">Brak wyjątków.</p>;
}
return (
<div className="flex flex-col gap-2">
{exceptions.map((ex) => (
<div
key={ex.id}
className="flex items-center gap-3 rounded-[10px] border border-dashed border-danger/40 bg-danger/7 px-3 py-2"
>
<span className="font-display text-[0.85rem] font-bold tabular-nums">
{new Date(ex.date).toLocaleDateString('pl-PL')}
</span>
<span className="min-w-0 flex-1 truncate text-dim text-[0.8125rem]">
{ex.availability ? `${ex.availability.start}–${ex.availability.end}` : 'zamknięte'}
</span>
<Button variant="danger" size="sm" type="button" onClick={() => void remove(ex.id)}>
Usuń
</Button>
</div>
))}
</div>
);
}
/* 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 (
<>
<ExceptionsComposer gymId={gymId} />
{has && (
<div className="mt-4">
<ExceptionsList gymId={gymId} />
</div>
)}
</>
);
}
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 (
<>
<SectionHeader
title="Właściciele (OWNER)"
description="Osoby zarządzające siłownią w aplikacji. Tylko admin może nadać lub odebrać tę rolę."
/>
<div className="divide-y divide-line">
{owners.length === 0 && (
<Muted>Brak właściciela — wyznacz go, aby użytkownik mógł zarządzać siłownią.</Muted>
)}
{owners.map((o) => (
<ListRow
key={o.id}
title={[o.firstName, o.lastName].filter(Boolean).join(' ') || o.email}
meta={o.email}
actions={
<Button
variant="danger"
size="sm"
type="button"
disabled={busy}
onClick={() => void remove(o.id)}
>
Odbierz rolę
</Button>
}
/>
))}
</div>
<div className="mt-4 border-t border-line pt-4">
<H3>Nadaj właściciela</H3>
<div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
<div>
<Label>Użytkownik</Label>
<UserPicker
users={availableUsers}
value={pick}
onChange={setPick}
ariaLabel="Szukaj przyszłego właściciela"
emptyLabel="Brak użytkowników"
/>
</div>
<div className="flex items-end">
<Button variant="secondary" onClick={() => void add()} disabled={!pick || busy}>
{busy ? 'Zapisywanie…' : 'Nadaj właściciela'}
</Button>
</div>
</div>
{error && <ErrorText>{error}</ErrorText>}
</div>
</>
);
}
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 <Loading />;
@@ -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() {
</div>
</div>
{/* DWIE KOLUMNY */}
{/* DWIE KOLUMNY (widok odczytu identyczny jak w apce; edycja w grupach menu) */}
<div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-[1.5fr_1fr]">
<div className="flex min-w-0 flex-col gap-4">
{gym.kind === 'REAL' && (
<Card>
<GallerySection gym={gym} onChanged={() => {}} />
<SectionHeader title="Galeria zdjęć" />
<GalleryMosaic gym={gym} />
</Card>
)}
<Card>
<EquipmentSection key={gym.id} gym={gym} />
</Card>
<Card>
<SectionHeader title="Edycja" />
<GymEditForm
key={gym.id}
gym={gym}
onSaved={() => {
void queryClient.invalidateQueries({ queryKey: ['gyms'] });
void queryClient.invalidateQueries({ queryKey: ['gym', gym.id] });
}}
<SectionHeader
title="Urządzenia"
description="Maszyny i urządzenia dostępne w tej siłowni."
/>
<EquipmentTiles gym={gym} />
</Card>
</div>
@@ -284,7 +661,7 @@ export default function GymDetail() {
<div className="mt-4 mb-2 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
Wyjątki
</div>
<ExceptionsBlock gymId={gym.id} />
<ExceptionsList gymId={gym.id} />
</Card>
<Card>
<SectionHeader title="Dane" />
@@ -295,16 +672,64 @@ export default function GymDetail() {
<b>{gym.isPrivate ? 'tak' : 'nie'}</b>
<span className="text-dim">Pojemność</span>
<b className="font-display tabular-nums">{gym.capacity ?? '—'}</b>
<span className="text-dim">Właściciele</span>
<b>{ownerNames.length > 0 ? ownerNames.join(', ') : '—'}</b>
</div>
</Card>
</div>
</div>
{/* MODALE operacji (otwierane z grup menu kontekstowego) */}
<Modal
open={editOpen}
onClose={() => setEditOpen(false)}
title="Dane, godziny i wyjątki"
className="max-w-2xl"
>
<GymEditForm
key={gym.id}
gym={gym}
onSaved={() => {
void invalidate();
}}
/>
<div className="mt-6 border-t border-line pt-5">
<SectionHeader
title="Wyjątki w harmonogramie"
description="Jednorazowe zmiany na konkretny dzień (zamknięcie lub inne godziny)."
/>
<ExceptionsEditor gymId={gym.id} />
</div>
</Modal>
<Modal open={galleryOpen} onClose={() => setGalleryOpen(false)} title="Zarządzaj galerią">
<GallerySection key={gym.id} gym={gym} onChanged={() => void invalidate()} />
</Modal>
<Modal
open={equipmentOpen}
onClose={() => setEquipmentOpen(false)}
title="Zarządzaj urządzeniami"
>
<EquipmentSection key={gym.id} gym={gym} onChanged={() => void invalidate()} />
</Modal>
<Modal open={ownersOpen} onClose={() => setOwnersOpen(false)} title="Zarządzaj właścicielami">
<OwnersSection key={gym.id} gym={gym} onChanged={() => void invalidate()} />
</Modal>
<ConfirmDialog
open={confirmOpen}
onClose={() => 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 (
<>
<div className="rounded-xl border border-line bg-input/40 p-3.5">
<div className="mb-2.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
Dodaj wyjątek — data i tryb dnia
</div>
{/* wiersz 1: data + tryb; na wąskich ekranach każde przechodzi na pełną szerokość */}
<div className="flex flex-wrap gap-2.5">
<Input
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
aria-label="Data wyjątku"
className="w-full min-w-0 sm:w-44 sm:flex-none"
required
/>
<div className="flex h-10 w-full items-center gap-1 rounded-[10px] border border-line bg-card p-1 sm:w-auto">
<button
type="button"
aria-pressed={closed}
onClick={() => setClosed(true)}
className={`h-full flex-1 whitespace-nowrap rounded-[10px] px-3 text-[0.8125rem] font-semibold transition-colors sm:flex-none ${
closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
Zamknięte
</button>
<button
type="button"
aria-pressed={!closed}
onClick={() => setClosed(false)}
className={`h-full flex-1 whitespace-nowrap rounded-[10px] px-3 text-[0.8125rem] font-semibold transition-colors sm:flex-none ${
!closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
Inne godziny
</button>
</div>
</div>
{/* wiersz 2: godziny + akcja; selecty dzielą miejsce po równo, nigdy się nie łamią */}
{!closed && (
<div className="mt-2.5 flex flex-wrap items-center gap-2.5">
<Select
value={start}
onChange={(e) => setStart(e.target.value)}
aria-label="Od godziny"
className="min-w-0 flex-1 sm:flex-none sm:basis-28"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
<Select
value={end}
onChange={(e) => setEnd(e.target.value)}
aria-label="Do godziny"
className="min-w-0 flex-1 sm:flex-none sm:basis-28"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
<Button
type="button"
onClick={() => void add()}
disabled={busy || !date}
className="w-full sm:ml-auto sm:w-auto"
>
{busy ? 'Dodawanie…' : 'Dodaj'}
</Button>
</div>
)}
{closed && (
<div className="mt-2.5">
<Button
type="button"
onClick={() => void add()}
disabled={busy || !date}
className="w-full sm:w-auto"
>
{busy ? 'Dodawanie…' : 'Dodaj'}
</Button>
</div>
)}
{error && <ErrorText>{error}</ErrorText>}
</div>
{isLoading ? (
<Loading />
) : (
exceptions.length > 0 && (
<div className="mt-3 flex flex-col gap-2">
{exceptions.map((ex) => (
<div
key={ex.id}
className="flex items-center gap-3 rounded-[10px] border border-dashed border-danger/40 bg-danger/7 px-3 py-2"
>
<span className="font-display text-[0.85rem] font-bold tabular-nums">
{new Date(ex.date).toLocaleDateString('pl-PL')}
</span>
<span className="min-w-0 flex-1 truncate text-dim text-[0.8125rem]">
{ex.availability
? `${ex.availability.start}–${ex.availability.end}`
: 'zamknięte'}
</span>
<Button variant="danger" size="sm" type="button" onClick={() => void remove(ex.id)}>
Usuń
</Button>
</div>
))}
</div>
)
)}
</>
);
async function uploadGymPhotos(gymId: string, files: File[]): Promise<unknown> {
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<HTMLInputElement>) => {
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 })
</div>
<div className="mt-4 flex items-center gap-2">
<label className="inline-flex cursor-pointer items-center gap-1.5 rounded-xl border border-line px-3 py-1.5 text-[0.85rem] font-semibold text-dim hover:text-accent-text hover:border-accent">
<ImagePlus className="w-4 h-4" />
<ImageIcon className="w-4 h-4" />
{busy ? 'Wgrywanie…' : 'Dodaj zdjęcia'}
<input
type="file"

View File

@@ -2,16 +2,20 @@ import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../../api/client';
import { BackButton, Button, Card, ErrorText, Field, H1, Input } from '../../components/ui';
import { UserPicker } from '../../components/UserPicker';
import { AvailabilityEditor } from '../../components/AvailabilityEditor';
import { emptyAvailability } from '../../lib/availability';
import { useAdminUsers } from '../users/user-queries';
import type { Availability } from '../../api/types';
import { useTopbar } from '../../topbar';
export default function GymForm() {
useTopbar({ title: 'Siłownie', back: '/gyms' });
const navigate = useNavigate();
const { data: usersData } = useAdminUsers();
const [form, setForm] = useState({
name: '',
ownerId: '',
location: '',
availability: emptyAvailability(),
capacity: '',
@@ -21,6 +25,7 @@ export default function GymForm() {
const submit = async (e: React.FormEvent) => {
e.preventDefault();
if (!form.ownerId) return;
setError('');
setBusy(true);
try {
@@ -31,6 +36,7 @@ export default function GymForm() {
method: 'POST',
body: {
name: form.name,
ownerId: form.ownerId,
location: form.location || null,
availability,
capacity: form.capacity ? parseInt(form.capacity) : null,
@@ -52,13 +58,33 @@ export default function GymForm() {
<form onSubmit={submit}>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="Nazwa">
<Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
<Input
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
required
/>
</Field>
<Field label="Właściciel">
<UserPicker
users={usersData?.users ?? []}
value={form.ownerId}
onChange={(ownerId) => setForm({ ...form, ownerId })}
ariaLabel="Szukaj właściciela"
emptyLabel={usersData ? 'Brak użytkowników' : 'Wczytywanie…'}
/>
</Field>
<Field label="Lokalizacja">
<Input value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} />
<Input
value={form.location}
onChange={(e) => setForm({ ...form, location: e.target.value })}
/>
</Field>
<Field label="Ilość miejsc">
<Input type="number" value={form.capacity} onChange={(e) => setForm({ ...form, capacity: e.target.value })} />
<Input
type="number"
value={form.capacity}
onChange={(e) => setForm({ ...form, capacity: e.target.value })}
/>
</Field>
</div>
<Field label="Dostępność (dzień tygodnia + przedział godzin)">
@@ -67,8 +93,13 @@ export default function GymForm() {
onChange={(availability) => setForm({ ...form, availability })}
/>
</Field>
{!form.ownerId && (
<p className="mb-3 text-[0.875rem] text-dim">
Wyznacz właściciela — otrzyma on rolę OWNER i dostęp do zarządzania siłownią.
</p>
)}
{error && <ErrorText>{error}</ErrorText>}
<Button type="submit" disabled={busy}>
<Button type="submit" disabled={busy || !form.ownerId}>
{busy ? 'Zapisywanie…' : 'Utwórz siłownię'}
</Button>
</form>

View File

@@ -1,8 +1,26 @@
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '../lib/utils';
/** Telefon (<md): panel grupy renderowany płasko w dolnym pasku zamiast akordeonu. */
function useIsMobile() {
const [isMobile, setIsMobile] = useState(
() =>
typeof window !== 'undefined' &&
typeof window.matchMedia === 'function' &&
window.matchMedia('(max-width: 767px)').matches,
);
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
const mql = window.matchMedia('(max-width: 767px)');
const onChange = (e: MediaQueryListEvent) => setIsMobile(e.matches);
mql.addEventListener('change', onChange);
return () => mql.removeEventListener('change', onChange);
}, []);
return isMobile;
}
interface GroupButtonProps {
icon: LucideIcon;
/** aria-label ikony (stabilny selektor e2e). */
@@ -11,6 +29,17 @@ interface GroupButtonProps {
active?: boolean;
open: boolean;
onToggle: () => void;
/**
* Telefon: opcje grupy płasko w dolnym pasku (zawsze widoczne, bez zwijania
* za ikonę) — dla stron, gdzie to główna nawigacja (np. wizard).
* Tablet (md–lg) i PC (lg+) bez zmian.
*/
flatOnMobile?: boolean;
/**
* md+: panel grupy zawsze inline (bez akordeonu od ikonki) — dla stron,
* gdzie akcje to główna nawigacja (np. wizard). Telefon bez zmian.
*/
alwaysInlineFromMd?: boolean;
children: ReactNode;
}
@@ -21,8 +50,20 @@ interface GroupButtonProps {
* (przycisk grupy ukryty).
* Zamykanie: Escape, klik poza grupą (klik w inną grupę ją przełącza).
*/
export function GroupButton({ icon: Icon, label, active, open, onToggle, children }: GroupButtonProps) {
export function GroupButton({
icon: Icon,
label,
active,
open,
onToggle,
flatOnMobile,
alwaysInlineFromMd,
children,
}: GroupButtonProps) {
const ref = useRef<HTMLDivElement>(null);
const isMobile = useIsMobile();
// telefon + flatOnMobile: panel = płaski rząd w dolnym pasku (zawsze widoczny)
const flat = flatOnMobile && isMobile;
useEffect(() => {
if (!open) return;
@@ -42,13 +83,18 @@ export function GroupButton({ icon: Icon, label, active, open, onToggle, childre
return (
<div ref={ref} className="md:relative flex items-center gap-2">
{/* lg+ treść grupy zawsze inline; <lg — akordeon (widać tylko po otwarciu) */}
{/* lg+ (lub md+ przy alwaysInlineFromMd) treść grupy zawsze inline;
md–lg akordeon od ikonki;
telefon: domyślnie panel nad dolnym paskiem (w górę),
flatOnMobile: płaski rząd bezpośrednio w pasku */}
<div
className={cn(
'topbar-expand items-center gap-2',
open ? 'flex' : 'hidden',
'lg:flex',
'max-md:absolute max-md:inset-x-0 max-md:bottom-full max-md:z-50 max-md:flex-col max-md:items-stretch max-md:gap-1.5 max-md:rounded-t-xl max-md:border-t max-md:border-line max-md:bg-card max-md:p-2.5 max-md:shadow-card max-md:animate-none',
flat || open ? 'flex' : 'hidden',
alwaysInlineFromMd ? 'md:flex' : 'lg:flex',
flat
? 'max-md:static max-md:flex-row max-md:items-center max-md:gap-2'
: 'max-md:absolute max-md:inset-x-0 max-md:bottom-full max-md:z-50 max-md:flex-col max-md:items-stretch max-md:gap-1.5 max-md:rounded-t-xl max-md:border-t max-md:border-line max-md:bg-card max-md:p-2.5 max-md:shadow-card max-md:animate-none',
)}
>
{children}
@@ -60,15 +106,27 @@ export function GroupButton({ icon: Icon, label, active, open, onToggle, childre
aria-haspopup="true"
aria-expanded={open}
className={cn(
'relative grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border shadow-card transition-all duration-150 lg:hidden',
'relative grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border shadow-card transition-all duration-150',
// tryb płaski: ikona niepotrzebna na telefonie (akcje płasko w pasku)
// i na lg+ (panel inline); md–lg zostaje akordeon od ikonki;
// alwaysInlineFromMd: ikona niepotrzebna od md+ (panel inline)
alwaysInlineFromMd
? flatOnMobile
? 'hidden'
: 'md:hidden'
: flatOnMobile
? 'max-md:hidden lg:hidden'
: 'lg:hidden',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60',
open
? 'border-accent/55 bg-accent/10 text-accent-text'
: 'border-line bg-card text-dim hover:border-accent/45 hover:text-ink',
)}
>
<Icon className="h-4 w-4" />
{active && <span className="absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full bg-accent" />}
<Icon className="w-4 h-4" />
{active && (
<span className="absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full bg-accent" />
)}
</button>
</div>
);

View File

@@ -1,3 +1,4 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ChevronLeft, Filter, Menu, MoreHorizontal, Plus, Search, X } from 'lucide-react';
import { useTopbarStore } from './store';
@@ -5,7 +6,7 @@ import { useListSearch, type SearchableSection } from '../store/list-search';
import { Button, Input } from '../components/ui';
import { cn } from '../lib/utils';
import { GroupButton } from './GroupButton';
import type { TopbarAction, TopbarGroup } from './types';
import type { TopbarAction } from './types';
const SEARCH_LABELS: Record<SearchableSection, string> = {
gyms: 'Szukaj siłowni',
@@ -31,7 +32,13 @@ function SectionSearchInput({ section }: { section: SearchableSection }) {
);
}
function ActionButton({ action, onNavigate }: { action: TopbarAction; onNavigate: (to: string) => void }) {
function ActionButton({
action,
onNavigate,
}: {
action: TopbarAction;
onNavigate: (to: string) => void;
}) {
const Icon = action.icon;
return (
<Button
@@ -39,6 +46,7 @@ function ActionButton({ action, onNavigate }: { action: TopbarAction; onNavigate
variant={action.variant ?? 'primary'}
disabled={action.disabled}
onClick={() => (action.to ? onNavigate(action.to) : action.onClick?.())}
/* telefon: panel akordeonu rozciąga opcje (items-stretch); tryb płaski — naturalna szerokość */
>
{Icon && <Icon className="w-4 h-4" />}
{action.label}
@@ -46,6 +54,32 @@ function ActionButton({ action, onNavigate }: { action: TopbarAction; onNavigate
);
}
/**
* Telefon: dystans (px) od dołu layout viewportu do dołu *widzialnego* viewportu.
* Gdy otwiera się klawiatura (lub zwija pasek adresu), dolny pasek jest przypinany
* do dolnej krawędzi visualViewport zamiast skakać / znikać za ekranem.
* 0 = pasek zostaje przy dole ekranu (desktop, brak klawiatury).
*/
function useVisualViewportBottom() {
const [bottom, setBottom] = useState(0);
useEffect(() => {
const vv = window.visualViewport;
if (!vv) return;
const update = () => {
const offset = Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop));
setBottom(offset);
};
update();
vv.addEventListener('resize', update);
vv.addEventListener('scroll', update);
return () => {
vv.removeEventListener('resize', update);
vv.removeEventListener('scroll', update);
};
}, []);
return bottom;
}
/**
* Menu kontekstowe otwartej zakładki (jedno menu, trzy zachowania responsywne):
* - PC (lg+): wszystkie opcje rozwinięte inline z automatu (bez akordeonu);
@@ -59,6 +93,8 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
const openGroup = useTopbarStore((s) => s.openGroup);
const setOpenGroup = useTopbarStore((s) => s.setOpenGroup);
const navigate = useNavigate();
// telefon: dolny pasek podąża za widzialnym viewportem (klawiatura / pasek adresu)
const vvBottom = useVisualViewportBottom();
const section = config?.search;
const searchQuery = useListSearch((s) => (section ? s.queries[section] : ''));
@@ -67,12 +103,13 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
const plusActions = actions.filter((a) => a.icon?.displayName === 'Plus');
const otherActions = actions.filter((a) => a.icon?.displayName !== 'Plus');
const hasFilters = config?.dateFilter != null || (config?.filters?.length ?? 0) > 0;
const toggle = (group: TopbarGroup) => setOpenGroup(openGroup === group ? null : group);
const toggle = (group: string) => setOpenGroup(openGroup === group ? null : group);
// X tylko gdy otwarta grupa naprawdę istnieje na tej stronie (stare id z innej
// strony nie może pokazywać zamknięcia „nierozwiniętego” menu)
const presentGroups = new Set<string>();
if (hasFilters) presentGroups.add('filters');
(config?.groups ?? []).forEach((g) => presentGroups.add(`grp:${g.id}`));
if (plusActions.length > 0) presentGroups.add('add');
if (otherActions.length > 0) presentGroups.add('actions');
if (config?.search) presentGroups.add('search');
@@ -98,8 +135,9 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
<div
className={cn(
'flex shrink-0 items-center gap-2 md:flex-wrap md:justify-end',
'max-md:fixed max-md:inset-x-0 max-md:bottom-0 max-md:z-40 max-md:justify-center max-md:gap-2 max-md:border-t max-md:border-line max-md:bg-card max-md:px-3 max-md:py-2',
'max-md:fixed max-md:inset-x-0 max-md:bottom-0 max-md:z-40 max-md:justify-center max-md:gap-2 max-md:border-t max-md:border-line max-md:bg-card max-md:px-3 max-md:pt-2 max-md:pb-[max(0.5rem,env(safe-area-inset-bottom))]',
)}
style={vvBottom > 0 ? { bottom: vvBottom } : undefined}
>
{/* nawigacja (np. Kalendarz) zawsze widoczna, nie jest grupą */}
{config?.navWidget}
@@ -107,7 +145,7 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
{config?.back && (
<button
type="button"
onClick={() => navigate(config.back!)}
onClick={() => (config.onBack ? config.onBack() : navigate(config.back!))}
aria-label="Wstecz"
className="grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border border-line bg-card text-dim shadow-card transition-colors hover:text-ink md:hidden"
>
@@ -128,8 +166,27 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
))}
</GroupButton>
)}
{/* własne grupy tematyczne strony (np. Edycja/Galeria/Urządzenia) */}
{(config?.groups ?? []).map((g) => (
<GroupButton
key={g.id}
icon={g.icon}
label={g.label}
open={openGroup === `grp:${g.id}`}
onToggle={() => toggle(`grp:${g.id}`)}
>
{g.actions.map((action) => (
<ActionButton key={action.label} action={action} onNavigate={navigate} />
))}
</GroupButton>
))}
{plusActions.length > 0 && (
<GroupButton icon={Plus} label="Dodawanie" open={openGroup === 'add'} onToggle={() => toggle('add')}>
<GroupButton
icon={Plus}
label="Dodawanie"
open={openGroup === 'add'}
onToggle={() => toggle('add')}
>
{plusActions.map((action) => (
<ActionButton key={action.label} action={action} onNavigate={navigate} />
))}
@@ -141,6 +198,8 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
label="Akcje"
open={openGroup === 'actions'}
onToggle={() => toggle('actions')}
flatOnMobile={config?.flatActionsMobile}
alwaysInlineFromMd={config?.alwaysInlineActions}
>
{otherActions.map((action) => (
<ActionButton key={action.label} action={action} onNavigate={navigate} />

View File

@@ -1,4 +1,4 @@
export { Topbar } from './Topbar';
export { useTopbar } from './useTopbar';
export { useTopbarStore } from './store';
export type { TopbarAction, TopbarConfig, TopbarGroup } from './types';
export type { TopbarAction, TopbarConfig, TopbarCustomGroup, TopbarGroup } from './types';

View File

@@ -1,16 +1,16 @@
import { create } from 'zustand';
import type { TopbarConfig, TopbarGroup } from './types';
import type { TopbarConfig } from './types';
interface TopbarState {
/** Konfiguracja top menu zarejestrowana przez aktywną stronę (null = brak). */
config: TopbarConfig | null;
/** Otwarta grupa akordeonu (jedna naraz); null = wszystkie zwinięte. */
openGroup: TopbarGroup | null;
openGroup: string | null;
/** Odświeża konfigurację (re-render strony) — nie dotyka otwartej grupy. */
setConfig: (config: TopbarConfig | null) => void;
/** Rejestracja strony (mount): ustawia konfigurację i resetuje grupę (null = czyszczenie). */
registerPage: (config: TopbarConfig | null) => void;
setOpenGroup: (group: TopbarGroup | null) => void;
setOpenGroup: (group: string | null) => void;
}
export const useTopbarStore = create<TopbarState>((set) => ({
@@ -18,6 +18,6 @@ export const useTopbarStore = create<TopbarState>((set) => ({
openGroup: null,
setConfig: (config) => set({ config }),
registerPage: (config) =>
set({ config, openGroup: config ? config.defaultOpenGroup ?? null : null }),
set({ config, openGroup: config ? (config.defaultOpenGroup ?? null) : null }),
setOpenGroup: (group) => set({ openGroup: group }),
}));

View File

@@ -18,6 +18,15 @@ export interface TopbarAction {
disabled?: boolean;
}
/** Własna grupa akordeonu z ikoną (np. Edycja/Galeria) — strona grupuje operacje tematycznie. */
export interface TopbarCustomGroup {
id: string;
/** aria-label ikony grupy. */
label: string;
icon: LucideIcon;
actions: TopbarAction[];
}
/**
* Konfiguracja top menu (nagłówka) dla aktywnej podstrony.
* Każda podstrona deklaruje ją sama (hook useTopbar) — brak centralnej mapy tras.
@@ -31,6 +40,11 @@ export interface TopbarConfig {
* Tablet/PC bez zmian (przycisk „Wstecz” w treści strony).
*/
back?: string;
/**
* Opcjonalny handler „Wstecz” (mobile „<”): strona może przechwycić powrót
* (np. potwierdzenie niezapisanych zmian). Brak handlera = nawigacja do `back`.
*/
onBack?: () => void;
/** Wyszukiwarka listy (store list-search) → grupa 🔍. */
search?: SearchableSection;
/** Filtr po dacie (np. selektor miesiąca) → grupa lejka. */
@@ -43,6 +57,20 @@ export interface TopbarConfig {
navWidget?: ReactNode;
/** Akcje: `icon: Plus` → grupa ➕, reszta → grupa ⋯ (mechaniczna reguła). */
actions?: TopbarAction[];
/**
* Telefon: akcje (grupa ⋯) renderowane płasko w dolnym pasku zamiast
* zwijania za ikonę — dla stron, gdzie akcje to główna nawigacja (np. wizard).
* Tablet (md–lg) i PC (lg+) bez zmian.
*/
flatActionsMobile?: boolean;
/**
* Tablet/PC (md+): akcje (grupa ⋯) zawsze rozwinięte inline w nagłówku
* (bez akordeonu od ikonki) — dla stron, gdzie akcje to główna nawigacja
* (np. wizard). Telefon bez zmian (flatActionsMobile lub akordeon).
*/
alwaysInlineActions?: boolean;
/** Własne grupy tematyczne (ikona + akcje), np. Edycja/Galeria/Urządzenia. */
groups?: TopbarCustomGroup[];
/** Wyjątek od domyślnie-zwiniętego akordeonu: grupa otwarta na starcie strony. */
defaultOpenGroup?: 'actions';
}

View File

@@ -1,11 +1,14 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { render, screen, fireEvent, waitFor, within } 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 GymDetail from '../src/pages/gyms/GymDetail';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import type { Equipment, Gym } from '../src/api/types';
import { Topbar } from '../src/topbar';
import type { Equipment, Gym, User } from '../src/api/types';
const OWNER1 = { id: 'u-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' };
const G1: Gym = {
id: 'g1',
@@ -13,8 +16,12 @@ const G1: Gym = {
location: 'Warszawa',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 50,
kind: 'REAL',
isPrivate: false,
equipment: [],
coverPhoto: null,
_count: { memberships: 12 },
owners: [OWNER1],
};
const EQ1: Equipment = {
@@ -42,6 +49,17 @@ const G1_EQ: Gym = {
equipment: [{ id: 'ge-2', gymId: 'g1', equipmentId: 'eq-2', quantity: 2, equipment: EQ2 }],
};
const U1 = {
id: 'u1',
email: 'jan@fitos.pl',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
isAdmin: false,
} as unknown as User;
type Call = { url: string; method?: string; body?: unknown };
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
@@ -49,11 +67,37 @@ function jsonResponse(status: number, body: unknown) {
});
}
/** Wspólny mock: karta siłowni, katalog, wyjątki, użytkownicy i endpointy właścicieli. */
function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) {
const gym = options.gym ?? G1;
const calls = options.calls ?? [];
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method ?? 'GET';
calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined });
if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] });
if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] });
if (url.includes('/admin/users')) return jsonResponse(200, { users: [U1] });
if (url.includes('/admin/gyms/g1/equipment/eq-2') && method === 'PATCH') {
return jsonResponse(200, { gym: G1_EQ });
}
if (url.includes('/admin/gyms/g1/owners') && method === 'POST') {
return jsonResponse(200, { membership: { gymId: 'g1', roles: ['OWNER'] } });
}
if (url.includes('/admin/gyms/g1/owners') && method === 'DELETE') return jsonResponse(204, {});
if (url.includes('/admin/gyms/g1')) return jsonResponse(200, gym);
throw new Error(`Unexpected fetch: ${method} ${url}`);
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
function renderGymDetail() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/gyms/g1']}>
<QueryClientProvider client={queryClient}>
<Topbar />
<Routes>
<Route path="/gyms/:id" element={<GymDetail />} />
</Routes>
@@ -71,51 +115,76 @@ afterEach(() => {
});
describe('admin GymDetail page', () => {
it('shows gym details and the edit form', async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] });
if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] });
if (url.includes('/admin/gyms/g1')) return jsonResponse(200, G1);
throw new Error(`Unexpected fetch: ${url}`);
});
vi.stubGlobal('fetch', fetchMock);
it('shows read-only details, owners and top-menu groups (app parity)', async () => {
stubGymFetch();
renderGymDetail();
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
expect(screen.getByText('Warszawa')).toBeInTheDocument();
expect(screen.getByText('12 członków')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Zapisz' })).toBeInTheDocument();
// „Usuń siłownię" jest w top menu (menu kontekstowe) — sprawdzamy zarejestrowaną konfigurację
expect(
useTopbarStore.getState().config?.actions?.some((a) => a.label === 'Usuń siłownię'),
).toBe(true);
expect(screen.getByText('Anna Kowalska')).toBeInTheDocument();
// menu kontekstowe: grupy Edycja/Galeria/Urządzenia + admin-only Właściciele
const config = useTopbarStore.getState().config;
expect(config?.groups?.map((g) => g.id)).toEqual(['edit', 'gallery', 'equipment', 'owners']);
expect(config?.actions?.some((a) => a.label === 'Usuń siłownię')).toBe(true);
});
it('adding already-added equipment increases its quantity via PATCH', async () => {
let patchBody: unknown;
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] });
if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] });
if (url.includes('/admin/gyms/g1/equipment/eq-2') && init?.method === 'PATCH') {
patchBody = JSON.parse(String(init.body));
return jsonResponse(200, { gym: G1_EQ });
}
if (url.includes('/admin/gyms/g1')) return jsonResponse(200, G1_EQ);
throw new Error(`Unexpected fetch: ${url}`);
});
vi.stubGlobal('fetch', fetchMock);
it('manages equipment in a modal opened from the „Urządzenia” group', async () => {
const calls = stubGymFetch({ gym: G1_EQ });
renderGymDetail();
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
fireEvent.click(await screen.findByRole('button', { name: 'Zarządzaj urządzeniami' }));
const dialog = await screen.findByRole('dialog');
// select pokazuje cały katalog ze specyfikacją — sprzęt już dodany jest oznaczony bieżącą ilością
expect(
await screen.findByRole('option', { name: 'hantle · 2.5–25 kg (2 szt.)' }),
await within(dialog).findByRole('option', { name: 'hantle · 2.5–25 kg (2 szt.)' }),
).toBeInTheDocument();
fireEvent.change(screen.getByRole('combobox', { name: 'Dodaj urządzenie' }), {
fireEvent.change(within(dialog).getByRole('combobox', { name: 'Dodaj urządzenie' }), {
target: { value: 'eq-2' },
});
fireEvent.click(screen.getByRole('button', { name: 'Dodaj urządzenie' }));
await waitFor(() => expect(patchBody).toEqual({ quantity: 3 }));
fireEvent.click(within(dialog).getByRole('button', { name: 'Dodaj urządzenie' }));
await waitFor(() =>
expect(
calls.find((c) => c.method === 'PATCH' && c.url.includes('/equipment/eq-2')),
).toBeTruthy(),
);
expect(
calls.find((c) => c.method === 'PATCH' && c.url.includes('/equipment/eq-2'))?.body,
).toEqual({ quantity: 3 });
});
it('grants and revokes gym owners via admin-only owner endpoints', async () => {
const calls = stubGymFetch();
renderGymDetail();
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
fireEvent.click(await screen.findByRole('button', { name: 'Zarządzaj właścicielami' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Anna Kowalska')).toBeInTheDocument();
// odebranie roli = DELETE /admin/gyms/:id/owners/:userId
fireEvent.click(within(dialog).getByRole('button', { name: 'Odbierz rolę' }));
await waitFor(() =>
expect(
calls.find((c) => c.method === 'DELETE' && c.url.endsWith('/owners/u-owner')),
).toBeTruthy(),
);
// nadanie roli = POST /admin/gyms/:id/owners { userId }
const picker = within(dialog).getByRole('combobox', { name: 'Szukaj przyszłego właściciela' });
fireEvent.change(picker, { target: { value: 'jan' } });
fireEvent.click(await within(dialog).findByRole('option', { name: /Jan Kowalski/ }));
fireEvent.click(within(dialog).getByRole('button', { name: 'Nadaj właściciela' }));
await waitFor(() =>
expect(
calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners')),
).toBeTruthy(),
);
expect(calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners'))?.body).toEqual({
userId: 'u1',
});
});
});

View File

@@ -27,10 +27,45 @@ test('dodawanie już dodanego sprzętu zwiększa jego ilość', async ({ page })
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
await expect(page.getByText('Dywan ×3')).toBeVisible();
// select pokazuje cały katalog — ponowne dodanie zwiększa ilość
// zarządzanie urządzeniami w modalu z grupy „Urządzenia" menu kontekstowego
await page.getByRole('button', { name: 'Zarządzaj urządzeniami' }).click();
await page.getByRole('combobox', { name: 'Dodaj urządzenie' }).selectOption('eq-2');
await page.getByRole('button', { name: 'Dodaj urządzenie' }).click();
await expect(page.getByText('Dywan ×4')).toBeVisible();
// ilość widoczna zarówno w modalu, jak i na kafelkach urządzenia pod spodem
await expect(page.getByText('Dywan ×4').first()).toBeVisible();
});
test('admin zarządza właścicielami siłowni z menu kontekstowego', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
// właściciel widoczny w sekcji Dane
await expect(page.getByText('Anna Kowalska')).toBeVisible();
// modal Właściciele z grupy w menu kontekstowym
await page.getByRole('button', { name: 'Zarządzaj właścicielami' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('Anna Kowalska')).toBeVisible();
// nadanie roli = POST /admin/gyms/gym-1/owners { userId }
const addReq = page.waitForRequest((req) =>
req.url().includes('/admin/gyms/gym-1/owners') && req.method() === 'POST',
);
await dialog.getByRole('combobox', { name: 'Szukaj przyszłego właściciela' }).fill('jan');
await page.getByRole('option', { name: /Jan Kowalski/ }).click();
await dialog.getByRole('button', { name: 'Nadaj właściciela' }).click();
expect((await addReq).postDataJSON()).toEqual({ userId: 'user-1' });
await expect(dialog.getByText('Jan Kowalski')).toBeVisible();
// odebranie roli = DELETE /admin/gyms/gym-1/owners/:userId
const delReq = page.waitForRequest((req) =>
req.url().includes('/admin/gyms/gym-1/owners/user-owner') && req.method() === 'DELETE',
);
await dialog.getByRole('button', { name: 'Odbierz rolę' }).first().click();
await delReq;
await expect(dialog.getByText('Anna Kowalska')).toHaveCount(0);
});
test('kliknięcie w użytkownika otwiera przegląd profilu (wzór z apki)', async ({ page }) => {

View File

@@ -22,6 +22,9 @@ test('admin zarządza galerią zdjęć siłowni REAL (upload/okładka/usuwanie)'
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
await expect(page.getByRole('heading', { name: 'Galeria zdjęć' })).toBeVisible();
// zarządzanie galerią ukryte w grupie „Galeria" menu kontekstowego — otwórz modal
await page.getByRole('button', { name: 'Zarządzaj galerią' }).click();
// start: 2 zdjęcia, pierwsze jest okładką
const removeBtn = page.getByRole('button', { name: 'Usuń zdjęcie' });
await expect(removeBtn).toHaveCount(2);

View File

@@ -80,6 +80,11 @@ export const TEST_GYM_2: Gym = {
_count: { memberships: 4 },
};
/** Właściciele (OWNER) siłowni gym-1 — tylko w odpowiedzi GET /admin/gyms/gym-1. */
export const TEST_GYM_OWNERS = [
{ id: 'user-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' },
];
/** Wniosek o weryfikację wirtualnej siłowni (PENDING, z dokumentem). */
export const TEST_CLAIM_VERIFICATION: GymClaim = {
id: 'claim-v1',
@@ -287,6 +292,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
// Stateful: galeria zdjęć siłowni REAL (gym-1) — upload/delete/cover.
const gymPhotosState = TEST_GYM_PHOTOS.map((p) => ({ ...p }));
let photoSeq = TEST_GYM_PHOTOS.length;
// Stateful: właściciele siłowni gym-1 — nadawanie/odbieranie roli OWNER.
const gymOwnersState = TEST_GYM_OWNERS.map((o) => ({ ...o }));
const coverOf = (photos: typeof gymPhotosState) =>
photos.length ? `/gyms/gym-1/photos/${photos[0].id}` : null;
const gymDetailBody = () =>
@@ -294,6 +301,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
...TEST_GYM,
equipment: gymEquipmentState,
photos: [...gymPhotosState],
owners: [...gymOwnersState],
coverPhoto: coverOf(gymPhotosState),
});
@@ -388,6 +396,45 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
return route.fulfill({ status: 204 });
});
// Właściciele (OWNER): POST nadaje / DELETE odbiera rolę — stanowo (gymOwnersState).
page.route('**/api/v1/admin/gyms/*/owners**', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = JSON.parse(req.postData() || '{}');
const list = (users as { users?: User[] } | null)?.users ?? [];
const u = list.find((x) => x.id === body.userId);
if (u && !gymOwnersState.some((o) => o.id === u.id)) {
gymOwnersState.push({
id: u.id,
firstName: u.firstName,
lastName: u.lastName,
email: u.email,
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ membership: { gymId: 'gym-1', roles: ['OWNER'] } }),
});
}
if (req.method() === 'DELETE') {
const userId = req.url().match(/owners\/([^/?]+)/)?.[1];
const idx = gymOwnersState.findIndex((o) => o.id === userId);
if (idx >= 0) gymOwnersState.splice(idx, 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405 });
});
// Wyjątki harmonogramu — pusta lista (detail siłowni odświeża widok godzin).
page.route('**/api/v1/admin/gyms/*/exceptions*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ exceptions: [] }),
}),
);
page.route('**/api/v1/admin/users', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(users) }),
);