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:
tisachi
2026-10-29 21:21:03 +01:00
parent 2305649493
commit cc2f0f9166
26 changed files with 2781 additions and 2001 deletions

View File

@@ -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">

View File

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

View File

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

View File

@@ -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). */

View 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>
)}
</>
);
}

View File

@@ -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>
)}