323 lines
11 KiB
TypeScript
323 lines
11 KiB
TypeScript
import { useState } from 'react';
|
||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||
import {
|
||
Building2,
|
||
ChevronRight,
|
||
Dumbbell,
|
||
FileText,
|
||
Flame,
|
||
History,
|
||
Pencil,
|
||
Scale,
|
||
TrendingUp,
|
||
User,
|
||
type LucideIcon,
|
||
} from 'lucide-react';
|
||
import { useTopbar } from '../../topbar';
|
||
import { api } from '../../api/client';
|
||
import { BackButton, Badge, Card, ConfirmDialog, ErrorText, Loading } from '../../components/ui';
|
||
import { Avatar } from '../../components/Avatar';
|
||
import { displayName, fmtDate, fmtVolume } from '../../lib/format';
|
||
import {
|
||
useAdminUser,
|
||
useUserBodyParameters,
|
||
useUserClaims,
|
||
useUserHistory,
|
||
useUserKillstreak,
|
||
} from './user-queries';
|
||
|
||
/** Nazwa wyświetlana użytkownika (nick → imię+nazwisko → e-mail). */
|
||
export function userDisplayName(u: {
|
||
nickname?: string | null;
|
||
firstName?: string | null;
|
||
lastName?: string | null;
|
||
email: string;
|
||
}): string {
|
||
return displayName(u) === '—' ? u.email : displayName(u);
|
||
}
|
||
|
||
function sessionCountLabel(n: number) {
|
||
const mod10 = n % 10;
|
||
const mod100 = n % 100;
|
||
if (mod10 === 1 && mod100 !== 11) return `${n} sesja`;
|
||
if (mod10 >= 2 && mod10 <= 4 && !(mod100 >= 12 && mod100 <= 14)) return `${n} sesje`;
|
||
return `${n} sesji`;
|
||
}
|
||
|
||
/** Mini-statystyka: ikona + etykieta + wartość (+ meta). */
|
||
function MiniStat({
|
||
icon: Icon,
|
||
label,
|
||
value,
|
||
meta,
|
||
valueClassName = '',
|
||
}: {
|
||
icon: LucideIcon;
|
||
label: string;
|
||
value: string;
|
||
meta?: string;
|
||
valueClassName?: string;
|
||
}) {
|
||
return (
|
||
<div className="flex items-center gap-3 rounded-xl border border-line bg-(image:--card-grad) px-3.5 py-3 shadow-card">
|
||
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-[10px] bg-accent/10 text-accent-text">
|
||
<Icon className="h-4.5 w-4.5" />
|
||
</span>
|
||
<div className="min-w-0">
|
||
<div className="text-[11px] font-bold uppercase tracking-[0.1em] text-dim">{label}</div>
|
||
<div
|
||
className={`truncate font-display text-[1.05rem] font-bold leading-tight tabular-nums ${valueClassName}`.trim()}
|
||
>
|
||
{value}
|
||
</div>
|
||
{meta && <div className="truncate text-[0.75rem] text-dim">{meta}</div>}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** Wiersz sekcji: ikona + tytuł + podsumowanie + chevron; cały wiersz prowadzi na podstronę. */
|
||
function SectionLink({
|
||
to,
|
||
title,
|
||
icon: Icon,
|
||
summary,
|
||
}: {
|
||
to: string;
|
||
title: string;
|
||
icon: LucideIcon;
|
||
summary: string;
|
||
}) {
|
||
return (
|
||
<Link
|
||
to={to}
|
||
className="flex items-center gap-3 rounded-[10px] px-2 py-3 transition-colors hover:bg-line/20"
|
||
>
|
||
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-[10px] bg-accent/10 text-accent-text">
|
||
<Icon className="h-5 w-5" />
|
||
</span>
|
||
<span className="min-w-0 flex-1">
|
||
<span className="block text-[0.95rem] font-semibold">{title}</span>
|
||
<span className="block truncate text-[0.875rem] text-dim">{summary}</span>
|
||
</span>
|
||
<ChevronRight className="h-4 w-4 shrink-0 text-dim" aria-hidden />
|
||
</Link>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Przegląd użytkownika (admin): hero + pasek mini-statystyk + sekcje jako wiersze-listy.
|
||
* Struktura wzorowana na profilu z aplikacji (`/profile`) z dodatkami admina.
|
||
*/
|
||
export default function UserDetail() {
|
||
const { id } = useParams();
|
||
const navigate = useNavigate();
|
||
const { user, isLoading, error } = useAdminUser(id);
|
||
const { data: bp } = useUserBodyParameters(id);
|
||
const { data: hist } = useUserHistory(id);
|
||
const { data: ks } = useUserKillstreak(id);
|
||
const { data: claimsData } = useUserClaims(id);
|
||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||
const [busy, setBusy] = useState(false);
|
||
|
||
// Menu trzyma tylko akcje (edycja/usunięcie); nawigacja do podstron = wiersze w treści.
|
||
useTopbar({
|
||
title: user ? userDisplayName(user) : 'Użytkownik',
|
||
back: '/users',
|
||
actions: user
|
||
? [
|
||
{ label: 'Edytuj', icon: Pencil, to: `/users/${user.id}/edit` },
|
||
{ label: 'Usuń', variant: 'danger', onClick: () => setConfirmOpen(true) },
|
||
]
|
||
: [],
|
||
});
|
||
|
||
if (isLoading) return <Loading />;
|
||
if (error) return <ErrorText>Błąd: {(error as Error).message}</ErrorText>;
|
||
if (!user) return <ErrorText>Nie znaleziono użytkownika.</ErrorText>;
|
||
|
||
const remove = async () => {
|
||
setBusy(true);
|
||
try {
|
||
await api(`/admin/users/${user.id}`, { method: 'DELETE' });
|
||
navigate('/users');
|
||
} catch (err) {
|
||
alert(err instanceof Error ? err.message : 'Błąd');
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
};
|
||
|
||
const name = userDisplayName(user);
|
||
const memberships = user.memberships ?? [];
|
||
|
||
// ostatnia waga + delta vs poprzedni pomiar (spadek = accent, wzrost = warn)
|
||
const weightPoints = [...(bp?.weight ?? [])].sort((a, b) => a.date.localeCompare(b.date));
|
||
const latestWeight = weightPoints[weightPoints.length - 1];
|
||
const prevWeight = weightPoints[weightPoints.length - 2];
|
||
const weightDelta = latestWeight && prevWeight ? latestWeight.value - prevWeight.value : null;
|
||
const weightSummary = latestWeight
|
||
? `${latestWeight.value} kg · ${fmtDate(latestWeight.date)}`
|
||
: 'brak pomiarów';
|
||
|
||
// sesje: liczba + ostatnia data + objętość z ostatnich 7 dni (Σ planowane kg × powt.)
|
||
const sessions = hist?.sessions ?? [];
|
||
const lastSession = sessions.reduce<string | null>(
|
||
(max, s) => (max == null || s.startedAt > max ? s.startedAt : max),
|
||
null,
|
||
);
|
||
const historySummary =
|
||
sessions.length > 0
|
||
? `${sessionCountLabel(sessions.length)} · ostatnia ${fmtDate(lastSession!)}`
|
||
: 'brak sesji';
|
||
const weekAgo = Date.now() - 7 * 24 * 3600 * 1000;
|
||
const volume7d = sessions
|
||
.filter((s) => new Date(s.startedAt).getTime() >= weekAgo)
|
||
.flatMap((s) => s.exercises)
|
||
.flatMap((e) => e.sets)
|
||
.reduce(
|
||
(sum, st) =>
|
||
st.reps != null && st.planned?.loadKg != null ? sum + st.planned.loadKg * st.reps : sum,
|
||
0,
|
||
);
|
||
|
||
const gymsSummary =
|
||
memberships.length > 0
|
||
? memberships.map((m) => `${m.gym.name} (${m.roles.join(', ')})`).join(', ')
|
||
: 'brak';
|
||
|
||
const claims = claimsData?.claims ?? [];
|
||
const pendingClaims = claims.filter((c) => c.status === 'PENDING').length;
|
||
const claimsSummary =
|
||
claims.length === 0
|
||
? 'brak'
|
||
: pendingClaims > 0
|
||
? `${pendingClaims} oczekujących`
|
||
: `${claims.length} rozstrzygniętych`;
|
||
|
||
return (
|
||
<>
|
||
{/* md+ „Wstecz” w treści (telefon: „<” w topbarze) — jak na GymDetail i podstronach */}
|
||
<BackButton to="/users" className="mb-4" />
|
||
|
||
{/* Hero: avatar + nazwa + e-mail + nick/admin/role siłowni */}
|
||
<div className="mb-4 flex flex-wrap items-center gap-4 rounded-xl border border-line bg-(image:--card-grad) p-5 shadow-card">
|
||
<Avatar name={name} size={56} />
|
||
<div className="min-w-0 flex-1">
|
||
<div className="truncate font-display text-[1.3rem] font-bold tracking-[-0.02em]">
|
||
{name}
|
||
</div>
|
||
<div className="truncate text-dim text-[0.8125rem]">{user.email}</div>
|
||
<div className="text-[0.75rem] text-dim">
|
||
Utworzony {new Date(user.createdAt).toLocaleDateString('pl-PL')}
|
||
</div>
|
||
</div>
|
||
<span className="flex flex-wrap items-center gap-1.5">
|
||
{user.nickname && <Badge color="blue">@{user.nickname}</Badge>}
|
||
{user.isAdmin && <Badge color="blue">Admin</Badge>}
|
||
{memberships.length > 0 && <Badge>{memberships.length}</Badge>}
|
||
</span>
|
||
</div>
|
||
|
||
{/* Pasek mini-statystyk: 2×2 na mobile, 4 w rzędzie na desktop */}
|
||
<div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||
<MiniStat icon={Flame} label="Killstreak" value={ks ? String(ks.killstreak) : '—'} />
|
||
<MiniStat
|
||
icon={Scale}
|
||
label="Ostatnia waga"
|
||
value={latestWeight ? `${latestWeight.value} kg` : '—'}
|
||
meta={
|
||
weightDelta != null && weightDelta !== 0
|
||
? `${weightDelta > 0 ? '+' : '−'}${Math.abs(weightDelta).toLocaleString('pl-PL')} kg vs poprzedni`
|
||
: latestWeight
|
||
? fmtDate(latestWeight.date)
|
||
: undefined
|
||
}
|
||
valueClassName={
|
||
weightDelta != null && weightDelta !== 0
|
||
? weightDelta < 0
|
||
? 'text-accent-text'
|
||
: 'text-warn'
|
||
: ''
|
||
}
|
||
/>
|
||
<MiniStat
|
||
icon={Dumbbell}
|
||
label="Objętość 7 dni"
|
||
value={volume7d > 0 ? fmtVolume(volume7d) : '—'}
|
||
/>
|
||
<MiniStat
|
||
icon={History}
|
||
label="Sesje"
|
||
value={sessions.length > 0 ? String(sessions.length) : '—'}
|
||
meta={lastSession ? `ostatnia ${fmtDate(lastSession)}` : undefined}
|
||
/>
|
||
</div>
|
||
|
||
{/* Sekcje: wiersze-listy; mobile kolumna (divide-y), sm+ siatka 2 kol. */}
|
||
<Card>
|
||
<div className="grid grid-cols-1 gap-x-6 sm:grid-cols-2">
|
||
<div className="divide-y divide-line">
|
||
<SectionLink
|
||
to={`/users/${user.id}/info`}
|
||
title="Dane osobowe"
|
||
icon={User}
|
||
summary={
|
||
[
|
||
user.age != null ? `${user.age} lat` : null,
|
||
user.heightCm != null ? `${user.heightCm} cm` : null,
|
||
]
|
||
.filter(Boolean)
|
||
.join(' · ') || name
|
||
}
|
||
/>
|
||
<SectionLink
|
||
to={`/users/${user.id}/body-parameters`}
|
||
title="Parametry ciała"
|
||
icon={Scale}
|
||
summary={weightSummary}
|
||
/>
|
||
<SectionLink
|
||
to={`/users/${user.id}/history`}
|
||
title="Historia treningów"
|
||
icon={History}
|
||
summary={historySummary}
|
||
/>
|
||
</div>
|
||
<div className="divide-y divide-line">
|
||
<SectionLink
|
||
to={`/users/${user.id}/progress`}
|
||
title="Postępy"
|
||
icon={TrendingUp}
|
||
summary="1RM i objętość per ćwiczenie"
|
||
/>
|
||
<SectionLink
|
||
to={`/users/${user.id}/memberships`}
|
||
title="Członkostwa w siłowniach"
|
||
icon={Building2}
|
||
summary={gymsSummary}
|
||
/>
|
||
<SectionLink
|
||
to={`/users/${user.id}/claims`}
|
||
title="Wnioski"
|
||
icon={FileText}
|
||
summary={claimsSummary}
|
||
/>
|
||
</div>
|
||
</div>
|
||
</Card>
|
||
|
||
<ConfirmDialog
|
||
open={confirmOpen}
|
||
onClose={() => setConfirmOpen(false)}
|
||
onConfirm={() => void remove()}
|
||
title="Usunąć użytkownika?"
|
||
description="Jego plany i sesje zostaną usunięte. Tej operacji nie da się cofnąć."
|
||
confirmLabel="Usuń"
|
||
danger
|
||
busy={busy}
|
||
/>
|
||
</>
|
||
);
|
||
}
|