import { useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useQuery } from '@tanstack/react-query'; 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 { useListSearch } from '../store/list-search'; import i18n from '../i18n'; import { fmtDateTime } from '../lib/format'; const t = (key: string, options?: Record): string => String(i18n.t(`logs:${key}`, options as never)); export const ACTION_KEYS = [ 'user.registered', 'user.logged_in', 'user.logged_out', 'user.created', 'user.updated', 'user.status.changed', 'user.admin.changed', 'user.deleted', 'profile.updated', 'weight.added', 'weight.removed', 'circumference.added', 'circumference.removed', 'plan.created', 'plan.updated', 'plan.deleted', 'plan.activated', 'plan.abandoned', 'plan.completed', 'plan.reopened', 'plan.shared', 'plan.unshared', 'session.started', 'session.completed', 'session.abandoned', 'session.reopened', 'gym.created', 'gym.updated', 'gym.deleted', 'gym.joined', 'gym.invited', 'gym.invitation.accepted', 'gym.invitation.declined', 'gym.invitation.withdrawn', 'gym.owner.granted', 'gym.owner.revoked', 'gym.exception.added', 'gym.exception.removed', 'gym.equipment.added', 'gym.equipment.updated', 'gym.equipment.removed', 'gym.claim.created', 'gym.claim.approved', 'gym.claim.rejected', 'gym.claim.withdrawn', 'gym.photos.added', 'gym.photo.deleted', 'gym.photo.cover', 'gym.equipment.photos.added', 'gym.equipment.photo.deleted', 'membership.created', 'membership.updated', 'membership.deleted', 'coaching.invited', 'coaching.accepted', 'coaching.declined', 'coaching.withdrawn', 'coaching.archived', 'comment.added', 'comment.deleted', 'announcement.published', 'announcement.updated', 'announcement.deleted', 'exercise.created', 'exercise.updated', 'exercise.deleted', 'equipment.created', 'equipment.updated', 'equipment.deleted', 'focus_area.created', 'focus_area.updated', 'focus_area.deleted', ]; export function actionLabel(action: string) { return t(`actions.${action}`, { defaultValue: action }); } 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); } 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 naturalny tekst: `start: 2026-08-24 · wartość: 82.5 kg`. */ function detailsText(log: ActivityLog) { const d = log.details; if (!d) return null; const parts = Object.entries(d) .filter(([k]) => !HIDDEN_DETAIL_KEYS.has(k)) .map(([k, v]) => `${t(`details.${k}`, { defaultValue: k })}: ${formatDetailValue(log, k, v)}`); return parts.length > 0 ? parts.join(' · ') : null; } const PAGE_SIZE = 100; export default function Logs() { const { t: tr } = useTranslation('logs'); const [action, setAction] = useState(''); const [month, setMonth] = useState(''); const [limit, setLimit] = useState(PAGE_SIZE); const query = useListSearch((s) => s.queries.logs); const setQuery = useListSearch((s) => s.setQuery); const hasFilters = action !== '' || month !== ''; const { data, isLoading, error } = useQuery({ queryKey: ['admin-logs', action, month, limit], queryFn: () => { const params = new URLSearchParams(); if (action) params.set('action', action); if (month) { const [y, m] = month.split('-').map(Number); params.set('from', `${month}-01`); params.set('to', `${month}-${String(new Date(y, m, 0).getDate()).padStart(2, '0')}`); } params.set('limit', String(limit)); return api(`/admin/logs?${params.toString()}`); }, }); // miesiące do panelu selektora: z załadowanych logów + bieżący (chip lata) const availableMonths = useMemo(() => { const d = new Date(); const current = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; const set = new Set([...(data?.logs ?? []).map((l) => l.createdAt.slice(0, 7)), current]); return [...set].sort().reverse(); }, [data?.logs]); useTopbar({ title: tr('common:nav.logs'), search: 'logs', dateFilter: ( { setMonth(m); setLimit(PAGE_SIZE); }} availableMonths={availableMonths} allowAll /> ), filters: [
, ], filterActive: hasFilters, }); // wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony useEffect(() => () => setQuery('logs', ''), [setQuery]); const logs = data?.logs ?? []; const total = data?.total ?? 0; const filtered = query ? logs.filter((l) => { const q = query.toLowerCase(); const name = `${l.actor.firstName ?? ''} ${l.actor.lastName ?? ''}`.toLowerCase(); return l.actor.email.toLowerCase().includes(q) || (name.trim() && name.includes(q)); }) : logs; return ( <> {isLoading && } {error && ( {tr('common:errorPrefix')} {(error as Error).message} )} {!isLoading && !error && filtered.length === 0 && ( )} {!isLoading && !error && filtered.length > 0 && (
{filtered.map((log) => ( ))}
{tr('colDate')} {tr('colUser')} {tr('colAction')} {tr('colEntity')} {tr('colDetails')}
{formatLogDate(log.createdAt)}
{actorName(log)}
{log.actor.email}
{log.actor.id}
{actionLabel(log.action)}
{tr(`entities.${log.entityType}`, { defaultValue: log.entityType })}
{entityName(log) && (
{entityName(log)}
)}
{detailsText(log) ?? '—'}
)} {!isLoading && !error && logs.length < total && (
)} ); }