295 lines
10 KiB
TypeScript
295 lines
10 KiB
TypeScript
import { useEffect, useMemo, useState } from 'react';
|
|
import { useQuery } from '@tanstack/react-query';
|
|
import { ScrollText } from 'lucide-react';
|
|
import { useTopbar } from '../topbar';
|
|
import { MonthPicker } 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';
|
|
|
|
export const ACTION_LABELS: Record<string, string> = {
|
|
'user.registered': 'Rejestracja',
|
|
'profile.updated': 'Zmiana profilu',
|
|
'weight.added': 'Waga dodana',
|
|
'weight.removed': 'Waga usunięta',
|
|
'circumference.added': 'Obwód dodany',
|
|
'circumference.removed': 'Obwód usunięty',
|
|
'plan.created': 'Plan utworzony',
|
|
'plan.updated': 'Plan zaktualizowany',
|
|
'plan.deleted': 'Plan usunięty',
|
|
'plan.activated': 'Plan aktywowany',
|
|
'plan.abandoned': 'Plan porzucony',
|
|
'plan.completed': 'Plan ukończony',
|
|
'plan.reopened': 'Plan wznowiony',
|
|
'session.started': 'Sesja rozpoczęta',
|
|
'session.completed': 'Sesja zakończona',
|
|
'session.abandoned': 'Sesja porzucona',
|
|
'session.reopened': 'Sesja wznowiona',
|
|
'gym.created': 'Siłownia utworzona',
|
|
'gym.updated': 'Siłownia zaktualizowana',
|
|
'gym.deleted': 'Siłownia usunięta',
|
|
'gym.joined': 'Dołączono do siłowni',
|
|
'coaching.invited': 'Zaproszenie wysłane',
|
|
'coaching.accepted': 'Zaproszenie przyjęte',
|
|
'coaching.declined': 'Zaproszenie odrzucone',
|
|
'coaching.withdrawn': 'Zaproszenie wycofane',
|
|
'coaching.archived': 'Relacja zarchiwizowana',
|
|
};
|
|
|
|
const ENTITY_LABELS: Record<string, string> = {
|
|
user: 'Użytkownik',
|
|
plan: 'Plan',
|
|
session: 'Sesja',
|
|
gym: 'Siłownia',
|
|
coaching: 'Coaching',
|
|
};
|
|
|
|
export function actionLabel(action: string) {
|
|
return ACTION_LABELS[action] ?? 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';
|
|
return 'yellow';
|
|
}
|
|
|
|
const DATE_FORMAT = new Intl.DateTimeFormat('pl-PL', { dateStyle: 'medium', timeStyle: 'short' });
|
|
|
|
export function formatLogDate(iso: string) {
|
|
return DATE_FORMAT.format(new Date(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;
|
|
}
|
|
|
|
/** Polskie etykiety dla znanych kluczy szczegółów. */
|
|
const DETAIL_LABELS: Record<string, string> = {
|
|
email: 'e-mail',
|
|
fields: 'pola',
|
|
value: 'wartość',
|
|
name: 'nazwa',
|
|
title: 'tytuł',
|
|
startDate: 'start',
|
|
targetEmail: 'zaproszono',
|
|
traineeId: 'podopieczny',
|
|
};
|
|
|
|
/** 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]) => `${DETAIL_LABELS[k] ?? k}: ${formatDetailValue(log, k, v)}`);
|
|
return parts.length > 0 ? parts.join(' · ') : null;
|
|
}
|
|
|
|
const PAGE_SIZE = 100;
|
|
|
|
export default function 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<ActivityLogPage>(`/admin/logs?${params.toString()}`);
|
|
},
|
|
});
|
|
|
|
// lata do panelu selektora: z załadowanych logów + bieżący rok (nowe → stare)
|
|
const years = useMemo(() => {
|
|
const set = new Set((data?.logs ?? []).map((l) => l.createdAt.slice(0, 4)));
|
|
set.add(String(new Date().getFullYear()));
|
|
return [...set].sort().reverse();
|
|
}, [data?.logs]);
|
|
|
|
useTopbar({
|
|
title: 'Logi',
|
|
search: 'logs',
|
|
dateFilter: (
|
|
<MonthPicker
|
|
value={month}
|
|
onChange={(m) => {
|
|
setMonth(m);
|
|
setLimit(PAGE_SIZE);
|
|
}}
|
|
years={years}
|
|
/>
|
|
),
|
|
filters: [
|
|
<div key="action" className="w-48">
|
|
<Select
|
|
size="sm"
|
|
className="h-9"
|
|
aria-label="Filtruj po akcji"
|
|
value={action}
|
|
onChange={(e) => {
|
|
setAction(e.target.value);
|
|
setLimit(PAGE_SIZE);
|
|
}}
|
|
>
|
|
<option value="">Wszystkie akcje</option>
|
|
{Object.entries(ACTION_LABELS).map(([value, label]) => (
|
|
<option key={value} value={value}>
|
|
{label}
|
|
</option>
|
|
))}
|
|
</Select>
|
|
</div>,
|
|
],
|
|
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 && <Loading />}
|
|
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
|
|
|
|
{!isLoading && !error && filtered.length === 0 && (
|
|
<EmptyState
|
|
icon={ScrollText}
|
|
title="Brak zdarzeń"
|
|
description={
|
|
query
|
|
? 'Brak wyników dla podanego zapytania.'
|
|
: hasFilters
|
|
? 'Brak zdarzeń dla wybranych filtrów.'
|
|
: 'Zmiany wprowadzane przez użytkowników pojawią się tutaj.'
|
|
}
|
|
/>
|
|
)}
|
|
|
|
{!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]">
|
|
Data
|
|
</th>
|
|
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
|
Użytkownik
|
|
</th>
|
|
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
|
Akcja
|
|
</th>
|
|
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
|
Obiekt
|
|
</th>
|
|
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
|
|
Szczegóły
|
|
</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="whitespace-nowrap px-4 py-3 font-display text-dim tabular-nums">
|
|
{formatLogDate(log.createdAt)}
|
|
</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">
|
|
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<div>{ENTITY_LABELS[log.entityType] ?? log.entityType}</div>
|
|
{entityName(log) && (
|
|
<div className="text-[0.875rem] text-dim">{entityName(log)}</div>
|
|
)}
|
|
</td>
|
|
<td className="px-4 py-3 text-dim">{detailsText(log) ?? '—'}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
|
|
{!isLoading && !error && 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"
|
|
>
|
|
Pokaż więcej ({total - logs.length} pozostało)
|
|
</button>
|
|
</div>
|
|
)}
|
|
</>
|
|
);
|
|
}
|