Admin: konsola sirowni od nowa - panel KPI, godziny i logi w ukladzie dwukolumnowym (LogTable + podstrona Logi), menu czlonka z rolami i wyrzuceniem z powodem, wyszukiwarka w kafelku, lista sirowni bez naglowka, usuwanie bytnosci/heatmapy (unit + e2e)
This commit is contained in:
@@ -11,6 +11,7 @@ import GymBoard from './pages/gyms/GymBoard';
|
||||
import GymGalleryPage from './pages/gyms/GymGalleryPage';
|
||||
import GymEquipmentPage from './pages/gyms/GymEquipmentPage';
|
||||
import GymAnnouncementsPage from './pages/gyms/GymAnnouncementsPage';
|
||||
import GymLogsPage from './pages/gyms/GymLogsPage';
|
||||
import UsersList from './pages/users/UsersList';
|
||||
import UserForm from './pages/users/UserForm';
|
||||
import UserDetail from './pages/users/UserDetail';
|
||||
@@ -53,6 +54,7 @@ export default function App() {
|
||||
<Route path="/gyms/:id/gallery" element={<GymGalleryPage />} />
|
||||
<Route path="/gyms/:id/equipment" element={<GymEquipmentPage />} />
|
||||
<Route path="/gyms/:id/announcements" element={<GymAnnouncementsPage />} />
|
||||
<Route path="/gyms/:id/logs" element={<GymLogsPage />} />
|
||||
<Route path="/users" element={<UsersList />} />
|
||||
<Route path="/users/new" element={<UserForm />} />
|
||||
<Route path="/users/:id" element={<UserDetail />} />
|
||||
|
||||
@@ -1,6 +1,77 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
||||
import { api } from './client';
|
||||
import type { EquipmentUsageRow, GymBoardData, User } from './types';
|
||||
import type {
|
||||
ActivityLogPage,
|
||||
AdminGymListItem,
|
||||
AdminGymMemberPage,
|
||||
AdminGymRelated,
|
||||
EquipmentUsageRow,
|
||||
GymBoardData,
|
||||
GymKind,
|
||||
GymRole,
|
||||
User,
|
||||
} from './types';
|
||||
|
||||
/** Lista siłowni w panelu admina (GET /admin/gyms) — wyszukiwanie i filtr typu po stronie API. */
|
||||
export function useAdminGymList(q: string, kind: '' | GymKind) {
|
||||
return useQuery({
|
||||
queryKey: ['gyms', 'list', q, kind],
|
||||
queryFn: () => {
|
||||
const params = new URLSearchParams();
|
||||
if (q) params.set('q', q);
|
||||
if (kind) params.set('kind', kind);
|
||||
const qs = params.toString();
|
||||
return api<{ gyms: AdminGymListItem[] }>(`/admin/gyms${qs ? `?${qs}` : ''}`);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Logi jednej siłowni (GET /admin/gyms/:id/logs) — audyt operacji powiązanych z siłownią. */
|
||||
export function useGymAuditLogs(gymId: string | undefined, limit: number) {
|
||||
return useQuery({
|
||||
queryKey: ['gym-audit-logs', gymId, limit],
|
||||
queryFn: () => api<ActivityLogPage>(`/admin/gyms/${gymId}/logs?limit=${limit}`),
|
||||
enabled: !!gymId,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Członkowie jednej siłowni (GET /admin/gyms/:id/members) — OWNER najpierw, potem wg
|
||||
* dołączenia; filtry q i roli po stronie API; strony doklejane (load-more).
|
||||
*/
|
||||
export function useGymMembers(
|
||||
gymId: string | undefined,
|
||||
q: string,
|
||||
role: '' | GymRole,
|
||||
limit: number,
|
||||
) {
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['gym-members', gymId, q, role, limit],
|
||||
initialPageParam: 0,
|
||||
queryFn: ({ pageParam }) => {
|
||||
const params = new URLSearchParams();
|
||||
if (q) params.set('q', q);
|
||||
if (role) params.set('role', role);
|
||||
params.set('limit', String(limit));
|
||||
if (pageParam > 0) params.set('offset', String(pageParam));
|
||||
return api<AdminGymMemberPage>(`/admin/gyms/${gymId}/members?${params.toString()}`);
|
||||
},
|
||||
getNextPageParam: (lastPage, allPages) => {
|
||||
const loaded = allPages.reduce((sum, page) => sum + page.members.length, 0);
|
||||
return loaded < lastPage.total ? loaded : undefined;
|
||||
},
|
||||
enabled: !!gymId,
|
||||
});
|
||||
}
|
||||
|
||||
/** Wnioski i zaproszenia powiązane z jedną siłownią (GET /admin/gyms/:id/related). */
|
||||
export function useGymRelated(gymId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['gym-related', gymId],
|
||||
queryFn: () => api<AdminGymRelated>(`/admin/gyms/${gymId}/related`),
|
||||
enabled: !!gymId,
|
||||
});
|
||||
}
|
||||
|
||||
/** Bieżący użytkownik (admin) — profil + członkostwa, jak `useMe` w aplikacji. */
|
||||
export function useMe() {
|
||||
|
||||
@@ -179,6 +179,8 @@ export interface Gym {
|
||||
equipment: GymEquipment[];
|
||||
coverPhoto: string | null;
|
||||
photos?: GymPhoto[];
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
_count?: { memberships: number };
|
||||
/** Właściciele (rola OWNER) — tylko odpowiedź GET /admin/gyms/:id. */
|
||||
owners?: GymOwner[];
|
||||
@@ -191,28 +193,65 @@ export interface GymOwner {
|
||||
email: string;
|
||||
}
|
||||
|
||||
// ---------- bytność (telemetria admina, GET /admin/gyms/occupancy | /admin/gyms/:id/presence-stats) ----------
|
||||
export interface AdminOccupancyRow {
|
||||
gymId: string;
|
||||
/** Wiersz listy siłowni admina (GET /admin/gyms?q=&kind=) — dane administracyjne, bez galerii/urządzeń. */
|
||||
export interface AdminGymListItem {
|
||||
id: string;
|
||||
name: string;
|
||||
location: string | null;
|
||||
addressLine1: string | null;
|
||||
addressLine2: string | null;
|
||||
postalCode: string | null;
|
||||
city: string | null;
|
||||
countryCode: string | null;
|
||||
availability: Availability | null;
|
||||
capacity: number | null;
|
||||
count: number;
|
||||
kind: GymKind;
|
||||
isPrivate: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
_count: { memberships: number };
|
||||
owners: GymOwner[];
|
||||
}
|
||||
|
||||
export interface GymPresenceStatsData {
|
||||
visits: number;
|
||||
avgStayMinutes: number | null;
|
||||
heatmap: { day: number; hour: number; count: number }[];
|
||||
topGyms: { gymId: string; gymName: string; visits: number }[];
|
||||
peak: number;
|
||||
topEquipment: { equipmentId: string; name: string; nameEn: string | null; count: number }[];
|
||||
live: number;
|
||||
visitsPerDay: number;
|
||||
export interface AdminMemberUser {
|
||||
id: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
email: string;
|
||||
status: 'ACTIVE' | 'SUSPENDED' | 'BANNED';
|
||||
}
|
||||
|
||||
export interface GymPresenceStatsResponse {
|
||||
gym: { id: string; name: string; kind: GymKind; capacity: number | null };
|
||||
stats: GymPresenceStatsData;
|
||||
/** Wiersz listy członków siłowni (GET /admin/gyms/:id/members). */
|
||||
export interface AdminGymMemberItem {
|
||||
membershipId: string;
|
||||
roles: string[];
|
||||
joinedAt: string;
|
||||
checkedInNow: boolean;
|
||||
user: AdminMemberUser;
|
||||
}
|
||||
|
||||
export interface AdminGymMemberPage {
|
||||
members: AdminGymMemberItem[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** Wnioski i zaproszenia jednej siłowni (GET /admin/gyms/:id/related). */
|
||||
export interface AdminGymRelated {
|
||||
claims: {
|
||||
id: string;
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED';
|
||||
createdAt: string;
|
||||
user: GymOwner;
|
||||
documentCount: number;
|
||||
}[];
|
||||
invitations: {
|
||||
id: string;
|
||||
status: 'PENDING' | 'ACCEPTED' | 'DECLINED' | 'EXPIRED';
|
||||
invitedAt: string;
|
||||
expiresAt: string;
|
||||
user: GymOwner;
|
||||
invitedBy: GymOwner;
|
||||
}[];
|
||||
}
|
||||
|
||||
/** Wiersz rankingu tablicy (GET /gyms/:id/board) — skuteczne sesje w zakresie. */
|
||||
|
||||
150
admin/src/components/LogTable.tsx
Normal file
150
admin/src/components/LogTable.tsx
Normal file
@@ -0,0 +1,150 @@
|
||||
import type { ActivityLog } from '../api/types';
|
||||
import { Badge, type BadgeColor } from './ui';
|
||||
import i18n from '../i18n';
|
||||
import { fmtDate, fmtDateTime, fmtTime } from '../lib/format';
|
||||
|
||||
const t = (key: string, options?: Record<string, unknown>): string =>
|
||||
String(i18n.t(`logs:${key}`, options as never));
|
||||
|
||||
export function actionLabel(action: string) {
|
||||
return t(`actions.${action}`, { defaultValue: action });
|
||||
}
|
||||
|
||||
export function actionColor(action: string): BadgeColor {
|
||||
if (action.startsWith('plan.')) return 'blue';
|
||||
if (action.startsWith('session.')) return 'green';
|
||||
if (action.startsWith('gym.')) return 'gray';
|
||||
if (action.startsWith('coaching.')) return 'red';
|
||||
// akcje security konta — tak samo wyraźne jak relacje trenerskie
|
||||
if (action.startsWith('user.')) return 'red';
|
||||
if (action.startsWith('membership.')) return 'blue';
|
||||
return 'yellow';
|
||||
}
|
||||
|
||||
export function formatLogDate(iso: string) {
|
||||
return fmtDateTime(iso);
|
||||
}
|
||||
|
||||
export function actorName(log: ActivityLog) {
|
||||
const { firstName, lastName, email } = log.actor;
|
||||
return [firstName, lastName].filter(Boolean).join(' ') || email;
|
||||
}
|
||||
|
||||
/** Nazwa obiektu z szczegółów wpisu (tytuł planu, nazwa siłowni, nazwa obwodu). */
|
||||
function entityName(log: ActivityLog) {
|
||||
const d = log.details;
|
||||
if (!d) return null;
|
||||
return (d.title ?? d.name ?? d.gymName ?? null) as string | null;
|
||||
}
|
||||
|
||||
/** Klucze pokazywane w innych kolumnach (aktor w „Użytkownik", nazwa w „Obiekt"). */
|
||||
const HIDDEN_DETAIL_KEYS = new Set(['actorId', 'title', 'name', 'gymName']);
|
||||
|
||||
function formatDetailValue(log: ActivityLog, key: string, value: unknown): string {
|
||||
if (Array.isArray(value)) return value.map((v) => String(v)).join(', ');
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.entries(value)
|
||||
.map(([k, v]) => `${k}: ${formatDetailValue(log, k, v)}`)
|
||||
.join(', ');
|
||||
}
|
||||
let text = String(value);
|
||||
if (key === 'value' && typeof value === 'number') {
|
||||
const unit =
|
||||
log.action === 'weight.added' || log.action === 'weight.removed'
|
||||
? ' kg'
|
||||
: log.action === 'circumference.added' || log.action === 'circumference.removed'
|
||||
? ' cm'
|
||||
: '';
|
||||
text += unit;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/** Szczegóły wpisu jako linie: `start: 2026-08-24`, `wartość: 82.5 kg` — jedna pod drugą. */
|
||||
export function detailsLines(log: ActivityLog): string[] {
|
||||
const d = log.details;
|
||||
if (!d) return [];
|
||||
return Object.entries(d)
|
||||
.filter(([k]) => !HIDDEN_DETAIL_KEYS.has(k))
|
||||
.map(([k, v]) => `${t(`details.${k}`, { defaultValue: k })}: ${formatDetailValue(log, k, v)}`);
|
||||
}
|
||||
|
||||
/** Szczegóły jako jeden tekst: `start: 2026-08-24 · wartość: 82.5 kg`. */
|
||||
export function detailsText(log: ActivityLog) {
|
||||
const parts = detailsLines(log);
|
||||
return parts.length > 0 ? parts.join(' · ') : null;
|
||||
}
|
||||
|
||||
/** Tabela logów aktywności (wspólny rendering: globalne logi i logi pojedynczej siłowni). */
|
||||
export function LogTable({ logs }: { logs: ActivityLog[] }) {
|
||||
return (
|
||||
<div className="overflow-x-auto rounded-[10px] border border-line bg-(image:--card-grad) shadow-card">
|
||||
<table className="w-full text-[0.95rem]">
|
||||
<thead>
|
||||
<tr className="border-b border-line text-left text-dim">
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colDate')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colUser')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colAction')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colEntity')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colDetails')}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{logs.map((log) => (
|
||||
<tr
|
||||
key={log.id}
|
||||
className="border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20"
|
||||
>
|
||||
<td className="px-4 py-3 align-top font-display text-dim tabular-nums">
|
||||
<div className="whitespace-nowrap">{fmtDate(log.createdAt)}</div>
|
||||
<div className="whitespace-nowrap text-[0.875rem]">{fmtTime(log.createdAt)}</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-semibold">{actorName(log)}</div>
|
||||
<div className="text-[0.875rem] text-dim">{log.actor.email}</div>
|
||||
<div className="font-mono text-[0.75rem] text-dim/70" title={log.actor.id}>
|
||||
{log.actor.id}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top">
|
||||
<Badge
|
||||
color={actionColor(log.action)}
|
||||
className="h-auto max-w-[13rem] whitespace-normal"
|
||||
>
|
||||
{actionLabel(log.action)}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div>{t(`entities.${log.entityType}`, { defaultValue: log.entityType })}</div>
|
||||
{entityName(log) && (
|
||||
<div className="text-[0.875rem] text-dim">{entityName(log)}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-dim">
|
||||
{detailsLines(log).length > 0 ? (
|
||||
<div className="space-y-1">
|
||||
{detailsLines(log).map((line) => (
|
||||
<div key={line}>{line}</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
111
admin/src/components/gyms/AnnouncementsSection.tsx
Normal file
111
admin/src/components/gyms/AnnouncementsSection.tsx
Normal file
@@ -0,0 +1,111 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '../../api/client';
|
||||
import { Button, ErrorText, Field, Input, Loading, Muted, Textarea } from '../ui';
|
||||
import type { AdminAnnouncement, Gym } from '../../api/types';
|
||||
|
||||
/** Awaryjne ogłoszenia w imieniu siłowni (gdy właściciel nie może sam). */
|
||||
export function GymAnnouncementsSection({ gym }: { gym: Gym }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
const queryClient = useQueryClient();
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['admin-announcements', gym.id],
|
||||
queryFn: () =>
|
||||
api<{ announcements: AdminAnnouncement[] }>(
|
||||
`/admin/announcements?gymId=${encodeURIComponent(gym.id)}`,
|
||||
),
|
||||
});
|
||||
const announcements = data?.announcements ?? [];
|
||||
const [title, setTitle] = useState('');
|
||||
const [body, setBody] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const add = async () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api('/admin/announcements', {
|
||||
method: 'POST',
|
||||
body: { title: title.trim(), body: body.trim(), gymId: gym.id },
|
||||
});
|
||||
setTitle('');
|
||||
setBody('');
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-announcements', gym.id] });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t('common:error'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: string) => {
|
||||
setError(null);
|
||||
try {
|
||||
await api(`/admin/announcements/${id}`, { method: 'DELETE' });
|
||||
await queryClient.invalidateQueries({ queryKey: ['admin-announcements', gym.id] });
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t('common:error'));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-col gap-2.5 rounded-xl border border-line bg-input/40 p-3.5">
|
||||
<Muted className="block">{t('announcementSendTo', { name: gym.name })}</Muted>
|
||||
<Field label={t('announcementTitleLabel')}>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
maxLength={120}
|
||||
placeholder={t('announcementTitlePh')}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t('announcementBodyLabel')}>
|
||||
<Textarea
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
placeholder={t('announcementBodyPh')}
|
||||
/>
|
||||
</Field>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
<div>
|
||||
<Button onClick={() => void add()} disabled={busy || !title.trim() || !body.trim()}>
|
||||
{busy ? t('publishing') : t('publish')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
{isLoading ? (
|
||||
<Loading />
|
||||
) : announcements.length === 0 ? (
|
||||
<Muted className="block">{t('noAnnouncements')}</Muted>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{announcements.map((a) => (
|
||||
<div key={a.id} className="rounded-[10px] border border-line bg-card/50 px-3 py-2.5">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="min-w-0 truncate text-[0.9rem] font-bold">{a.title}</span>
|
||||
{a.kind === 'MANUAL' && (
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => void remove(a.id)}
|
||||
aria-label={t('removeAria', { name: a.title })}
|
||||
>
|
||||
{t('common:remove')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 whitespace-pre-wrap text-dim text-[0.8125rem]">{a.body}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
299
admin/src/components/gyms/EquipmentSection.tsx
Normal file
299
admin/src/components/gyms/EquipmentSection.tsx
Normal file
@@ -0,0 +1,299 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Trash2 } from 'lucide-react';
|
||||
import { api } from '../../api/client';
|
||||
import type { Equipment, EquipmentSpec, Gym } from '../../api/types';
|
||||
import {
|
||||
EMPTY_SPEC_FIELDS,
|
||||
LOAD_RANGE_KINDS,
|
||||
MAX_LOAD_KINDS,
|
||||
formatGymEquipment,
|
||||
hasSpecFields,
|
||||
specFromFields,
|
||||
type SpecFields,
|
||||
} from '../../lib/equipment';
|
||||
import { localizedName } from '../../lib/localizedName';
|
||||
import { Button, ErrorText, Field, Input, Loading, Select } from '../../components/ui';
|
||||
|
||||
/** Pola specyfikacji zależne od rodzaju urządzenia (wzorzec: katalog admina). */
|
||||
function AddSpecFields({
|
||||
kind,
|
||||
values,
|
||||
onChange,
|
||||
}: {
|
||||
kind: Equipment['kind'];
|
||||
values: SpecFields;
|
||||
onChange: (patch: Partial<SpecFields>) => void;
|
||||
}) {
|
||||
const { t } = useTranslation('gyms');
|
||||
if (LOAD_RANGE_KINDS.includes(kind)) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<Field label={t('minLoad')}>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={500}
|
||||
step="any"
|
||||
aria-label={t('minLoad')}
|
||||
value={values.minKg}
|
||||
onChange={(e) => onChange({ minKg: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t('maxLoad')}>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={500}
|
||||
step="any"
|
||||
aria-label={t('maxLoad')}
|
||||
value={values.maxKg}
|
||||
onChange={(e) => onChange({ maxKg: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (MAX_LOAD_KINDS.includes(kind)) {
|
||||
return (
|
||||
<Field label={t('maxLoadFull')}>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={1000}
|
||||
step="any"
|
||||
aria-label={t('maxLoadFull')}
|
||||
value={values.maxLoadKg}
|
||||
onChange={(e) => onChange({ maxLoadKg: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
if (kind === 'CARDIO') {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<Field label={t('maxSpeed')}>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={50}
|
||||
step="any"
|
||||
aria-label={t('maxSpeed')}
|
||||
value={values.maxSpeedKmh}
|
||||
onChange={(e) => onChange({ maxSpeedKmh: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t('maxIncline')}>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={40}
|
||||
step="any"
|
||||
aria-label={t('maxIncline')}
|
||||
value={values.maxInclinePct}
|
||||
onChange={(e) => onChange({ maxInclinePct: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
const { i18n } = useTranslation();
|
||||
const { data: eqData, isLoading } = useQuery({
|
||||
queryKey: ['equipment'],
|
||||
queryFn: () => api<{ equipment: Equipment[] }>('/admin/equipment'),
|
||||
});
|
||||
const catalog = eqData?.equipment ?? [];
|
||||
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [addId, setAddId] = useState('');
|
||||
const [addQty, setAddQty] = useState('1');
|
||||
const [addFields, setAddFields] = useState<SpecFields>(EMPTY_SPEC_FIELDS);
|
||||
|
||||
const addItem = catalog.find((e) => e.id === addId) ?? null;
|
||||
|
||||
// Parametry każdej pozycji admin wpisuje zawsze sam — bez podpowiedzi z katalogu.
|
||||
const selectAdd = (id: string) => {
|
||||
setAddId(id);
|
||||
setAddFields(EMPTY_SPEC_FIELDS);
|
||||
setError('');
|
||||
};
|
||||
|
||||
const add = async () => {
|
||||
if (!addItem) return;
|
||||
const quantity = parseInt(addQty, 10) || 1;
|
||||
setError('');
|
||||
let spec: EquipmentSpec | null = null;
|
||||
if (hasSpecFields(addItem.kind)) {
|
||||
const result = specFromFields(addItem.kind, addFields);
|
||||
if ('error' in result) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
if (result.spec == null) {
|
||||
setError(t('specRequired'));
|
||||
return;
|
||||
}
|
||||
spec = result.spec;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/admin/gyms/${gym.id}/equipment`, {
|
||||
method: 'POST',
|
||||
body: { equipmentId: addItem.id, quantity, ...(spec ? { spec } : {}) },
|
||||
});
|
||||
setAddId('');
|
||||
setAddQty('1');
|
||||
setAddFields(EMPTY_SPEC_FIELDS);
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t('common:error'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const changeQty = async (instanceId: string, quantity: number) => {
|
||||
try {
|
||||
await api(`/admin/gyms/${gym.id}/equipment/${instanceId}`, {
|
||||
method: 'PATCH',
|
||||
body: { quantity },
|
||||
});
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : t('common:error'));
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (instanceId: string) => {
|
||||
try {
|
||||
await api(`/admin/gyms/${gym.id}/equipment/${instanceId}`, { method: 'DELETE' });
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : t('common:error'));
|
||||
}
|
||||
};
|
||||
|
||||
const totalQty = (equipmentId: string) =>
|
||||
gym.equipment
|
||||
.filter((e) => e.equipmentId === equipmentId)
|
||||
.reduce((sum, e) => sum + e.quantity, 0);
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* POZYCJE NA STANIE: wiersz = nazwa/spec + ilość + usuwanie */}
|
||||
<div>
|
||||
<div className="mb-2 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
|
||||
{t('positionsInStock', { count: gym.equipment.length })}
|
||||
</div>
|
||||
{gym.equipment.length === 0 ? (
|
||||
<div className="rounded-[10px] border border-dashed border-line px-4 py-6 text-center text-[0.875rem] text-dim">
|
||||
{t('noStockDesc')}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{gym.equipment.map((e) => (
|
||||
<div
|
||||
key={e.id}
|
||||
className="flex items-center gap-2.5 rounded-[10px] border border-line bg-card/50 px-3 py-2"
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-semibold">
|
||||
{formatGymEquipment(e, i18n.language)}
|
||||
</span>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={10000}
|
||||
defaultValue={e.quantity}
|
||||
aria-label={t('qtyAria', { name: localizedName(e.equipment, i18n.language) })}
|
||||
className="w-16 shrink-0 rounded-[10px] border border-line bg-input px-2 py-1 text-center text-[0.875rem] text-ink focus:border-accent-text focus:outline-none"
|
||||
onBlur={(ev) => {
|
||||
const value = parseInt(ev.target.value, 10);
|
||||
if (Number.isFinite(value) && value >= 1 && value !== e.quantity) {
|
||||
void changeQty(e.id, value);
|
||||
} else {
|
||||
ev.target.value = String(e.quantity);
|
||||
}
|
||||
}}
|
||||
onKeyDown={(ev) => {
|
||||
if (ev.key === 'Enter') (ev.target as HTMLInputElement).blur();
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void remove(e.id)}
|
||||
aria-label={t('removeAria', { name: localizedName(e.equipment, i18n.language) })}
|
||||
title={t('removeAria', { name: localizedName(e.equipment, i18n.language) })}
|
||||
className="shrink-0 cursor-pointer rounded-lg p-1.5 text-dim transition-colors hover:bg-danger/10 hover:text-danger"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* DODAWANIE z katalogu: pozycja zawsze z własnymi parametrami (zdjęcia pozycji zarządza właściciel w apce) */}
|
||||
<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">
|
||||
{t('addFromCatalog')}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-end gap-2.5">
|
||||
<div className="min-w-0 flex-1 basis-52">
|
||||
<Select
|
||||
value={addId}
|
||||
onChange={(e) => selectAdd(e.target.value)}
|
||||
aria-label={t('addDeviceAria')}
|
||||
>
|
||||
<option value="">{t('chooseDevice')}</option>
|
||||
{catalog.map((e) => {
|
||||
const qty = totalQty(e.id);
|
||||
return (
|
||||
<option key={e.id} value={e.id}>
|
||||
{localizedName(e, i18n.language)}
|
||||
{qty > 0 ? ` ${t('inStockOption', { count: qty })}` : ''}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</Select>
|
||||
</div>
|
||||
<Field label={t('qty')} className="w-20 shrink-0">
|
||||
<Input
|
||||
type="number"
|
||||
size="sm"
|
||||
min={1}
|
||||
max={10000}
|
||||
value={addQty}
|
||||
onChange={(e) => setAddQty(e.target.value)}
|
||||
aria-label={t('qty')}
|
||||
/>
|
||||
</Field>
|
||||
<Button onClick={add} disabled={!addId || busy} className="shrink-0">
|
||||
{busy ? t('adding') : t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
{addItem && hasSpecFields(addItem.kind) && (
|
||||
<div className="mt-3.5 border-t border-line pt-3.5">
|
||||
<div className="mb-2 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
|
||||
{t('parameters')}
|
||||
</div>
|
||||
<AddSpecFields
|
||||
kind={addItem.kind}
|
||||
values={addFields}
|
||||
onChange={(patch) => setAddFields({ ...addFields, ...patch })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
{isLoading && <Loading />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
192
admin/src/components/gyms/ExceptionsBlock.tsx
Normal file
192
admin/src/components/gyms/ExceptionsBlock.tsx
Normal file
@@ -0,0 +1,192 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '../../api/client';
|
||||
import { Button, ErrorText, Input, Loading, Select } from '../ui';
|
||||
import { TIME_SLOTS } from '../../lib/availability';
|
||||
import { fmtDate } from '../../lib/format';
|
||||
import type { GymException } from '../../api/types';
|
||||
|
||||
/** Wyjątki (admin): komposer (data + tryb + godziny) — jak w apce. */
|
||||
export function ExceptionsComposer({ gymId }: { gymId: string }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
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 : t('common:error'));
|
||||
} 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">
|
||||
{t('addExceptionTitle')}
|
||||
</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={t('exceptionDateAria')}
|
||||
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'
|
||||
}`}
|
||||
>
|
||||
{t('closedBtn')}
|
||||
</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'
|
||||
}`}
|
||||
>
|
||||
{t('otherHours')}
|
||||
</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={t('fromHourAria')}
|
||||
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={t('toHourAria')}
|
||||
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 ? t('adding') : t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{closed && (
|
||||
<div className="mt-2.5">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => void add()}
|
||||
disabled={busy || !date}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{busy ? t('adding') : t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Lista wyjątków z usuwaniem (admin może zarządzać każdym dniem). */
|
||||
export function ExceptionsList({ gymId }: { gymId: string }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
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 : t('common:error'));
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) return <Loading />;
|
||||
if (exceptions.length === 0) {
|
||||
return <p className="text-[0.875rem] text-dim">{t('noExceptions')}</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">
|
||||
{fmtDate(ex.date)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-dim text-[0.8125rem]">
|
||||
{ex.availability ? `${ex.availability.start}–${ex.availability.end}` : t('closed')}
|
||||
</span>
|
||||
<Button variant="danger" size="sm" type="button" onClick={() => void remove(ex.id)}>
|
||||
{t('common:remove')}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Komposer + lista istniejących wyjątków (modal „Informacje", jak w apce). */
|
||||
export 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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
135
admin/src/components/gyms/GallerySection.tsx
Normal file
135
admin/src/components/gyms/GallerySection.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Image as ImageIcon, Star, X } from 'lucide-react';
|
||||
import { api } from '../../api/client';
|
||||
import { AuthImage } from '../AuthImage';
|
||||
import { ErrorText, SectionHeader } from '../ui';
|
||||
import type { Gym, GymPhoto } from '../../api/types';
|
||||
|
||||
const PHOTO_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
|
||||
const MAX_PHOTO_FILES = 10;
|
||||
const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024;
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
export function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
const photos = gym.photos ?? [];
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const onPick = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files ?? []);
|
||||
e.target.value = '';
|
||||
if (files.length === 0) return;
|
||||
const valid = files.filter(
|
||||
(f) => PHOTO_MIME_TYPES.includes(f.type) && f.size <= MAX_PHOTO_FILE_SIZE,
|
||||
);
|
||||
if (valid.length === 0) {
|
||||
setError(t('photoTypesError'));
|
||||
return;
|
||||
}
|
||||
if (valid.length > MAX_PHOTO_FILES) {
|
||||
setError(t('photoMaxFilesError', { count: MAX_PHOTO_FILES }));
|
||||
return;
|
||||
}
|
||||
setError('');
|
||||
setBusy(true);
|
||||
try {
|
||||
await uploadGymPhotos(gym.id, valid);
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : t('common:error'));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (photo: GymPhoto) => {
|
||||
if (!confirm(t('confirmDeletePhoto'))) return;
|
||||
try {
|
||||
await api(`/gyms/${gym.id}/photos/${photo.id}`, { method: 'DELETE' });
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : t('common:error'));
|
||||
}
|
||||
};
|
||||
|
||||
const setCover = async (photo: GymPhoto) => {
|
||||
try {
|
||||
await api(`/gyms/${gym.id}/photos/${photo.id}/cover`, { method: 'PATCH' });
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : t('common:error'));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<SectionHeader title={t('gallerySection')} description={t('galleryDesc')} />
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||
{photos.length === 0 && (
|
||||
<span className="col-span-full text-[0.875rem] text-dim">{t('noPhotos')}</span>
|
||||
)}
|
||||
{photos.map((photo, i) => (
|
||||
<div key={photo.id} className="relative overflow-hidden rounded-xl border border-line">
|
||||
<AuthImage
|
||||
src={photo.url}
|
||||
alt={t('photoAlt', { n: i + 1 })}
|
||||
className="h-32 w-full object-cover"
|
||||
/>
|
||||
{i === 0 && (
|
||||
<span className="absolute left-1.5 top-1.5 rounded-md bg-black/70 px-1.5 py-0.5 text-[0.7rem] font-semibold text-white">
|
||||
{t('coverBadge')}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex items-center justify-between gap-1 bg-card p-1.5">
|
||||
{i === 0 ? (
|
||||
<span className="inline-flex items-center gap-1 text-[0.75rem] text-dim">
|
||||
<Star className="w-3.5 h-3.5 fill-accent text-accent-text" />
|
||||
{t('coverLabel')}
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCover(photo)}
|
||||
className="inline-flex items-center gap-1 text-[0.75rem] text-dim hover:text-accent-text cursor-pointer"
|
||||
>
|
||||
<Star className="w-3.5 h-3.5" />
|
||||
{t('setCover')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => remove(photo)}
|
||||
aria-label={t('removePhotoAria')}
|
||||
className="text-dim hover:text-danger cursor-pointer"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</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">
|
||||
<ImageIcon className="w-4 w-4" />
|
||||
{busy ? t('uploading') : t('addPhotos')}
|
||||
<input
|
||||
type="file"
|
||||
accept={PHOTO_MIME_TYPES.join(',')}
|
||||
multiple
|
||||
hidden
|
||||
onChange={onPick}
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { dayName } from '../../lib/format';
|
||||
import { dayShort } from '../../lib/availability';
|
||||
|
||||
export interface PresenceHeatCell {
|
||||
day: number;
|
||||
hour: number;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/* Mapa ciepła bytności 7 (dzień 0=pon) × 24 (godzina) — natężenie ~ udział w szczycie,
|
||||
styl kafli jak mapa urządzeń. Lustrzana kopia komponentu z app (identyczny widok
|
||||
w obu pakietach). Etykiety dni skrócone (pełna nazwa w tytulu wiersza), siatka
|
||||
skaluje się do szerokosci kolumny — bez minimalnej szerokosci i przewijania. */
|
||||
export function PresenceHeatmapGrid({ cells }: { cells: PresenceHeatCell[] }) {
|
||||
const max = cells.reduce((m, c) => Math.max(m, c.count), 0);
|
||||
return (
|
||||
<div className="min-w-0">
|
||||
<div
|
||||
className="grid gap-[3px]"
|
||||
style={{ gridTemplateColumns: 'minmax(2.4rem, 3.4rem) repeat(24, minmax(0, 1fr))' }}
|
||||
>
|
||||
<span />
|
||||
{Array.from({ length: 24 }, (_, hour) => (
|
||||
<span
|
||||
key={hour}
|
||||
className="min-w-0 truncate text-center text-[0.6rem] font-bold tabular-nums text-dim"
|
||||
>
|
||||
{hour % 3 === 0 ? String(hour).padStart(2, '0') : ''}
|
||||
</span>
|
||||
))}
|
||||
{Array.from({ length: 7 }, (_, day) => (
|
||||
<HeatmapRow key={day} day={day} cells={cells} max={max} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HeatmapRow({ day, cells, max }: { day: number; cells: PresenceHeatCell[]; max: number }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
return (
|
||||
<>
|
||||
<span
|
||||
title={dayName(day + 1)}
|
||||
className="flex min-w-0 items-center pr-1 text-[0.68rem] font-semibold text-dim"
|
||||
>
|
||||
<span className="truncate">{dayShort(day)}</span>
|
||||
</span>
|
||||
{Array.from({ length: 24 }, (_, hour) => {
|
||||
const cell = cells.find((c) => c.day === day && c.hour === hour);
|
||||
const count = cell?.count ?? 0;
|
||||
const intensity = max > 0 ? count / max : 0;
|
||||
return (
|
||||
<span
|
||||
key={hour}
|
||||
title={t('stats.cellTitle', {
|
||||
day: dayName(day + 1),
|
||||
hour: String(hour).padStart(2, '0'),
|
||||
count,
|
||||
})}
|
||||
className="aspect-square rounded-[2px] border border-line/40"
|
||||
style={{
|
||||
background:
|
||||
intensity > 0
|
||||
? `color-mix(in srgb, var(--accent) ${Math.round(18 + intensity * 82)}%, var(--bg-input))`
|
||||
: 'var(--bg-input)',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -30,14 +30,91 @@
|
||||
"virtual": "Virtual",
|
||||
"private": "Private",
|
||||
"open": "Open →",
|
||||
"allGyms": "All gyms",
|
||||
"newGym": "New gym",
|
||||
"noResults": "No results",
|
||||
"noResultsDesc": "No results for the given query.",
|
||||
"noGymsTitle": "No gyms",
|
||||
"noGymsDesc": "No gyms yet. Add the first one using “New gym” in the context menu.",
|
||||
"colName": "Name",
|
||||
"colLocation": "Location",
|
||||
"colOwners": "Owners",
|
||||
"colMembers": "Members",
|
||||
"colOpenToday": "Today",
|
||||
"colCreatedAt": "Created",
|
||||
"closedToday": "closed",
|
||||
"noOwners": "none",
|
||||
"ownersMore_one": "+{{count}} other",
|
||||
"ownersMore_few": "+{{count}} others",
|
||||
"ownersMore_many": "+{{count}} others",
|
||||
"ownersMore_other": "+{{count}} others",
|
||||
"openInApp": "Open in app",
|
||||
"filterKindAria": "Gym kind filter",
|
||||
"filterKindAll": "All kinds",
|
||||
"kindReal": "Real",
|
||||
"logsTile": {
|
||||
"title": "Logs",
|
||||
"hint": "Gym audit"
|
||||
},
|
||||
"groupLogs": "Logs",
|
||||
"logsPage": {
|
||||
"title": "Gym logs",
|
||||
"subtitle": "Operations on the gym, its members, claims and invitations",
|
||||
"emptyTitle": "No logs",
|
||||
"emptyDesc": "No operations tied to this gym.",
|
||||
"showMore_one": "Show {{count}} more entry",
|
||||
"showMore_few": "Show {{count}} more entries",
|
||||
"showMore_many": "Show {{count}} more entries",
|
||||
"showMore_other": "Show {{count}} more entries"
|
||||
},
|
||||
"consoleTitle": "Gym",
|
||||
"backToList": "Back",
|
||||
"kpiMembers": "Members",
|
||||
"kpiEquipment": "Equipment",
|
||||
"kpiOwners": "Owners",
|
||||
"kpiRelated": "Requests / invites",
|
||||
"createdAtLabel": "Created",
|
||||
"hoursSection": "Opening hours",
|
||||
"noHours": "No opening hours",
|
||||
"membersSection": "Members",
|
||||
"colMember": "Member",
|
||||
"colRoles": "Roles",
|
||||
"colJoined": "Joined",
|
||||
"roleFilterAria": "Filter roles",
|
||||
"searchMembersAria": "Search member",
|
||||
"searchMembersPh": "Search member…",
|
||||
"roleFilterAll": "All members",
|
||||
"roleFilterOwners": "Owners",
|
||||
"roleFilterTrainers": "Trainers",
|
||||
"roleFilterMembers": "Members",
|
||||
"memberMenuTitle": "Member: {{name}}",
|
||||
"memberMenuDesc": "Manage roles or remove this member from the gym.",
|
||||
"memberProfileLink": "Open profile in panel",
|
||||
"memberRolesTitle": "Gym roles",
|
||||
"saveRoles": "Save roles",
|
||||
"rolesSaved": "Roles saved.",
|
||||
"removeMemberTitle": "Remove from gym",
|
||||
"removeMemberDesc": "The membership is removed immediately. The reason is stored in the audit log.",
|
||||
"removeReasonLabel": "Reason",
|
||||
"removeReasonPh": "e.g. repeated rule violations",
|
||||
"removeMemberAction": "Remove member",
|
||||
"removing": "Removing…",
|
||||
"membersEmpty": "No members",
|
||||
"membersNoResults": "No members match the filter",
|
||||
"loadMore_one": "Show {{count}} more member",
|
||||
"loadMore_few": "Show {{count}} more members",
|
||||
"loadMore_many": "Show {{count}} more members",
|
||||
"loadMore_other": "Show {{count}} more members",
|
||||
"relatedSection": "Claims and invitations",
|
||||
"relatedEmpty": "No claims or invitations for this gym",
|
||||
"relatedClaimsTitle": "Verification claims",
|
||||
"relatedInvitationsTitle": "Invitations",
|
||||
"invitedBy": "from",
|
||||
"invStatusAccepted": "Accepted",
|
||||
"invStatusDeclined": "Declined",
|
||||
"invStatusExpired": "Expired",
|
||||
"allLogs": "All logs",
|
||||
"nameLabel": "Name",
|
||||
"membersCapacity": "{{members}}/{{capacity}} members",
|
||||
"membersCapacity": "{{members}}/{{capacity}}",
|
||||
"owner": "Owner",
|
||||
"capacity": "Capacity",
|
||||
"availability": "Availability",
|
||||
@@ -66,13 +143,10 @@
|
||||
"saved": "Changes saved.",
|
||||
"noOwnerTitle": "No owner",
|
||||
"noOwnerDesc": "Assign a person who will manage the gym in the app.",
|
||||
"revokeAria": "Revoke role",
|
||||
"revokeTitle": "Revoke owner role",
|
||||
"searchFutureOwner": "Search future owner",
|
||||
"noOwnerCandidates": "No candidates — all users are already owners",
|
||||
"granting": "Granting…",
|
||||
"grantOwner": "Grant owner",
|
||||
"ownerRoleHint": "The owner manages the gym in the app: equipment, gallery and schedule.",
|
||||
"assignOwner": "Assign owner",
|
||||
"groupEdit": "Editing",
|
||||
"groupManage": "Manage",
|
||||
"tilePhotos_one": "{{count}} photo",
|
||||
@@ -157,24 +231,7 @@
|
||||
"photoTypesError": "Allowed files: JPEG, PNG, WEBP (max 5 MB).",
|
||||
"photoMaxFilesError": "Maximum {{count}} files at once.",
|
||||
"confirmDeletePhoto": "Delete this photo?",
|
||||
"presenceNow": "now: {{count}} person",
|
||||
"presenceNow_one": "now: {{count}} person",
|
||||
"presenceNow_few": "now: {{count}} people",
|
||||
"presenceNow_many": "now: {{count}} people",
|
||||
"presenceNow_other": "now: {{count}} people",
|
||||
"presenceFull": "full",
|
||||
"presence": {
|
||||
"title": "Attendance",
|
||||
"empty": "No check-ins in the last 30 days.",
|
||||
"live": "inside now",
|
||||
"visits": "visits (30 days)",
|
||||
"avgStay": "avg stay",
|
||||
"visitsPerDay": "visits/day",
|
||||
"peak": "hourly peak",
|
||||
"minutesShort": "min",
|
||||
"heatmap": "When they train (day × hour)",
|
||||
"topEquipment": "Most used equipment",
|
||||
"qrGroup": "QR",
|
||||
"qrAction": "QR code",
|
||||
"qrTitle": "Gym QR code",
|
||||
"qrSubtitle": "Scan and check in for your workout",
|
||||
@@ -203,9 +260,5 @@
|
||||
"recordsTitle": "1RM records",
|
||||
"emptyRecords": "No measurable records.",
|
||||
"anon": "anonymous"
|
||||
},
|
||||
"stats": {
|
||||
"cellTitle_one": "{{day}}, {{hour}}:00 — {{count}} visit",
|
||||
"cellTitle_other": "{{day}}, {{hour}}:00 — {{count}} visits"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,14 +30,91 @@
|
||||
"virtual": "Wirtualna",
|
||||
"private": "Prywatna",
|
||||
"open": "Otwórz →",
|
||||
"allGyms": "Wszystkie siłownie",
|
||||
"newGym": "Nowa siłownia",
|
||||
"noResults": "Brak wyników",
|
||||
"noResultsDesc": "Brak wyników dla podanego zapytania.",
|
||||
"noGymsTitle": "Brak siłowni",
|
||||
"noGymsDesc": "Brak siłowni. Dodaj pierwszą przyciskiem „Nowa siłownia” w menu kontekstowym.",
|
||||
"colName": "Nazwa",
|
||||
"colLocation": "Lokalizacja",
|
||||
"colOwners": "Właściciele",
|
||||
"colMembers": "Członkowie",
|
||||
"colOpenToday": "Dziś",
|
||||
"colCreatedAt": "Utworzono",
|
||||
"closedToday": "nieczynna",
|
||||
"noOwners": "brak",
|
||||
"ownersMore_one": "+{{count}} inny",
|
||||
"ownersMore_few": "+{{count}} innych",
|
||||
"ownersMore_many": "+{{count}} innych",
|
||||
"ownersMore_other": "+{{count}} innych",
|
||||
"openInApp": "Otwórz w aplikacji",
|
||||
"filterKindAria": "Filtr typu siłowni",
|
||||
"filterKindAll": "Wszystkie typy",
|
||||
"kindReal": "Realna",
|
||||
"logsTile": {
|
||||
"title": "Logi",
|
||||
"hint": "Audyt siłowni"
|
||||
},
|
||||
"groupLogs": "Logi",
|
||||
"logsPage": {
|
||||
"title": "Logi siłowni",
|
||||
"subtitle": "Operacje na siłowni, członkach, wnioskach i zaproszeniach",
|
||||
"emptyTitle": "Brak logów",
|
||||
"emptyDesc": "Brak operacji powiązanych z tą siłownią.",
|
||||
"showMore_one": "Pokaż jeszcze {{count}} wpis",
|
||||
"showMore_few": "Pokaż jeszcze {{count}} wpisy",
|
||||
"showMore_many": "Pokaż jeszcze {{count}} wpisów",
|
||||
"showMore_other": "Pokaż jeszcze {{count}} wpisów"
|
||||
},
|
||||
"consoleTitle": "Siłownia",
|
||||
"backToList": "Wróć",
|
||||
"kpiMembers": "Członkowie",
|
||||
"kpiEquipment": "Urządzenia",
|
||||
"kpiOwners": "Właściciele",
|
||||
"kpiRelated": "Wnioski / zaproszenia",
|
||||
"createdAtLabel": "Utworzono",
|
||||
"hoursSection": "Godziny otwarcia",
|
||||
"noHours": "Brak godzin otwarcia",
|
||||
"membersSection": "Członkowie",
|
||||
"colMember": "Członek",
|
||||
"colRoles": "Role",
|
||||
"colJoined": "Dołączył(a)",
|
||||
"roleFilterAria": "Filtruj role",
|
||||
"searchMembersAria": "Szukaj członka",
|
||||
"searchMembersPh": "Szukaj członka…",
|
||||
"roleFilterAll": "Wszyscy członkowie",
|
||||
"roleFilterOwners": "Właściciele",
|
||||
"roleFilterTrainers": "Trenerzy",
|
||||
"roleFilterMembers": "Członkowie",
|
||||
"memberMenuTitle": "Członek: {{name}}",
|
||||
"memberMenuDesc": "Zarządzaj rolami albo usuń członkostwo w tej siłowni.",
|
||||
"memberProfileLink": "Otwórz profil w panelu",
|
||||
"memberRolesTitle": "Role w siłowni",
|
||||
"saveRoles": "Zapisz role",
|
||||
"rolesSaved": "Role zapisane.",
|
||||
"removeMemberTitle": "Wyrzuć z siłowni",
|
||||
"removeMemberDesc": "Członkostwo zostanie usunięte natychmiast. Powód trafi do logów audytu.",
|
||||
"removeReasonLabel": "Powód",
|
||||
"removeReasonPh": "np. wielokrotne łamanie regulaminu",
|
||||
"removeMemberAction": "Wyrzuć członka",
|
||||
"removing": "Usuwanie…",
|
||||
"membersEmpty": "Brak członków",
|
||||
"membersNoResults": "Brak członków dla wybranego filtra",
|
||||
"loadMore_one": "Pokaż kolejnego członka ({{count}})",
|
||||
"loadMore_few": "Pokaż kolejnych {{count}} członków",
|
||||
"loadMore_many": "Pokaż kolejnych {{count}} członków",
|
||||
"loadMore_other": "Pokaż kolejnych {{count}} członków",
|
||||
"relatedSection": "Wnioski i zaproszenia",
|
||||
"relatedEmpty": "Brak wniosków ani zaproszeń dla tej siłowni",
|
||||
"relatedClaimsTitle": "Wnioski o weryfikację",
|
||||
"relatedInvitationsTitle": "Zaproszenia",
|
||||
"invitedBy": "od",
|
||||
"invStatusAccepted": "Przyjęte",
|
||||
"invStatusDeclined": "Odrzucone",
|
||||
"invStatusExpired": "Wygasło",
|
||||
"allLogs": "Wszystkie logi",
|
||||
"nameLabel": "Nazwa",
|
||||
"membersCapacity": "{{members}}/{{capacity}} członków",
|
||||
"membersCapacity": "{{members}}/{{capacity}}",
|
||||
"owner": "Właściciel",
|
||||
"capacity": "Ilość miejsc",
|
||||
"availability": "Dostępność",
|
||||
@@ -68,13 +145,10 @@
|
||||
"saved": "Zapisano zmiany.",
|
||||
"noOwnerTitle": "Brak właściciela",
|
||||
"noOwnerDesc": "Wyznacz osobę, która będzie zarządzać siłownią w aplikacji.",
|
||||
"revokeAria": "Odbierz rolę",
|
||||
"revokeTitle": "Odbierz rolę właściciela",
|
||||
"searchFutureOwner": "Szukaj przyszłego właściciela",
|
||||
"noOwnerCandidates": "Brak kandydatów — wszyscy użytkownicy są już właścicielami",
|
||||
"granting": "Nadawanie…",
|
||||
"grantOwner": "Nadaj właściciela",
|
||||
"ownerRoleHint": "Właściciel zarządza siłownią w aplikacji: urządzeniami, galerią i harmonogramem.",
|
||||
"assignOwner": "Przypisz właściciela",
|
||||
"groupEdit": "Edycja",
|
||||
"groupManage": "Zarządzaj",
|
||||
"tilePhotos_one": "{{count}} zdjęcie",
|
||||
@@ -169,24 +243,7 @@
|
||||
"photoTypesError": "Dozwolone pliki: JPEG, PNG, WEBP (max 5 MB).",
|
||||
"photoMaxFilesError": "Maksymalnie {{count}} plików naraz.",
|
||||
"confirmDeletePhoto": "Usunąć to zdjęcie?",
|
||||
"presenceNow": "teraz: {{count}} osoba",
|
||||
"presenceNow_one": "teraz: {{count}} osoba",
|
||||
"presenceNow_few": "teraz: {{count}} osoby",
|
||||
"presenceNow_many": "teraz: {{count}} osób",
|
||||
"presenceNow_other": "teraz: {{count}} osób",
|
||||
"presenceFull": "pełno",
|
||||
"presence": {
|
||||
"title": "Bytność",
|
||||
"empty": "Brak meldunków w ostatnich 30 dniach.",
|
||||
"live": "teraz w środku",
|
||||
"visits": "wizyty (30 dni)",
|
||||
"avgStay": "śr. pobyt",
|
||||
"visitsPerDay": "wizyt/dzień",
|
||||
"peak": "rekord godzinowy",
|
||||
"minutesShort": "min",
|
||||
"heatmap": "Kiedy bywają (dzień × godzina)",
|
||||
"topEquipment": "Najczęściej używane urządzenia",
|
||||
"qrGroup": "QR",
|
||||
"qrAction": "Kod QR",
|
||||
"qrTitle": "Kod QR siłowni",
|
||||
"qrSubtitle": "Zeskanuj i melduj się na treningu",
|
||||
@@ -217,11 +274,5 @@
|
||||
"recordsTitle": "Rekordy 1RM",
|
||||
"emptyRecords": "Brak mierzalnych rekordów.",
|
||||
"anon": "anonim"
|
||||
},
|
||||
"stats": {
|
||||
"cellTitle_one": "{{day}}, {{hour}}:00 — {{count}} wizyta",
|
||||
"cellTitle_few": "{{day}}, {{hour}}:00 — {{count}} wizyty",
|
||||
"cellTitle_many": "{{day}}, {{hour}}:00 — {{count}} wizyt",
|
||||
"cellTitle_other": "{{day}}, {{hour}}:00 — {{count}} wizyt"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,14 +5,21 @@ import { ScrollText } from 'lucide-react';
|
||||
import { useTopbar } from '../topbar';
|
||||
import { MonthPickerCore } from '../topbar/MonthPicker';
|
||||
import { api } from '../api/client';
|
||||
import type { ActivityLog, ActivityLogPage } from '../api/types';
|
||||
import { Badge, EmptyState, ErrorText, Loading, Select, type BadgeColor } from '../components/ui';
|
||||
import type { ActivityLogPage } from '../api/types';
|
||||
import { EmptyState, ErrorText, Loading, Select } from '../components/ui';
|
||||
import { LogTable } from '../components/LogTable';
|
||||
import { useListSearch } from '../store/list-search';
|
||||
import i18n from '../i18n';
|
||||
import { fmtDate, fmtDateTime, fmtTime } from '../lib/format';
|
||||
|
||||
const t = (key: string, options?: Record<string, unknown>): string =>
|
||||
String(i18n.t(`logs:${key}`, options as never));
|
||||
// Wspólne helpery logów mieszkają w komponencie tabeli (używane też przez UserDetail
|
||||
// i logi pojedynczej siłowni) — re-export zachodzi tutaj dla istniejących importów.
|
||||
export {
|
||||
actionColor,
|
||||
actionLabel,
|
||||
actorName,
|
||||
detailsLines,
|
||||
detailsText,
|
||||
formatLogDate,
|
||||
} from '../components/LogTable';
|
||||
|
||||
export const ACTION_KEYS = [
|
||||
'user.registered',
|
||||
@@ -89,75 +96,6 @@ export const ACTION_KEYS = [
|
||||
'focus_area.deleted',
|
||||
];
|
||||
|
||||
export function actionLabel(action: string) {
|
||||
return t(`actions.${action}`, { defaultValue: action });
|
||||
}
|
||||
|
||||
export function actionColor(action: string): BadgeColor {
|
||||
if (action.startsWith('plan.')) return 'blue';
|
||||
if (action.startsWith('session.')) return 'green';
|
||||
if (action.startsWith('gym.')) return 'gray';
|
||||
if (action.startsWith('coaching.')) return 'red';
|
||||
// akcje security konta — tak samo wyraźne jak relacje trenerskie
|
||||
if (action.startsWith('user.')) return 'red';
|
||||
if (action.startsWith('membership.')) return 'blue';
|
||||
return 'yellow';
|
||||
}
|
||||
|
||||
export function formatLogDate(iso: string) {
|
||||
return fmtDateTime(iso);
|
||||
}
|
||||
|
||||
export function actorName(log: ActivityLog) {
|
||||
const { firstName, lastName, email } = log.actor;
|
||||
return [firstName, lastName].filter(Boolean).join(' ') || email;
|
||||
}
|
||||
|
||||
/** Nazwa obiektu z szczegółów wpisu (tytuł planu, nazwa siłowni, nazwa obwodu). */
|
||||
function entityName(log: ActivityLog) {
|
||||
const d = log.details;
|
||||
if (!d) return null;
|
||||
return (d.title ?? d.name ?? d.gymName ?? null) as string | null;
|
||||
}
|
||||
|
||||
/** Klucze pokazywane w innych kolumnach (aktor w „Użytkownik", nazwa w „Obiekt"). */
|
||||
const HIDDEN_DETAIL_KEYS = new Set(['actorId', 'title', 'name', 'gymName']);
|
||||
|
||||
function formatDetailValue(log: ActivityLog, key: string, value: unknown): string {
|
||||
if (Array.isArray(value)) return value.map((v) => String(v)).join(', ');
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.entries(value)
|
||||
.map(([k, v]) => `${k}: ${formatDetailValue(log, k, v)}`)
|
||||
.join(', ');
|
||||
}
|
||||
let text = String(value);
|
||||
if (key === 'value' && typeof value === 'number') {
|
||||
const unit =
|
||||
log.action === 'weight.added' || log.action === 'weight.removed'
|
||||
? ' kg'
|
||||
: log.action === 'circumference.added' || log.action === 'circumference.removed'
|
||||
? ' cm'
|
||||
: '';
|
||||
text += unit;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/** Szczegóły wpisu jako linie: `start: 2026-08-24`, `wartość: 82.5 kg` — jedna pod drugą. */
|
||||
export function detailsLines(log: ActivityLog): string[] {
|
||||
const d = log.details;
|
||||
if (!d) return [];
|
||||
return Object.entries(d)
|
||||
.filter(([k]) => !HIDDEN_DETAIL_KEYS.has(k))
|
||||
.map(([k, v]) => `${t(`details.${k}`, { defaultValue: k })}: ${formatDetailValue(log, k, v)}`);
|
||||
}
|
||||
|
||||
/** Szczegóły jako jeden tekst: `start: 2026-08-24 · wartość: 82.5 kg`. */
|
||||
export function detailsText(log: ActivityLog) {
|
||||
const parts = detailsLines(log);
|
||||
return parts.length > 0 ? parts.join(' · ') : null;
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
export default function Logs() {
|
||||
@@ -265,78 +203,7 @@ export default function Logs() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && filtered.length > 0 && (
|
||||
<div className="overflow-x-auto rounded-[10px] border border-line bg-(image:--card-grad) shadow-card">
|
||||
<table className="w-full text-[0.95rem]">
|
||||
<thead>
|
||||
<tr className="border-b border-line text-left text-dim">
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{tr('colDate')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{tr('colUser')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{tr('colAction')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{tr('colEntity')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{tr('colDetails')}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.map((log) => (
|
||||
<tr
|
||||
key={log.id}
|
||||
className="border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20"
|
||||
>
|
||||
<td className="px-4 py-3 align-top font-display text-dim tabular-nums">
|
||||
<div className="whitespace-nowrap">{fmtDate(log.createdAt)}</div>
|
||||
<div className="whitespace-nowrap text-[0.875rem]">
|
||||
{fmtTime(log.createdAt)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-semibold">{actorName(log)}</div>
|
||||
<div className="text-[0.875rem] text-dim">{log.actor.email}</div>
|
||||
<div className="font-mono text-[0.75rem] text-dim/70" title={log.actor.id}>
|
||||
{log.actor.id}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top">
|
||||
<Badge
|
||||
color={actionColor(log.action)}
|
||||
className="h-auto max-w-[13rem] whitespace-normal"
|
||||
>
|
||||
{actionLabel(log.action)}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div>{tr(`entities.${log.entityType}`, { defaultValue: log.entityType })}</div>
|
||||
{entityName(log) && (
|
||||
<div className="text-[0.875rem] text-dim">{entityName(log)}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-dim">
|
||||
{detailsLines(log).length > 0 ? (
|
||||
<div className="space-y-1">
|
||||
{detailsLines(log).map((line) => (
|
||||
<div key={line}>{line}</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && !error && filtered.length > 0 && <LogTable logs={filtered} />}
|
||||
|
||||
{!isLoading && !error && logs.length < total && (
|
||||
<div className="mt-4 text-center">
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { AdminAnnouncement, Gym } from '../../api/types';
|
||||
import { BackButton, Card, ErrorText, Loading, Modal, SectionHeader } from '../../components/ui';
|
||||
import { fmtDateTime } from '../../lib/format';
|
||||
import { useTopbar, type TopbarAction } from '../../topbar';
|
||||
import { GymAnnouncementsSection } from './GymDetail';
|
||||
import { GymAnnouncementsSection } from '../../components/gyms/AnnouncementsSection';
|
||||
|
||||
/* Podstrona ogłoszeń (read-only): lista; tworzenie/usuwanie modalem z sekcją
|
||||
przeniesioną ze strony detalu (akcja „Nowe ogłoszenie” w menu). */
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,7 +18,7 @@ import {
|
||||
import { useTopbar, type TopbarAction } from '../../topbar';
|
||||
import { formatGymEquipment } from '../../lib/equipment';
|
||||
import { localizedName } from '../../lib/localizedName';
|
||||
import { EquipmentSection } from './GymDetail';
|
||||
import { EquipmentSection } from '../../components/gyms/EquipmentSection';
|
||||
|
||||
const RANGE_OPTIONS = [7, 30, 90];
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { Gym, GymPhoto } from '../../api/types';
|
||||
import { AuthImage } from '../../components/AuthImage';
|
||||
import { BackButton, Card, ErrorText, Loading, Modal, SectionHeader } from '../../components/ui';
|
||||
import { useTopbar, type TopbarAction } from '../../topbar';
|
||||
import { GallerySection } from './GymDetail';
|
||||
import { GallerySection } from '../../components/gyms/GallerySection';
|
||||
|
||||
/* Podstrona galerii (read-only): pełna siatka zdjęć + podgląd; edycja modalem
|
||||
GallerySection (akcja „Edytuj zdjęcia” w menu). */
|
||||
|
||||
94
admin/src/pages/gyms/GymLogsPage.tsx
Normal file
94
admin/src/pages/gyms/GymLogsPage.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ScrollText } from 'lucide-react';
|
||||
import { api } from '../../api/client';
|
||||
import type { Gym } from '../../api/types';
|
||||
import { useGymAuditLogs } from '../../api/queries';
|
||||
import { BackButton, EmptyState, ErrorText, Loading } from '../../components/ui';
|
||||
import { LogTable } from '../../components/LogTable';
|
||||
import { useTopbar } from '../../topbar';
|
||||
|
||||
/* Podstrona logów siłowni (read-only): audyt operacji powiązanych z siłownią —
|
||||
gym.*, membership.* tej siłowni, jej wnioski i zaproszenia. */
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
export default function GymLogsPage() {
|
||||
const { t } = useTranslation('gyms');
|
||||
const { id } = useParams();
|
||||
const [limit, setLimit] = useState(PAGE_SIZE);
|
||||
|
||||
const {
|
||||
data: gym,
|
||||
isLoading,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: ['gym', id],
|
||||
queryFn: () => api<Gym>(`/admin/gyms/${id}`),
|
||||
enabled: !!id,
|
||||
});
|
||||
const { data, isLoading: logsLoading } = useGymAuditLogs(id, limit);
|
||||
const logs = data?.logs ?? [];
|
||||
const total = data?.total ?? 0;
|
||||
|
||||
useTopbar({ title: t('logsPage.title'), back: `/gyms/${id}` });
|
||||
|
||||
if (isLoading) return <Loading />;
|
||||
if (error)
|
||||
return (
|
||||
<>
|
||||
<BackButton to={`/gyms/${id}`} className="mb-4" />
|
||||
<ErrorText>
|
||||
{t('common:errorPrefix')}
|
||||
{(error as Error).message}
|
||||
</ErrorText>
|
||||
</>
|
||||
);
|
||||
if (!gym) {
|
||||
return (
|
||||
<>
|
||||
<BackButton to={`/gyms/${id}`} className="mb-4" />
|
||||
<ErrorText>{t('notFound')}</ErrorText>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* HERO-LITE: nazwa siłowni (tytuł h1 należy do topbaru) */}
|
||||
<div className="mb-5 flex flex-wrap items-end justify-between gap-3">
|
||||
<div>
|
||||
<span className="font-display text-[1.35rem] font-bold tracking-[-0.02em]">
|
||||
{gym.name}
|
||||
</span>
|
||||
<p className="mt-0.5 text-[0.85rem] text-dim">{t('logsPage.subtitle')}</p>
|
||||
</div>
|
||||
<BackButton to={`/gyms/${id}`} />
|
||||
</div>
|
||||
|
||||
{logsLoading && <Loading />}
|
||||
{!logsLoading && logs.length === 0 && (
|
||||
<EmptyState
|
||||
icon={ScrollText}
|
||||
title={t('logsPage.emptyTitle')}
|
||||
description={t('logsPage.emptyDesc')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{logs.length > 0 && <LogTable logs={logs} />}
|
||||
|
||||
{logs.length < total && (
|
||||
<div className="mt-4 text-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLimit((l) => l + PAGE_SIZE)}
|
||||
className="text-[0.9rem] font-semibold text-accent-text hover:underline cursor-pointer"
|
||||
>
|
||||
{t('logsPage.showMore', { count: total - logs.length })}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,165 +1,141 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Activity, MapPin, Plus, Users, Building2, Dumbbell } from 'lucide-react';
|
||||
import { api } from '../../api/client';
|
||||
import type { AdminOccupancyRow, Gym } from '../../api/types';
|
||||
import { Badge, Card, EmptyState, ErrorText, H3, Loading, MetaItem } from '../../components/ui';
|
||||
import { dayShort, formatDayRange, normalizeAvailability } from '../../lib/availability';
|
||||
import { Building2, Plus } from 'lucide-react';
|
||||
import type { AdminGymListItem, GymKind } from '../../api/types';
|
||||
import { useAdminGymList } from '../../api/queries';
|
||||
import { Badge, Card, EmptyState, ErrorText, Loading, Select } from '../../components/ui';
|
||||
import { formatDayRangeClock, normalizeAvailability } from '../../lib/availability';
|
||||
import { useListSearch } from '../../store/list-search';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { AuthImage } from '../../components/AuthImage';
|
||||
import { fmtDate } from '../../lib/format';
|
||||
|
||||
/* Karta siłowni 1:1 z widokiem z aplikacji (app/src/pages/gyms/Gyms.tsx):
|
||||
cover z badge'ami i „Otwórz →”, nazwa, meta z ikonami, pasek tygodnia z wyróżnionym „dziś”. */
|
||||
function GymCard({ gym, live }: { gym: Gym; live?: AdminOccupancyRow }) {
|
||||
function ownerLabel(o: AdminGymListItem['owners'][number]): string {
|
||||
return [o.firstName, o.lastName].filter(Boolean).join(' ') || o.email;
|
||||
}
|
||||
|
||||
/* Wiersz listy — klik na całej szerokości prowadzi do konsoli siłowni w panelu admina;
|
||||
dane istotne dla admina: lokalizacja, właściciele, członkowie, godziny dziś, utworzenie. */
|
||||
function GymRow({ gym }: { gym: AdminGymListItem }) {
|
||||
const { t } = useTranslation('gyms');
|
||||
const navigate = useNavigate();
|
||||
const availability = normalizeAvailability(gym.availability);
|
||||
const todayIdx = (new Date().getDay() + 6) % 7;
|
||||
const members = gym._count?.memberships ?? 0;
|
||||
const today = availability[(new Date().getDay() + 6) % 7];
|
||||
const hasHours = availability.some(Boolean);
|
||||
const members = gym._count.memberships;
|
||||
const owners = gym.owners;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="gym-card"
|
||||
className="flex cursor-pointer flex-col overflow-hidden rounded-xl border border-line bg-(image:--card-grad) shadow-card transition-all hover:-translate-y-0.5 hover:border-accent/55 hover:shadow-[var(--glow),var(--shadow)]"
|
||||
<tr
|
||||
onClick={() => navigate(`/gyms/${gym.id}`)}
|
||||
className="cursor-pointer border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20"
|
||||
>
|
||||
{/* okładka: zdjęcie albo gradientowy placeholder z piktogramem */}
|
||||
<div className="relative grid h-28 place-items-center overflow-hidden sm:h-32">
|
||||
{gym.coverPhoto ? (
|
||||
<AuthImage
|
||||
src={gym.coverPhoto}
|
||||
alt={gym.name}
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
'linear-gradient(140deg, color-mix(in srgb, var(--accent) 26%, var(--bg-input)), color-mix(in srgb, var(--line) 60%, var(--bg-input)) 55%, var(--bg-input))',
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="absolute inset-0 opacity-60"
|
||||
style={{
|
||||
background:
|
||||
'repeating-linear-gradient(45deg, color-mix(in srgb, var(--text) 4%, transparent) 0 2px, transparent 2px 14px)',
|
||||
}}
|
||||
/>
|
||||
<Dumbbell className="relative h-8 w-8 text-ink/25" />
|
||||
</>
|
||||
)}
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="absolute inset-0 bg-[linear-gradient(180deg,transparent_55%,rgb(0_0_0/0.45))]"
|
||||
/>
|
||||
<div className="absolute left-2.5 top-2.5 flex flex-wrap gap-1.5">
|
||||
<td className="px-4 py-3 align-top">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<Link
|
||||
to={`/gyms/${gym.id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="min-w-0 font-semibold hover:text-accent-text"
|
||||
>
|
||||
{gym.name}
|
||||
</Link>
|
||||
{gym.kind === 'VIRTUAL' && <Badge color="blue">{t('virtual')}</Badge>}
|
||||
{gym.isPrivate && <Badge color="gray">{t('private')}</Badge>}
|
||||
</div>
|
||||
<span className="absolute bottom-2.5 right-2.5 inline-flex items-center gap-1.5 rounded-full bg-black/35 px-2.5 py-1 text-[0.7rem] font-bold text-white backdrop-blur-sm">
|
||||
{t('open')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-col gap-2.5 p-4">
|
||||
<Link
|
||||
to={`/gyms/${gym.id}`}
|
||||
className="min-w-0 truncate text-[1.02rem] font-bold hover:text-accent-text"
|
||||
>
|
||||
{gym.name}
|
||||
</Link>
|
||||
<div className="flex flex-col gap-1 text-dim text-[0.78rem]">
|
||||
<MetaItem icon={MapPin}>{gym.location || '—'}</MetaItem>
|
||||
<div className="flex items-center gap-x-4">
|
||||
<MetaItem icon={Users}>
|
||||
{gym.capacity != null
|
||||
? t('membersCapacity', { members, capacity: gym.capacity })
|
||||
: t('common:counters.members', { count: members })}
|
||||
</MetaItem>
|
||||
<MetaItem icon={Dumbbell}>
|
||||
{t('common:counters.devices', { count: gym.equipment.length })}
|
||||
</MetaItem>
|
||||
{live && (
|
||||
<MetaItem icon={Activity}>
|
||||
{t('presenceNow', { count: live.count })}
|
||||
{gym.capacity != null ? ` (${gym.capacity})` : ''}
|
||||
{gym.capacity != null && live.count >= gym.capacity
|
||||
? ` — ${t('presenceFull')}`
|
||||
: ''}
|
||||
</MetaItem>
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top text-dim">
|
||||
{gym.addressLine1
|
||||
? `${gym.addressLine1}${gym.postalCode ? `, ${gym.postalCode}` : ''}${gym.city ? ` ${gym.city}` : ''}`
|
||||
: (gym.location ?? '—')}
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top">
|
||||
{owners.length === 0 ? (
|
||||
<span className="text-dim">{t('noOwners')}</span>
|
||||
) : (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{owners.slice(0, 2).map((o) => (
|
||||
<Link
|
||||
key={o.id}
|
||||
to={`/users/${o.id}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="hover:text-accent-text"
|
||||
>
|
||||
{ownerLabel(o)}
|
||||
</Link>
|
||||
))}
|
||||
{owners.length > 2 && (
|
||||
<span className="text-[0.8rem] text-dim">
|
||||
{t('ownersMore', { count: owners.length - 2 })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top">
|
||||
<div className="whitespace-nowrap tabular-nums">
|
||||
{gym.capacity != null
|
||||
? t('membersCapacity', { members, capacity: gym.capacity })
|
||||
: members}
|
||||
</div>
|
||||
<div className="grid grid-cols-7 gap-0.5">
|
||||
{availability.map((day, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`min-w-0 rounded-[10px] px-0 py-1.5 text-center ${day ? 'bg-accent/10' : 'bg-input/50'} ${
|
||||
i === todayIdx ? 'outline outline-1 outline-accent/50' : ''
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`truncate text-[0.6rem] font-semibold uppercase tracking-wide ${
|
||||
day ? 'text-accent-text' : 'text-dim/60'
|
||||
}`}
|
||||
>
|
||||
{dayShort(i)}
|
||||
</div>
|
||||
<div
|
||||
className={`whitespace-nowrap text-[0.65rem] tabular-nums tracking-tight ${
|
||||
day ? 'text-ink' : 'text-dim/50'
|
||||
}`}
|
||||
>
|
||||
{day ? formatDayRange(day) : '—'}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top whitespace-nowrap tabular-nums">
|
||||
{today ? (
|
||||
formatDayRangeClock(today)
|
||||
) : hasHours ? (
|
||||
<span className="text-dim">{t('closedToday')}</span>
|
||||
) : (
|
||||
<span className="text-dim">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 align-top whitespace-nowrap text-dim tabular-nums">
|
||||
{fmtDate(gym.createdAt)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
export default function GymsList() {
|
||||
const { t } = useTranslation('gyms');
|
||||
const [kind, setKind] = useState<'' | GymKind>('');
|
||||
|
||||
const query = useListSearch((s) => s.queries.gyms);
|
||||
const setQuery = useListSearch((s) => s.setQuery);
|
||||
// wyszukiwanie serwerowe — debounce, żeby nie odpytywać API przy każdym znaku
|
||||
const [debounced, setDebounced] = useState(query);
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => setDebounced(query.trim()), 300);
|
||||
return () => clearTimeout(id);
|
||||
}, [query]);
|
||||
|
||||
useTopbar({
|
||||
title: t('common:nav.gyms'),
|
||||
search: 'gyms',
|
||||
actions: [{ label: t('newGym'), to: '/gyms/new', icon: Plus }],
|
||||
filters: [
|
||||
<div key="kind" className="w-40">
|
||||
<Select
|
||||
size="sm"
|
||||
className="h-9"
|
||||
aria-label={t('filterKindAria')}
|
||||
value={kind}
|
||||
onChange={(e) => setKind(e.target.value as '' | GymKind)}
|
||||
>
|
||||
<option value="">{t('filterKindAll')}</option>
|
||||
<option value="REAL">{t('kindReal')}</option>
|
||||
<option value="VIRTUAL">{t('virtual')}</option>
|
||||
</Select>
|
||||
</div>,
|
||||
],
|
||||
filterActive: kind !== '',
|
||||
});
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['gyms'],
|
||||
queryFn: () => api<{ gyms: Gym[] }>('/admin/gyms'),
|
||||
});
|
||||
// live occupancy — osobny query (licznik „teraz” na kartach REAL)
|
||||
const { data: occupancyData } = useQuery({
|
||||
queryKey: ['gyms', 'occupancy'],
|
||||
queryFn: () => api<{ gyms: AdminOccupancyRow[] }>('/admin/gyms/occupancy'),
|
||||
});
|
||||
const occupancy = new Map((occupancyData?.gyms ?? []).map((o) => [o.gymId, o]));
|
||||
const query = useListSearch((s) => s.queries.gyms);
|
||||
const setQuery = useListSearch((s) => s.setQuery);
|
||||
|
||||
const gyms = data?.gyms ?? [];
|
||||
|
||||
const filtered = query
|
||||
? gyms.filter((g) =>
|
||||
[g.name, g.location]
|
||||
.filter(Boolean)
|
||||
.some((s) => s!.toLowerCase().includes(query.toLowerCase())),
|
||||
)
|
||||
: gyms;
|
||||
const { data, isLoading, error } = useAdminGymList(debounced, kind);
|
||||
|
||||
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
|
||||
useEffect(() => () => setQuery('gyms', ''), [setQuery]);
|
||||
|
||||
const gyms = data?.gyms ?? [];
|
||||
|
||||
return (
|
||||
<>
|
||||
{isLoading && <Loading />}
|
||||
@@ -170,30 +146,48 @@ export default function GymsList() {
|
||||
</ErrorText>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && filtered.length > 0 && (
|
||||
{!isLoading && !error && gyms.length > 0 && (
|
||||
<>
|
||||
<div className="mb-3 flex items-center gap-2.5">
|
||||
<H3 className="mb-0">{t('allGyms')}</H3>
|
||||
<Badge color="gray">{filtered.length}</Badge>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
|
||||
{filtered.map((g) => (
|
||||
<GymCard
|
||||
key={g.id}
|
||||
gym={g}
|
||||
live={g.kind === 'REAL' ? occupancy.get(g.id) : undefined}
|
||||
/>
|
||||
))}
|
||||
<div className="overflow-x-auto rounded-[10px] border border-line bg-(image:--card-grad) shadow-card">
|
||||
<table className="w-full text-[0.95rem]">
|
||||
<thead>
|
||||
<tr className="border-b border-line text-left text-dim">
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colName')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colLocation')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colOwners')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colMembers')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colOpenToday')}
|
||||
</th>
|
||||
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
||||
{t('colCreatedAt')}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{gyms.map((g) => (
|
||||
<GymRow key={g.id} gym={g} />
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && filtered.length === 0 && (
|
||||
{!isLoading && !error && gyms.length === 0 && (
|
||||
<Card>
|
||||
<EmptyState
|
||||
icon={Building2}
|
||||
title={query ? t('noResults') : t('noGymsTitle')}
|
||||
description={query ? t('noResultsDesc') : t('noGymsDesc')}
|
||||
title={debounced || kind ? t('noResults') : t('noGymsTitle')}
|
||||
description={debounced || kind ? t('noResultsDesc') : t('noGymsDesc')}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
@@ -31,6 +31,7 @@ const G1: Gym = {
|
||||
isPrivate: false,
|
||||
equipment: [],
|
||||
coverPhoto: null,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
_count: { memberships: 12 },
|
||||
owners: [OWNER1],
|
||||
};
|
||||
@@ -69,6 +70,94 @@ const U1 = {
|
||||
isAdmin: false,
|
||||
} as unknown as User;
|
||||
|
||||
const MEMBERS_PAGE_1 = {
|
||||
members: [
|
||||
{
|
||||
membershipId: 'mem-1',
|
||||
roles: ['OWNER'],
|
||||
joinedAt: '2026-01-02T10:00:00.000Z',
|
||||
checkedInNow: false,
|
||||
user: {
|
||||
id: 'u-owner',
|
||||
firstName: 'Anna',
|
||||
lastName: 'Kowalska',
|
||||
email: 'anna@fitos.pl',
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
},
|
||||
{
|
||||
membershipId: 'mem-2',
|
||||
roles: ['MEMBER', 'TRAINER'],
|
||||
joinedAt: '2026-02-01T10:00:00.000Z',
|
||||
checkedInNow: true,
|
||||
user: {
|
||||
id: 'u-mem',
|
||||
firstName: 'Jan',
|
||||
lastName: 'Nowak',
|
||||
email: 'jan@fitos.pl',
|
||||
status: 'SUSPENDED',
|
||||
},
|
||||
},
|
||||
],
|
||||
total: 3,
|
||||
};
|
||||
|
||||
const MEMBERS_PAGE_2 = {
|
||||
members: [
|
||||
{
|
||||
membershipId: 'mem-3',
|
||||
roles: ['MEMBER'],
|
||||
joinedAt: '2026-03-01T10:00:00.000Z',
|
||||
checkedInNow: false,
|
||||
user: {
|
||||
id: 'u-mem-2',
|
||||
firstName: 'Ola',
|
||||
lastName: 'Wajs',
|
||||
email: 'ola@fitos.pl',
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
},
|
||||
],
|
||||
total: 3,
|
||||
};
|
||||
|
||||
const RELATED = {
|
||||
claims: [
|
||||
{
|
||||
id: 'c1',
|
||||
status: 'PENDING',
|
||||
createdAt: '2026-03-05T12:00:00.000Z',
|
||||
user: { id: 'u-mem', firstName: 'Jan', lastName: 'Nowak', email: 'jan@fitos.pl' },
|
||||
documentCount: 1,
|
||||
},
|
||||
],
|
||||
invitations: [
|
||||
{
|
||||
id: 'i1',
|
||||
status: 'PENDING',
|
||||
invitedAt: '2026-03-06T12:00:00.000Z',
|
||||
expiresAt: '2026-03-13T12:00:00.000Z',
|
||||
user: { id: 'u-mem-2', firstName: 'Ola', lastName: 'Wajs', email: 'ola@fitos.pl' },
|
||||
invitedBy: OWNER1,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const LOGS_PAGE = {
|
||||
logs: [
|
||||
{
|
||||
id: 'log-1',
|
||||
createdAt: '2026-03-07T09:00:00.000Z',
|
||||
action: 'gym.updated',
|
||||
entityType: 'gym',
|
||||
entityId: 'g1',
|
||||
details: { name: 'Gym A' },
|
||||
actor: { id: 'adm', firstName: 'Ada', lastName: 'Admin', email: 'ada@fitos.pl' },
|
||||
},
|
||||
],
|
||||
total: 7,
|
||||
};
|
||||
|
||||
type Call = { url: string; method?: string; body?: unknown };
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
@@ -78,7 +167,7 @@ function jsonResponse(status: number, body: unknown) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Wspólny mock: karta siłowni, katalog, wyjątki, użytkownicy i endpointy właścicieli. */
|
||||
/** Wspólny mock konsoli: karta siłowni, KPI, członkowie, related, logi, wyjątki, właściciele. */
|
||||
function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) {
|
||||
const gym = options.gym ?? G1;
|
||||
const calls = options.calls ?? [];
|
||||
@@ -88,20 +177,16 @@ function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) {
|
||||
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/gyms/g1/presence-stats'))
|
||||
return jsonResponse(200, {
|
||||
gym: { id: 'g1', name: gym.name, kind: gym.kind, capacity: gym.capacity },
|
||||
stats: {
|
||||
visits: 40,
|
||||
avgStayMinutes: 62,
|
||||
heatmap: [{ day: 1, hour: 18, count: 7 }],
|
||||
topGyms: [],
|
||||
peak: 7,
|
||||
topEquipment: [{ equipmentId: 'eq-1', name: 'sztanga', nameEn: null, count: 12 }],
|
||||
live: 3,
|
||||
visitsPerDay: 1.3,
|
||||
},
|
||||
});
|
||||
if (url.includes('/memberships/') && method === 'PATCH')
|
||||
return jsonResponse(200, { membership: {} });
|
||||
if (url.includes('/memberships/') && method === 'DELETE') return jsonResponse(204, {});
|
||||
if (url.includes('/admin/gyms/g1/members')) {
|
||||
const offset = Number(new URL(`http://x${url}`).searchParams.get('offset') ?? 0);
|
||||
if (offset > 0) return jsonResponse(200, MEMBERS_PAGE_2);
|
||||
return jsonResponse(200, MEMBERS_PAGE_1);
|
||||
}
|
||||
if (url.includes('/admin/gyms/g1/related')) return jsonResponse(200, RELATED);
|
||||
if (url.includes('/admin/gyms/g1/logs')) return jsonResponse(200, LOGS_PAGE);
|
||||
if (url.includes('/admin/users')) return jsonResponse(200, { users: [U1] });
|
||||
if (url.includes('/admin/announcements')) return jsonResponse(200, { announcements: [] });
|
||||
if (url.includes('/equipment-usage'))
|
||||
@@ -168,48 +253,199 @@ afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('admin GymDetail page', () => {
|
||||
it('pokazuje szczegóły odczytu, kafelki sekcji i pojedynczą grupę menu „Zarządzaj”', async () => {
|
||||
describe('admin GymDetail (konsola)', () => {
|
||||
it('renderuje konsolę: KPI, członków, właścicieli i powiązania; bez hero i kafelków apki', async () => {
|
||||
stubGymFetch();
|
||||
renderGymDetail();
|
||||
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
|
||||
// hero bez chipa miasta i karty „Dane" — zostają liczniki członków/urządzeń
|
||||
expect(screen.getByText('12 członków')).toBeInTheDocument();
|
||||
|
||||
// kafelki sekcji prowadzą do podstron (galeria/urządzenia/ogłoszenia + tablica nad bytnością)
|
||||
expect(screen.getByRole('link', { name: /Galeria zdjęć/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /Urządzenia/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /Ogłoszenia/ })).toBeInTheDocument();
|
||||
const boardTile = screen.getByRole('link', { name: /Tablica/ });
|
||||
expect(boardTile).toHaveAttribute('href', '/gyms/g1/board');
|
||||
const presenceHeading = await screen.findByText('Bytność');
|
||||
expect(
|
||||
boardTile.compareDocumentPosition(presenceHeading) & Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
).toBeTruthy();
|
||||
// KPI z licznikami admina (bez zdjęcia okładki i chipów apki)
|
||||
expect(screen.getByText('12/50')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { level: 3, name: /Członkowie/ })).toBeInTheDocument();
|
||||
|
||||
// menu kontekstowe: JEDNA grupa „Zarządzaj” z akcjami strony (admin: + Właściciele)
|
||||
// tabela członków: OWNER + MEMBER/TRAINER z pigułkami ról (bez kolumn Konto/Obecność/Akcje)
|
||||
const table = await screen.findByRole('table');
|
||||
expect(within(table).getByText('Anna Kowalska')).toBeInTheDocument();
|
||||
const trainerRow = within(table).getByText('Jan Nowak').closest('tr');
|
||||
expect(within(trainerRow as HTMLElement).getByText('Trener')).toBeInTheDocument();
|
||||
// brak przycisków w tabeli — akcje członka dopiero w menu z kliknięcia wiersza
|
||||
expect(within(table).queryAllByRole('button')).toHaveLength(0);
|
||||
|
||||
// powiązane wnioski/zaproszenia i podgląd logów
|
||||
expect(screen.getByText('Wnioski i zaproszenia')).toBeInTheDocument();
|
||||
expect(screen.getByText('Wnioski o weryfikację')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'Wszystkie logi' })).toHaveAttribute(
|
||||
'href',
|
||||
'/gyms/g1/logs',
|
||||
);
|
||||
|
||||
// TOPBAR: tytuł = kategoria „Siłownia”, bez wyszukiwarki (wyjątek: kafelek członków), osobny przycisk „Otwórz w aplikacji”, grupa „Zarządzaj”
|
||||
const config = useTopbarStore.getState().config;
|
||||
expect(config?.title).toBe('Siłownia');
|
||||
// nazwa siłowni w treści (h2) + przycisk powrotu na listę
|
||||
expect(screen.getByRole('heading', { level: 2, name: 'Gym A' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'Wróć' })).toBeInTheDocument();
|
||||
expect(config?.search).toBeUndefined();
|
||||
const openInApp = config?.actions?.find((a) => a.label === 'Otwórz w aplikacji');
|
||||
expect(openInApp?.to).toBeUndefined();
|
||||
expect(typeof openInApp?.onClick).toBe('function');
|
||||
expect(config?.groups?.map((g) => g.id)).toEqual(['manage']);
|
||||
// akcje nigdy luzem na pasku — zebrane w kontrolce „Zarządzaj” (collapsed)
|
||||
expect(config?.groups?.[0]?.collapsed).toBe(true);
|
||||
expect(config?.groups?.[0]?.actions?.map((a) => a.label)).toEqual([
|
||||
'Informacje',
|
||||
'Galeria',
|
||||
'Tablica',
|
||||
'Kod QR',
|
||||
'Urządzenia',
|
||||
'Ogłoszenia',
|
||||
'Właściciele',
|
||||
'Logi',
|
||||
'Usuń siłownię',
|
||||
]);
|
||||
expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Galeria')?.to).toBe(
|
||||
'/gyms/g1/gallery',
|
||||
expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Tablica')?.to).toBe(
|
||||
'/gyms/g1/board',
|
||||
);
|
||||
expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Urządzenia')?.to).toBe(
|
||||
'/gyms/g1/equipment',
|
||||
});
|
||||
|
||||
it('dostraja listę członków przyciskiem „Pokaż kolejnych” (offset)', async () => {
|
||||
const calls = stubGymFetch();
|
||||
renderGymDetail();
|
||||
await screen.findByRole('heading', { name: 'Gym A' });
|
||||
const table = await screen.findByRole('table');
|
||||
await within(table).findByText('Anna Kowalska');
|
||||
expect(within(table).queryByText('Ola Wajs')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Pokaż kolejnego członka (1)' }));
|
||||
await within(table).findByText('Ola Wajs');
|
||||
expect(
|
||||
calls.some((c) => c.url.includes('/members') && c.url.includes('offset=2')),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('wyszukiwarka w kafelek członków odpytuje API z q (serwerowo)', async () => {
|
||||
const calls = stubGymFetch();
|
||||
renderGymDetail();
|
||||
await screen.findByRole('heading', { name: 'Gym A' });
|
||||
|
||||
fireEvent.change(screen.getByRole('searchbox', { name: 'Szukaj członka' }), {
|
||||
target: { value: 'ola' },
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
calls.some((c) => c.url.includes('/admin/gyms/g1/members') && c.url.includes('q=ola')),
|
||||
),
|
||||
);
|
||||
expect(config?.groups?.[0]?.actions?.find((a) => a.label === 'Ogłoszenia')?.to).toBe(
|
||||
'/gyms/g1/announcements',
|
||||
});
|
||||
|
||||
it('klik w wiersz otwiera menu członka: zmiana ról wysyła PATCH z pełną listą', async () => {
|
||||
const calls = stubGymFetch();
|
||||
renderGymDetail();
|
||||
const table = await screen.findByRole('table');
|
||||
|
||||
fireEvent.click(within(table).getByText('Jan Nowak'));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('Role w siłowni')).toBeInTheDocument();
|
||||
|
||||
// do pełnej listy MEMBER+TRAINER dopisujemy OWNER
|
||||
fireEvent.click(within(dialog).getByRole('checkbox', { name: 'Właściciel — Jan Nowak' }));
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Zapisz role' }));
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
calls.some(
|
||||
(c) =>
|
||||
c.method === 'PATCH' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
|
||||
),
|
||||
).toBe(true),
|
||||
);
|
||||
const patch = calls.find(
|
||||
(c) => c.method === 'PATCH' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
|
||||
);
|
||||
expect(patch?.body).toEqual({ roles: ['MEMBER', 'TRAINER', 'OWNER'] });
|
||||
});
|
||||
|
||||
it('wyrzucenie członka wymaga powodu i wysyła DELETE z powodem', async () => {
|
||||
const calls = stubGymFetch();
|
||||
renderGymDetail();
|
||||
const table = await screen.findByRole('table');
|
||||
|
||||
fireEvent.click(within(table).getByText('Jan Nowak'));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
|
||||
const removeBtn = within(dialog).getByRole('button', { name: 'Wyrzuć członka' });
|
||||
expect(removeBtn).toBeDisabled();
|
||||
|
||||
fireEvent.change(within(dialog).getByRole('textbox', { name: 'Powód' }), {
|
||||
target: { value: 'Wielokrotne łamanie regulaminu' },
|
||||
});
|
||||
fireEvent.click(removeBtn);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
calls.some(
|
||||
(c) =>
|
||||
c.method === 'DELETE' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
|
||||
),
|
||||
).toBe(true),
|
||||
);
|
||||
const del = calls.find(
|
||||
(c) => c.method === 'DELETE' && c.url.endsWith('/admin/users/u-mem/memberships/g1'),
|
||||
);
|
||||
expect(del?.body).toEqual({ reason: 'Wielokrotne łamanie regulaminu' });
|
||||
});
|
||||
|
||||
it('siłownia bez właściciela: alert i picker przypisania w sekcji członków', async () => {
|
||||
const calls = stubGymFetch({ gym: { ...G1, owners: [] } });
|
||||
renderGymDetail();
|
||||
expect(await screen.findByText('Brak właściciela')).toBeInTheDocument();
|
||||
|
||||
const picker = screen.getByRole('combobox', { name: 'Szukaj przyszłego właściciela' });
|
||||
fireEvent.change(picker, { target: { value: 'jan' } });
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Jan Kowalski/ }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Przypisz właściciela' }));
|
||||
await waitFor(() =>
|
||||
expect(calls.some((c) => c.method === 'POST' && c.url.endsWith('/owners'))).toBe(true),
|
||||
);
|
||||
expect(calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners'))?.body).toEqual({
|
||||
userId: 'u1',
|
||||
});
|
||||
});
|
||||
|
||||
it('filtr ról przy tabeli członków przekazuje parametr role do API', async () => {
|
||||
const calls = stubGymFetch();
|
||||
renderGymDetail();
|
||||
await screen.findByRole('heading', { name: 'Gym A' });
|
||||
|
||||
fireEvent.change(screen.getByRole('combobox', { name: 'Filtruj role' }), {
|
||||
target: { value: 'TRAINER' },
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(calls.some((c) => c.url.includes('/members') && c.url.includes('role=TRAINER'))).toBe(
|
||||
true,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('sekcja godzin: pasek tygodnia w treści; wyjątki w modalu „Informacje” (jak w apce)', async () => {
|
||||
stubGymFetch();
|
||||
renderGymDetail();
|
||||
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
|
||||
expect(screen.getByText('Godziny otwarcia')).toBeInTheDocument();
|
||||
expect(screen.getByText('6:00–22:00')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Dodaj' })).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(actionButton('Informacje'));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('Dodaj wyjątek — data i tryb dnia')).toBeInTheDocument();
|
||||
expect(within(dialog).getByRole('button', { name: 'Dodaj' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async () => {
|
||||
stubGymFetch();
|
||||
renderGymDetail();
|
||||
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(actionButton('Kod QR'));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByRole('img', { name: 'Gym A' })).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/\/gyms\/g1\/checkin/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('podstrona urządzeń: mapa ciepła godzinowa + edycja modalem z menu', async () => {
|
||||
@@ -251,77 +487,4 @@ describe('admin GymDetail page', () => {
|
||||
).toEqual({ equipmentId: 'eq-2', quantity: 1, spec: { minKg: 2.5, maxKg: 25 } });
|
||||
expect(calls.some((c) => c.method === 'PATCH')).toBe(false);
|
||||
});
|
||||
|
||||
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(actionButton('Właściciele'));
|
||||
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',
|
||||
});
|
||||
});
|
||||
|
||||
it('pokazuje telemetrię bytności dla siłowni REAL', async () => {
|
||||
stubGymFetch();
|
||||
renderGymDetail();
|
||||
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
|
||||
|
||||
expect(await screen.findByText('Bytność')).toBeInTheDocument();
|
||||
expect(screen.getByText('teraz w środku')).toBeInTheDocument();
|
||||
expect(screen.getByText('40')).toBeInTheDocument(); // wizyty (30 dni)
|
||||
expect(
|
||||
screen.getByText((_, el) => el?.tagName === 'DD' && el.textContent === '62 min'),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('1.3')).toBeInTheDocument(); // wizyt/dzień (jak w apce: surowa wartość)
|
||||
expect(screen.getByText('sztanga · 12')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('telemetria bytności pyta presence-stats ze stałego zakresu 30 dni (bez filtra okresu)', async () => {
|
||||
const calls = stubGymFetch();
|
||||
renderGymDetail();
|
||||
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
|
||||
|
||||
await screen.findByText('teraz w środku');
|
||||
// brak filtra okresu w topbarze — widok ogólny zawsze 30 dni
|
||||
expect(screen.queryByRole('combobox', { name: 'Zakres dat bytności' })).not.toBeInTheDocument();
|
||||
|
||||
const last = calls.filter((c) => c.url.includes('presence-stats')).at(-1);
|
||||
expect(last).toBeTruthy();
|
||||
const from = new Date(String(new URL(`http://x${last!.url}`).searchParams.get('from')));
|
||||
const days = (Date.now() - from.getTime()) / 86_400_000;
|
||||
expect(days).toBeGreaterThan(28);
|
||||
expect(days).toBeLessThan(32);
|
||||
});
|
||||
|
||||
it('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async () => {
|
||||
stubGymFetch();
|
||||
renderGymDetail();
|
||||
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(actionButton('Kod QR'));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByRole('img', { name: 'Gym A' })).toBeInTheDocument();
|
||||
expect(within(dialog).getByText(/\/gyms\/g1\/checkin/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
130
admin/test/GymLogsPage.test.tsx
Normal file
130
admin/test/GymLogsPage.test.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter, Route, Routes, useParams } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import GymLogsPage from '../src/pages/gyms/GymLogsPage';
|
||||
import { setAccessToken } from '../src/api/client';
|
||||
import type { ActivityLog } from '../src/api/types';
|
||||
|
||||
const GYM = {
|
||||
id: 'g1',
|
||||
name: 'Gym A',
|
||||
location: 'Warszawa',
|
||||
availability: null,
|
||||
capacity: null,
|
||||
kind: 'REAL',
|
||||
isPrivate: false,
|
||||
equipment: [],
|
||||
_count: { memberships: 3 },
|
||||
};
|
||||
|
||||
const LOG1: ActivityLog = {
|
||||
id: 'log-1',
|
||||
action: 'gym.created',
|
||||
entityType: 'gym',
|
||||
entityId: 'g1',
|
||||
details: { actorId: 'admin-1', name: 'Gym A' },
|
||||
createdAt: '2026-08-20T10:00:00.000Z',
|
||||
actor: { id: 'admin-1', email: 'admin@fitos.pl', firstName: 'Ada', lastName: 'Admin' },
|
||||
};
|
||||
|
||||
const LOG2: ActivityLog = {
|
||||
id: 'log-2',
|
||||
action: 'membership.created',
|
||||
entityType: 'membership',
|
||||
entityId: 'user-9',
|
||||
details: { actorId: 'admin-1', userId: 'user-9', gymId: 'g1', roles: ['MEMBER'] },
|
||||
createdAt: '2026-08-21T11:00:00.000Z',
|
||||
actor: { id: 'admin-1', email: 'admin@fitos.pl', firstName: 'Ada', lastName: 'Admin' },
|
||||
};
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
function DetailStub() {
|
||||
const { id } = useParams();
|
||||
return <div>GYM-DETAIL-{id}</div>;
|
||||
}
|
||||
|
||||
function renderPage() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<MemoryRouter initialEntries={['/gyms/g1/logs']}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Routes>
|
||||
<Route path="/gyms/:id" element={<DetailStub />} />
|
||||
<Route path="/gyms/:id/logs" element={<GymLogsPage />} />
|
||||
</Routes>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setAccessToken('admin-tok');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('admin GymLogsPage', () => {
|
||||
it('renderuje wspólną tabelę logów z operacjami siłowni', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes('/logs')) {
|
||||
return jsonResponse(200, { logs: [LOG2, LOG1], total: 2 });
|
||||
}
|
||||
return jsonResponse(200, GYM);
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
expect(await screen.findByText('Siłownia utworzona')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Ada Admin').length).toBeGreaterThan(0);
|
||||
// szczegóły membership: powiązanie z siłownią widoczne w kolumnie szczegółów
|
||||
expect(await screen.findByText('siłownia: g1')).toBeInTheDocument();
|
||||
// powrót na detal siłowni
|
||||
expect(screen.getByRole('link', { name: /Wstecz/ })).toHaveAttribute('href', '/gyms/g1');
|
||||
});
|
||||
|
||||
it('pusty stan, gdy brak operacji powiązanych z siłownią', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes('/logs')) return jsonResponse(200, { logs: [], total: 0 });
|
||||
return jsonResponse(200, GYM);
|
||||
}),
|
||||
);
|
||||
renderPage();
|
||||
expect(await screen.findByText('Brak operacji powiązanych z tą siłownią.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('„Pokaż jeszcze” dokłada limit i odpytuje API', async () => {
|
||||
const urls: string[] = [];
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
urls.push(url);
|
||||
if (url.includes('/logs'))
|
||||
return jsonResponse(200, {
|
||||
logs: [LOG1],
|
||||
total: 60,
|
||||
});
|
||||
return jsonResponse(200, GYM);
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderPage();
|
||||
await user.click(await screen.findByRole('button', { name: 'Pokaż jeszcze 59 wpisów' }));
|
||||
await vi.waitFor(() => expect(urls.some((u) => u.includes('limit=100'))).toBe(true));
|
||||
});
|
||||
});
|
||||
@@ -6,16 +6,33 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import GymsList from '../src/pages/gyms/GymsList';
|
||||
import { setAccessToken } from '../src/api/client';
|
||||
import { useListSearch } from '../src/store/list-search';
|
||||
import type { Gym } from '../src/api/types';
|
||||
import type { AdminGymListItem } from '../src/api/types';
|
||||
|
||||
const G1: Gym = {
|
||||
const G1: AdminGymListItem = {
|
||||
id: 'g1',
|
||||
name: 'Gym A',
|
||||
location: 'Warszawa',
|
||||
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
|
||||
addressLine1: 'Bobrowiecka 12',
|
||||
addressLine2: null,
|
||||
postalCode: '02-847',
|
||||
city: 'Warszawa',
|
||||
countryCode: 'PL',
|
||||
availability: [
|
||||
{ start: '06:00', end: '22:00' },
|
||||
{ start: '06:00', end: '22:00' },
|
||||
{ start: '06:00', end: '22:00' },
|
||||
{ start: '06:00', end: '22:00' },
|
||||
{ start: '06:00', end: '22:00' },
|
||||
{ start: '06:00', end: '22:00' },
|
||||
{ start: '06:00', end: '22:00' },
|
||||
],
|
||||
capacity: 50,
|
||||
equipment: [],
|
||||
kind: 'REAL',
|
||||
isPrivate: false,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
_count: { memberships: 12 },
|
||||
owners: [{ id: 'u1', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' }],
|
||||
};
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
@@ -40,6 +57,11 @@ function DetailStub() {
|
||||
return <div>GYM-DETAIL-{id}</div>;
|
||||
}
|
||||
|
||||
function UserStub() {
|
||||
const { id } = useParams();
|
||||
return <div>USER-{id}</div>;
|
||||
}
|
||||
|
||||
function renderGyms() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
@@ -48,6 +70,7 @@ function renderGyms() {
|
||||
<Routes>
|
||||
<Route path="/gyms" element={<GymsList />} />
|
||||
<Route path="/gyms/:id" element={<DetailStub />} />
|
||||
<Route path="/users/:id" element={<UserStub />} />
|
||||
</Routes>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
@@ -64,47 +87,67 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('admin GymsList page', () => {
|
||||
it('lists gyms fetched from the API', async () => {
|
||||
it('lists gyms fetched from the API with admin data (address, owners, today; no app column)', async () => {
|
||||
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
|
||||
renderGyms();
|
||||
expect(await screen.findByText('Gym A')).toBeInTheDocument();
|
||||
expect(screen.getByText('Warszawa')).toBeInTheDocument();
|
||||
expect(screen.getByText('12/50 członków')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bobrowiecka 12, 02-847 Warszawa')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: 'Anna Kowalska' })).toHaveAttribute(
|
||||
'href',
|
||||
'/users/u1',
|
||||
);
|
||||
// komórek licznika bez duplikowania nagłówka „Członkowie”
|
||||
expect(screen.getByText('12/50')).toBeInTheDocument();
|
||||
expect(screen.getByText('6:00–22:00')).toBeInTheDocument();
|
||||
// kolumna Aplikacja usunięta — do apki prowadzi akcja z topbara konsoli
|
||||
expect(screen.queryByRole('link', { name: 'Otwórz w aplikacji' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clicking a gym opens the detail page', async () => {
|
||||
it('klik w dowolnym miejscu wiersza otwiera konsolę siłowni', async () => {
|
||||
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
|
||||
const user = userEvent.setup();
|
||||
renderGyms();
|
||||
await user.click(await screen.findByRole('link', { name: 'Gym A' }));
|
||||
await user.click(await screen.findByText('Bobrowiecka 12, 02-847 Warszawa'));
|
||||
expect(await screen.findByText('GYM-DETAIL-g1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters gyms by the search box', async () => {
|
||||
it('klik w link właściciela prowadzi do profilu usera, nie do konsoli', async () => {
|
||||
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
|
||||
const user = userEvent.setup();
|
||||
renderGyms();
|
||||
expect(await screen.findByText('Gym A')).toBeInTheDocument();
|
||||
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
|
||||
act(() => useListSearch.getState().setQuery('gyms', 'kraków'));
|
||||
expect(screen.queryByText('Gym A')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument();
|
||||
await user.click(await screen.findByRole('link', { name: 'Anna Kowalska' }));
|
||||
expect(await screen.findByText('USER-u1')).toBeInTheDocument();
|
||||
expect(screen.queryByText('GYM-DETAIL-g1')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('karty REAL pokazują licznik „teraz” z endpointu occupancy', async () => {
|
||||
const realGym: Gym = { ...G1, kind: 'REAL' };
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes('/admin/gyms/occupancy'))
|
||||
return jsonResponse(200, {
|
||||
gyms: [{ gymId: 'g1', name: 'Gym A', capacity: 50, count: 3 }],
|
||||
});
|
||||
return jsonResponse(200, { gyms: [realGym] });
|
||||
}),
|
||||
);
|
||||
it('search queries the API with the q parameter (server-side)', async () => {
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes('?q=')) return jsonResponse(200, { gyms: [] });
|
||||
return jsonResponse(200, { gyms: [G1] });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
renderGyms();
|
||||
expect(await screen.findByText('Gym A')).toBeInTheDocument();
|
||||
expect(await screen.findByText('teraz: 3 osoby (50)')).toBeInTheDocument();
|
||||
// wyszukiwarka jest w menu kontekstowym (Layout) — zapytanie ustawiamy przez store
|
||||
act(() => useListSearch.getState().setQuery('gyms', 'kraków'));
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const urls = fetchMock.mock.calls.map((c) => String(c[0]));
|
||||
expect(urls.some((u) => u.includes('/admin/gyms?q=krak%C3%B3w'))).toBe(true);
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
expect(await screen.findByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument();
|
||||
// klient-side filtrowanie nie istnieje: bez q pełna lista znów jest w zapytaniu
|
||||
const urls = fetchMock.mock.calls.map((c) => String(c[0]));
|
||||
expect(urls.some((u) => u.endsWith('/admin/gyms'))).toBe(true);
|
||||
});
|
||||
|
||||
it('brak właścicieli sygnalizowany w kolumnie Właściciele', async () => {
|
||||
mockFetchSequence(jsonResponse(200, { gyms: [{ ...G1, owners: [] }] }));
|
||||
renderGyms();
|
||||
expect(await screen.findByText('Gym A')).toBeInTheDocument();
|
||||
expect(screen.getByText('brak')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,17 +19,32 @@ test('sidebar zawiera link „Aplikacja” prowadzący do aplikacji użytkownika
|
||||
await expect(link).toHaveAttribute('href', /:5173\/?$/);
|
||||
});
|
||||
|
||||
test('kliknięcie w siłownię otwiera podstronę z detalami', async ({ page }) => {
|
||||
test('kliknięcie w siłownię otwiera konsolę z KPI, godzinami i członkami', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
await expect(page.getByRole('heading', { name: 'Fit Factory' })).toBeVisible();
|
||||
// pasek godzin pod hero: forma zegarowa z minutami + wyjątek harmonogramu
|
||||
await expect(page.locator('span:visible', { hasText: '6:00–22:00' })).toBeVisible();
|
||||
await expect(page.getByText('10:00–14:00')).toBeVisible();
|
||||
// topbar = kategoria „Siłownia”, nazwa siłowni dopiero w treści (h2)
|
||||
await expect(page.getByRole('heading', { level: 1, name: 'Siłownia' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { level: 2, name: 'Fit Factory' })).toBeVisible();
|
||||
// konsola admina: KPI członków (licznik/pojemność) i tabela członków
|
||||
await expect(page.getByText('12/120')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { level: 3, name: /Członkowie/ })).toBeVisible();
|
||||
await expect(page.getByRole('table')).toBeVisible();
|
||||
// pasek godzin w sekcji godzin: forma zegarowa z minutami
|
||||
await expect(page.getByText('6:00–22:00', { exact: true })).toBeVisible();
|
||||
// wyjątki harmonogramu edytowane w modalu „Informacje” (jak w apce)
|
||||
await page.getByRole('button', { name: 'Zarządzaj' }).click();
|
||||
await page.getByRole('button', { name: 'Informacje' }).click();
|
||||
const infoDialog = page.getByRole('dialog');
|
||||
await expect(infoDialog.getByText('Dodaj wyjątek — data i tryb dnia')).toBeVisible();
|
||||
await expect(infoDialog.getByText('10:00–14:00')).toBeVisible();
|
||||
await page.keyboard.press('Escape');
|
||||
// menu kontekstowe podstrony detalu nie dziedziczy akcji ze strony listy (brak ikony ➕)
|
||||
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
|
||||
// przycisk „← Wróć” w nagłówku treści → lista wszystkich siłowni
|
||||
await page.getByRole('link', { name: 'Wróć' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms$/);
|
||||
});
|
||||
|
||||
test('ponowne dodanie tego samego typu tworzy osobną instancję (bez inkrementacji ilości)', async ({
|
||||
@@ -39,12 +54,12 @@ test('ponowne dodanie tego samego typu tworzy osobną instancję (bez inkrementa
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
await expect(page.getByText('Dywan ×3')).toBeVisible();
|
||||
|
||||
// akcja „Urządzenia" w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje) → podstrona urządzeń; edycja modalem z menu
|
||||
await page.getByRole('button', { name: 'Zarządzaj' }).click();
|
||||
await page.getByRole('button', { name: 'Urządzenia' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1\/equipment$/);
|
||||
await expect(page.getByText('Dywan ×3')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Edytuj urządzenia' }).click();
|
||||
const addReq = page.waitForRequest(
|
||||
(req) => req.url().endsWith('/admin/gyms/gym-1/equipment') && req.method() === 'POST',
|
||||
@@ -82,36 +97,58 @@ test('dodanie urządzenia z własnymi parametrami wysyła spec w POST', async ({
|
||||
});
|
||||
});
|
||||
|
||||
test('admin zarządza właścicielami siłowni z menu kontekstowego', async ({ page }) => {
|
||||
test('rola członka edytowana z menu wiersza — zapis wysyła PATCH z pełną listą ról', 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$/);
|
||||
|
||||
// modal Właściciele z rozwijanego „Zarządzaj” (desktop: kontrolka zbiera akcje)
|
||||
// (karta „Dane" usunięta — lista właścicieli dostępna tylko w modalu)
|
||||
await page.getByRole('button', { name: 'Zarządzaj' }).click();
|
||||
await page.locator('button[data-slot="button"]', { hasText: 'Właściciele' }).click();
|
||||
// klik w wiersz członka otwiera jego menu (brak kolumny akcji w tabeli)
|
||||
const janRow = page.locator('tr', { hasText: 'Jan Kowalski' });
|
||||
await janRow.click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByText('Anna Kowalska')).toBeVisible();
|
||||
await expect(dialog.getByText('Role w siłowni')).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',
|
||||
// do pełnej listy MEMBER+TRAINER dopisujemy OWNER → PATCH z pełną listą
|
||||
await dialog.getByRole('checkbox', { name: 'Właściciel — Jan Kowalski' }).click();
|
||||
const patchReq = page.waitForRequest(
|
||||
(req) =>
|
||||
req.url().includes('/admin/users/user-1/memberships/gym-1') && req.method() === 'PATCH',
|
||||
);
|
||||
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();
|
||||
await dialog.getByRole('button', { name: 'Zapisz role' }).click();
|
||||
const roles = (await patchReq).postDataJSON().roles as string[];
|
||||
expect(roles).toEqual(expect.arrayContaining(['MEMBER', 'TRAINER', 'OWNER']));
|
||||
await expect(janRow.getByText('Właściciel', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
// odebranie roli = DELETE /admin/gyms/gym-1/owners/:userId
|
||||
test('wyrzucenie członka z siłowni — wymagalny powód i DELETE z powodem w ciele', 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$/);
|
||||
|
||||
const janRow = page.locator('tr', { hasText: 'Jan Kowalski' });
|
||||
await janRow.click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
|
||||
// bez powodu usunięcie zablokowane
|
||||
const removeBtn = dialog.getByRole('button', { name: 'Wyrzuć członka' });
|
||||
await expect(removeBtn).toBeDisabled();
|
||||
|
||||
await dialog.getByRole('textbox', { name: 'Powód' }).fill('Wielokrotne łamanie regulaminu');
|
||||
const delReq = page.waitForRequest(
|
||||
(req) => req.url().includes('/admin/gyms/gym-1/owners/user-owner') && req.method() === 'DELETE',
|
||||
(req) =>
|
||||
req.url().includes('/admin/users/user-1/memberships/gym-1') && req.method() === 'DELETE',
|
||||
);
|
||||
await dialog.getByRole('button', { name: 'Odbierz rolę' }).first().click();
|
||||
await delReq;
|
||||
await expect(dialog.getByText('Anna Kowalska')).toHaveCount(0);
|
||||
await removeBtn.click();
|
||||
expect((await delReq).postDataJSON()).toEqual({ reason: 'Wielokrotne łamanie regulaminu' });
|
||||
|
||||
// stan mocka: członek znika z tabeli po refetchu
|
||||
await expect(page.locator('tr', { hasText: 'Jan Kowalski' })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('kliknięcie w użytkownika otwiera przegląd profilu (wzór z apki)', async ({ page }) => {
|
||||
@@ -521,7 +558,46 @@ test('wyszukiwarka w menu kontekstowym filtruje listę siłowni', async ({ page
|
||||
// po logowaniu jesteśmy na /gyms
|
||||
await expect(page.getByText('Fit Factory')).toBeVisible();
|
||||
await expect(page.getByText('Mega Gym')).toBeVisible();
|
||||
// wyszukiwanie jest po stronie API — żądanie niesie parametr q
|
||||
const qRequest = page.waitForRequest(
|
||||
(req) => req.url().includes('/api/v1/admin/gyms?') && req.url().includes('q=krak'),
|
||||
);
|
||||
await page.getByRole('searchbox', { name: 'Szukaj siłowni' }).fill('kraków');
|
||||
await expect(page.getByText('Fit Factory')).not.toBeVisible();
|
||||
await expect(page.getByText('Mega Gym')).toBeVisible();
|
||||
await expect(qRequest).resolves.toBeTruthy();
|
||||
});
|
||||
|
||||
test('logi siłowni: akcja „Logi” w menu prowadzi na podstronę z tabelą operacji', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
// akcja „Logi" w rozwijanym „Zarządzaj" → podstrona logów
|
||||
await page.getByRole('button', { name: 'Zarządzaj' }).click();
|
||||
await page.getByRole('button', { name: 'Logi' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1\/logs$/);
|
||||
// wspólna tabela logów: kolumny i wpisy
|
||||
await expect(page.getByRole('columnheader', { name: 'Data' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { level: 1, name: 'Logi siłowni' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('akcja „Otwórz w aplikacji” otwiera widok siłowni z perspektywy usera', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
// aplikacja usera nie działa w tym teście — podstawiamy stub pod jej origin,
|
||||
// żeby popup zatrzymał się na docelowym URL zamiast chrome-error
|
||||
await page.context().route('http://localhost:5173/**', (route) =>
|
||||
route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>app</title>' }),
|
||||
);
|
||||
// osobny przycisk w topbarze konsoli (dodatek, nie główna ścieżka) — popup na APP_URL
|
||||
const popupPromise = page.waitForEvent('popup');
|
||||
await page.getByRole('button', { name: 'Otwórz w aplikacji' }).click();
|
||||
const popup = await popupPromise;
|
||||
// dev (vite 5174) → port aplikacji 5173 wg mapowania z src/config.ts
|
||||
await expect(popup).toHaveURL(/:5173\/gyms\/gym-1$/);
|
||||
});
|
||||
|
||||
@@ -20,10 +20,10 @@ test('admin zarządza galerią zdjęć siłowni REAL (upload/okładka/usuwanie)'
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
await expect(page.getByRole('link', { name: /Galeria zdjęć/ })).toBeVisible();
|
||||
|
||||
// kafelek galerii → podstrona galerii (read-only)
|
||||
await page.getByRole('link', { name: /Galeria zdjęć/ }).click();
|
||||
// akcja „Galeria" w rozwijanym „Zarządzaj” → podstrona galerii (read-only)
|
||||
await page.getByRole('button', { name: 'Zarządzaj' }).click();
|
||||
await page.getByRole('button', { name: 'Galeria' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1\/gallery$/);
|
||||
await expect(page.getByRole('heading', { name: 'Galeria zdjęć' })).toBeVisible();
|
||||
|
||||
|
||||
26
admin/test/e2e/gym-qr.spec.ts
Normal file
26
admin/test/e2e/gym-qr.spec.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
import { test, expect } from './fixtures';
|
||||
import { mockApi, TEST_GYM } from './mock-api';
|
||||
|
||||
async function loginAsAdmin(page: Page) {
|
||||
await page.goto('/login');
|
||||
await page.locator('input[type="email"]').fill('admin@fitos.pl');
|
||||
await page.locator('input[type="password"]').fill('haslo123');
|
||||
await page.getByRole('button', { name: 'Zaloguj' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms$/);
|
||||
}
|
||||
|
||||
test('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
|
||||
// akcja „Kod QR” w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje)
|
||||
await page.getByRole('button', { name: 'Zarządzaj' }).click();
|
||||
await page.getByRole('button', { name: 'Kod QR' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByRole('heading', { name: 'Kod QR siłowni' })).toBeVisible();
|
||||
await expect(dialog.getByRole('img', { name: 'Fit Factory' })).toBeVisible();
|
||||
await expect(dialog.getByText(/\/gyms\/gym-1\/checkin/)).toBeVisible();
|
||||
});
|
||||
@@ -86,7 +86,10 @@ export const TEST_GYM: Gym = {
|
||||
],
|
||||
coverPhoto: '/gyms/gym-1/photos/photo-1',
|
||||
photos: TEST_GYM_PHOTOS,
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
updatedAt: '2026-01-05T00:00:00.000Z',
|
||||
_count: { memberships: 12 },
|
||||
owners: [{ id: 'user-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' }],
|
||||
};
|
||||
|
||||
export const TEST_GYM_2: Gym = {
|
||||
@@ -99,7 +102,10 @@ export const TEST_GYM_2: Gym = {
|
||||
isPrivate: false,
|
||||
equipment: [],
|
||||
coverPhoto: null,
|
||||
createdAt: '2026-02-01T00:00:00.000Z',
|
||||
updatedAt: '2026-02-05T00:00:00.000Z',
|
||||
_count: { memberships: 4 },
|
||||
owners: [],
|
||||
};
|
||||
|
||||
/** Właściciele (OWNER) siłowni gym-1 — tylko w odpowiedzi GET /admin/gyms/gym-1. */
|
||||
@@ -107,6 +113,36 @@ export const TEST_GYM_OWNERS = [
|
||||
{ id: 'user-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' },
|
||||
];
|
||||
|
||||
/** Członkowie siłowni gym-1 — GET /admin/gyms/gym-1/members (tabela w konsoli detalu). */
|
||||
export const TEST_GYM_MEMBERS = [
|
||||
{
|
||||
membershipId: 'membership-1',
|
||||
roles: ['OWNER'],
|
||||
joinedAt: '2026-01-02T10:00:00.000Z',
|
||||
checkedInNow: false,
|
||||
user: {
|
||||
id: 'user-owner',
|
||||
firstName: 'Anna',
|
||||
lastName: 'Kowalska',
|
||||
email: 'anna@fitos.pl',
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
},
|
||||
{
|
||||
membershipId: 'membership-2',
|
||||
roles: ['MEMBER', 'TRAINER'],
|
||||
joinedAt: '2026-02-01T10:00:00.000Z',
|
||||
checkedInNow: true,
|
||||
user: {
|
||||
id: 'user-1',
|
||||
firstName: 'Jan',
|
||||
lastName: 'Kowalski',
|
||||
email: 'jan@fitos.pl',
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** Wniosek o weryfikację wirtualnej siłowni (PENDING, z dokumentem). */
|
||||
export const TEST_CLAIM_VERIFICATION: GymClaim = {
|
||||
id: 'claim-v1',
|
||||
@@ -440,6 +476,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
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 }));
|
||||
// Stateful: członkowie gym-1 — menu członka (PATCH ról / DELETE z powodem).
|
||||
const membersState = TEST_GYM_MEMBERS.map((m) => ({ ...m, roles: [...m.roles] }));
|
||||
const coverOf = (photos: typeof gymPhotosState) =>
|
||||
photos.length ? `/gyms/gym-1/photos/${photos[0].id}` : null;
|
||||
const gymDetailBody = () =>
|
||||
@@ -456,41 +494,6 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() }),
|
||||
);
|
||||
|
||||
// Live occupancy listy siłowni (GET /admin/gyms/occupancy) — licznik „teraz” na kartach REAL.
|
||||
page.route('**/api/v1/admin/gyms/occupancy', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
gyms: [{ gymId: 'gym-1', name: TEST_GYM.name, capacity: TEST_GYM.capacity, count: 7 }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
// Telemetria bytności (GET /admin/gyms/gym-1/presence-stats).
|
||||
page.route('**/api/v1/admin/gyms/*/presence-stats*', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
gym: { id: 'gym-1', name: TEST_GYM.name, kind: 'REAL', capacity: TEST_GYM.capacity },
|
||||
stats: {
|
||||
visits: 96,
|
||||
avgStayMinutes: 63,
|
||||
heatmap: [
|
||||
{ day: 1, hour: 18, count: 9 },
|
||||
{ day: 4, hour: 19, count: 6 },
|
||||
],
|
||||
topGyms: [{ gymId: 'gym-1', name: TEST_GYM.name, count: 96 }],
|
||||
peak: 9,
|
||||
topEquipment: [{ equipmentId: 'eq-1', name: 'ławka', nameEn: 'Bench', count: 41 }],
|
||||
live: 7,
|
||||
visitsPerDay: 3.2,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
// POST /gyms/gym-1/photos — upload (multipart, pole `photos`).
|
||||
page.route('**/api/v1/gyms/*/photos', (route) => {
|
||||
const req = route.request();
|
||||
@@ -541,24 +544,91 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/admin/gyms', (route) => {
|
||||
const list = (gyms as { gyms?: Array<Record<string, unknown>> } | null)?.gyms;
|
||||
const body =
|
||||
list && gyms
|
||||
? {
|
||||
...gyms,
|
||||
gyms: list.map((g) =>
|
||||
g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g,
|
||||
),
|
||||
}
|
||||
: gyms;
|
||||
// Lista siłowni (bez `/gym-1`) — wyszukiwanie i filtr `kind` po stronie „API”.
|
||||
page.route(
|
||||
(url) => /\/api\/v1\/admin\/gyms(\?.*)?$/.test(url.pathname + (url.search ?? '')),
|
||||
(route) => {
|
||||
const raw = (gyms as { gyms?: Array<Record<string, unknown>> } | null)?.gyms ?? [];
|
||||
const params = new URL(route.request().url()).searchParams;
|
||||
const q = (params.get('q') ?? '').trim().toLowerCase();
|
||||
const kind = params.get('kind');
|
||||
const filtered = raw.filter((g) => {
|
||||
if (kind && g.kind !== kind) return false;
|
||||
if (!q) return true;
|
||||
const hay = [
|
||||
String(g.name ?? ''),
|
||||
String(g.location ?? ''),
|
||||
String(g.city ?? ''),
|
||||
String(g.addressLine1 ?? ''),
|
||||
String(g.postalCode ?? ''),
|
||||
...(Array.isArray(g.owners)
|
||||
? (g.owners as Array<Record<string, unknown>>).flatMap((o) => [
|
||||
String(o.firstName ?? ''),
|
||||
String(o.lastName ?? ''),
|
||||
String(o.email ?? ''),
|
||||
])
|
||||
: []),
|
||||
]
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
return hay.includes(q);
|
||||
});
|
||||
const body =
|
||||
gyms != null
|
||||
? {
|
||||
...gyms,
|
||||
gyms: filtered.map((g) =>
|
||||
g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g,
|
||||
),
|
||||
}
|
||||
: gyms;
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Logi pojedynczej siłowni (GET /admin/gyms/:id/logs).
|
||||
page.route('**/api/v1/admin/gyms/*/logs*', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(logs),
|
||||
}),
|
||||
);
|
||||
|
||||
// Członkowie pojedynczej siłowni (GET /admin/gyms/:id/members) — q i role po stronie „API";
|
||||
// role żyją w membersState (menu członka PATCH/DELETE aktualizuje je na bieżąco).
|
||||
page.route('**/api/v1/admin/gyms/*/members*', (route) => {
|
||||
const params = new URL(route.request().url()).searchParams;
|
||||
const q = (params.get('q') ?? '').trim().toLowerCase();
|
||||
const role = params.get('role');
|
||||
const list = membersState.filter(
|
||||
(m) =>
|
||||
(!role || m.roles.includes(role)) &&
|
||||
(!q ||
|
||||
`${m.user.firstName ?? ''} ${m.user.lastName ?? ''} ${m.user.email}`
|
||||
.toLowerCase()
|
||||
.includes(q)),
|
||||
);
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify({ members: list, total: list.length }),
|
||||
});
|
||||
});
|
||||
|
||||
// Wnioski i zaproszenia pojedynczej siłowni (GET /admin/gyms/:id/related).
|
||||
page.route('**/api/v1/admin/gyms/*/related*', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ claims: [], invitations: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
// POST = zawsze NOWA instancja; PATCH/DELETE po id instancji (GymEquipment.id).
|
||||
page.route('**/api/v1/admin/gyms/*/equipment', (route) => {
|
||||
const req = route.request();
|
||||
@@ -613,7 +683,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
return route.fulfill({ status: 204 });
|
||||
});
|
||||
|
||||
// Właściciele (OWNER): POST nadaje / DELETE odbiera rolę — stanowo (gymOwnersState).
|
||||
// Właściciele (OWNER): POST nadaje / DELETE odbiera rolę — stanowo (gymOwnersState + membersState).
|
||||
page.route('**/api/v1/admin/gyms/*/owners**', (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
@@ -627,6 +697,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
lastName: u.lastName,
|
||||
email: u.email,
|
||||
});
|
||||
const m = membersState.find((x) => x.user.id === u.id);
|
||||
if (m && !m.roles.includes('OWNER')) m.roles.push('OWNER');
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
@@ -638,6 +710,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
const userId = req.url().match(/owners\/([^/?]+)/)?.[1];
|
||||
const idx = gymOwnersState.findIndex((o) => o.id === userId);
|
||||
if (idx >= 0) gymOwnersState.splice(idx, 1);
|
||||
const m = userId ? membersState.find((x) => x.user.id === userId) : undefined;
|
||||
if (m) m.roles = m.roles.filter((r) => r !== 'OWNER');
|
||||
return route.fulfill({ status: 204 });
|
||||
}
|
||||
return route.fulfill({ status: 405 });
|
||||
@@ -769,13 +843,27 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
}),
|
||||
);
|
||||
|
||||
page.route('**/api/v1/admin/users/*/memberships/*', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ membership: {} }),
|
||||
}),
|
||||
);
|
||||
// PATCH ról / DELETE członkostwa (menu członka w konsoli siłowni) — stanowo (membersState).
|
||||
page.route('**/api/v1/admin/users/*/memberships/*', (route) => {
|
||||
const req = route.request();
|
||||
const userId = decodeURIComponent(req.url().match(/users\/([^/]+)\/memberships\//)?.[1] ?? '');
|
||||
if (req.method() === 'PATCH') {
|
||||
const body = JSON.parse(req.postData() || '{}');
|
||||
const m = membersState.find((x) => x.user.id === userId);
|
||||
if (m && Array.isArray(body.roles)) m.roles = body.roles;
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ membership: { userId, gymId: 'gym-1', roles: m?.roles ?? [] } }),
|
||||
});
|
||||
}
|
||||
if (req.method() === 'DELETE') {
|
||||
const idx = membersState.findIndex((x) => x.user.id === userId);
|
||||
if (idx >= 0) membersState.splice(idx, 1);
|
||||
return route.fulfill({ status: 204 });
|
||||
}
|
||||
return route.fulfill({ status: 405 });
|
||||
});
|
||||
|
||||
// ---------- gym claims (verifications) ----------
|
||||
// Kolejność rejestracji: list (catch-all) najpierw, potem coraz bardziej
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
import { test, expect } from './fixtures';
|
||||
import { mockApi, TEST_GYM } from './mock-api';
|
||||
|
||||
async function loginAsAdmin(page: Page) {
|
||||
await page.goto('/login');
|
||||
await page.locator('input[type="email"]').fill('admin@fitos.pl');
|
||||
await page.locator('input[type="password"]').fill('haslo123');
|
||||
await page.getByRole('button', { name: 'Zaloguj' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms$/);
|
||||
}
|
||||
|
||||
test('lista siłowni pokazuje licznik „teraz” na karcie REAL', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await expect(page.getByText('teraz: 7 osób (120)')).toBeVisible();
|
||||
});
|
||||
|
||||
test('detal REAL pokazuje kartę bytności z telemetrią', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Bytność' })).toBeVisible();
|
||||
await expect(page.getByText('teraz w środku')).toBeVisible();
|
||||
await expect(page.getByText('7', { exact: true })).toBeVisible();
|
||||
await expect(page.getByText('wizyty (30 dni)')).toBeVisible();
|
||||
await expect(page.getByText('96', { exact: true })).toBeVisible();
|
||||
await expect(page.getByText('ławka · 41')).toBeVisible();
|
||||
});
|
||||
|
||||
test('widok ogólny bytności ma stały zakres 30 dni (bez filtra okresu)', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page.getByText('wizyty (30 dni)')).toBeVisible();
|
||||
await expect(page.getByRole('combobox', { name: 'Zakres dat bytności' })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
|
||||
|
||||
// akcja „Kod QR” w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje)
|
||||
await page.getByRole('button', { name: 'Zarządzaj' }).click();
|
||||
await page.getByRole('button', { name: 'Kod QR' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(dialog.getByRole('heading', { name: 'Kod QR siłowni' })).toBeVisible();
|
||||
await expect(dialog.getByRole('img', { name: 'Fit Factory' })).toBeVisible();
|
||||
await expect(dialog.getByText(/\/gyms\/gym-1\/checkin/)).toBeVisible();
|
||||
});
|
||||
Reference in New Issue
Block a user