diff --git a/admin/src/App.tsx b/admin/src/App.tsx index cebcc79..2336941 100644 --- a/admin/src/App.tsx +++ b/admin/src/App.tsx @@ -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() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/admin/src/api/queries.ts b/admin/src/api/queries.ts index 008f657..53d5173 100644 --- a/admin/src/api/queries.ts +++ b/admin/src/api/queries.ts @@ -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(`/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(`/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(`/admin/gyms/${gymId}/related`), + enabled: !!gymId, + }); +} /** Bieżący użytkownik (admin) — profil + członkostwa, jak `useMe` w aplikacji. */ export function useMe() { diff --git a/admin/src/api/types.ts b/admin/src/api/types.ts index 4a74736..184ce8f 100644 --- a/admin/src/api/types.ts +++ b/admin/src/api/types.ts @@ -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. */ diff --git a/admin/src/components/LogTable.tsx b/admin/src/components/LogTable.tsx new file mode 100644 index 0000000..c4141c6 --- /dev/null +++ b/admin/src/components/LogTable.tsx @@ -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 => + 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 ( +
+ + + + + + + + + + + + {logs.map((log) => ( + + + + + + + + ))} + +
+ {t('colDate')} + + {t('colUser')} + + {t('colAction')} + + {t('colEntity')} + + {t('colDetails')} +
+
{fmtDate(log.createdAt)}
+
{fmtTime(log.createdAt)}
+
+
{actorName(log)}
+
{log.actor.email}
+
+ {log.actor.id} +
+
+ + {actionLabel(log.action)} + + +
{t(`entities.${log.entityType}`, { defaultValue: log.entityType })}
+ {entityName(log) && ( +
{entityName(log)}
+ )} +
+ {detailsLines(log).length > 0 ? ( +
+ {detailsLines(log).map((line) => ( +
{line}
+ ))} +
+ ) : ( + '—' + )} +
+
+ ); +} diff --git a/admin/src/components/gyms/AnnouncementsSection.tsx b/admin/src/components/gyms/AnnouncementsSection.tsx new file mode 100644 index 0000000..95b688e --- /dev/null +++ b/admin/src/components/gyms/AnnouncementsSection.tsx @@ -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(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 ( +
+
+ {t('announcementSendTo', { name: gym.name })} + + setTitle(e.target.value)} + maxLength={120} + placeholder={t('announcementTitlePh')} + /> + + +