Admin: konsola użytkownika od nowa — status, członkostwa z menu ról, logi konta z podstroną; usunięcie podstron treningowych (współdzielone menu członkostwa z konsolą siłowni)

This commit is contained in:
tisachi
2026-10-29 21:44:51 +01:00
parent ac0e22f287
commit 248fa0bc9b
27 changed files with 836 additions and 3131 deletions

View File

@@ -15,12 +15,7 @@ import GymLogsPage from './pages/gyms/GymLogsPage';
import UsersList from './pages/users/UsersList';
import UserForm from './pages/users/UserForm';
import UserDetail from './pages/users/UserDetail';
import UserInfo from './pages/users/UserInfo';
import UserBodyParameters from './pages/users/UserBodyParameters';
import UserHistory from './pages/users/UserHistory';
import UserProgress from './pages/users/UserProgress';
import UserMemberships from './pages/users/UserMemberships';
import UserClaims from './pages/users/UserClaims';
import UserLogsPage from './pages/users/UserLogsPage';
import FocusAreas from './pages/catalog/FocusAreas';
import Exercises from './pages/catalog/Exercises';
import EquipmentCatalog from './pages/catalog/Equipment';
@@ -59,12 +54,7 @@ export default function App() {
<Route path="/users/new" element={<UserForm />} />
<Route path="/users/:id" element={<UserDetail />} />
<Route path="/users/:id/edit" element={<UserForm />} />
<Route path="/users/:id/info" element={<UserInfo />} />
<Route path="/users/:id/body-parameters" element={<UserBodyParameters />} />
<Route path="/users/:id/history" element={<UserHistory />} />
<Route path="/users/:id/progress" element={<UserProgress />} />
<Route path="/users/:id/memberships" element={<UserMemberships />} />
<Route path="/users/:id/claims" element={<UserClaims />} />
<Route path="/users/:id/logs" element={<UserLogsPage />} />
<Route path="/focus-areas" element={<FocusAreas />} />
<Route path="/exercises" element={<Exercises />} />
<Route path="/equipment" element={<EquipmentCatalog />} />

View File

@@ -1,185 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronUp, TrendingDown, TrendingUp } from 'lucide-react';
import {
Bar,
BarChart,
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from 'recharts';
import type { ExerciseProgress } from '../api/types';
import { resolveLocaleTag } from '../i18n/language';
import { fmtDate, fmtVolume } from '../lib/format';
import { localizedName } from '../lib/localizedName';
import { muscleName } from '../lib/labels';
import { Badge, Tabs } from './ui';
const TOOLTIP_STYLE = {
background: 'var(--bg-card)',
border: '1px solid var(--border)',
borderRadius: 12,
color: 'var(--text)',
};
/**
* Lista postępów per ćwiczenie: wiersz (nazwa + 1RM + delta + objętość + PR),
* tap rozwija kartę z zakładkami 1RM/Objętość i jednym wykresem (renderowany
* tylko dla aktywnej zakładki — unik ostrzeżeń recharts/ResizeObserver).
* Współdzielone z detalem podopiecznego (spójnie).
*/
export default function ExerciseProgressCards({ exercises }: { exercises: ExerciseProgress[] }) {
const { t, i18n } = useTranslation();
const [openId, setOpenId] = useState<string | null>(null);
// aktywna zakładka per ćwiczenie (domyślnie 1RM)
const [tabs, setTabs] = useState<Record<string, 'onerm' | 'volume'>>({});
return (
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
{exercises.map((ex) => {
const last = ex.points[ex.points.length - 1];
const prev = ex.points[ex.points.length - 2];
const oneRmDelta =
last?.oneRm != null && prev?.oneRm != null ? last.oneRm - prev.oneRm : null;
const maxOneRm = ex.points.reduce(
(max, p) => (p.oneRm != null && p.oneRm > max ? p.oneRm : max),
0,
);
const isPr = last?.oneRm != null && last.oneRm === maxOneRm && ex.points.length > 1;
const open = openId === ex.exerciseId;
const tab = tabs[ex.exerciseId] ?? 'onerm';
const setTab = (t: 'onerm' | 'volume') => setTabs((m) => ({ ...m, [ex.exerciseId]: t }));
return (
<div
key={ex.exerciseId}
className="rounded-xl border border-line bg-(image:--card-grad) shadow-card"
>
{/* Wiersz: nazwa + mięsień (meta) + 1RM + delta + objętość + PR */}
<button
type="button"
onClick={() => setOpenId(open ? null : ex.exerciseId)}
aria-expanded={open}
className="w-full cursor-pointer rounded-xl px-4 py-3.5 text-left transition-colors hover:bg-line/20"
>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<strong className="truncate text-[0.95rem]">
{localizedName(ex, i18n.language)}
</strong>
{isPr && <Badge color="green">PR</Badge>}
</div>
<div className="text-[0.8125rem] text-dim">{muscleName(ex.muscle)}</div>
</div>
<div className="flex shrink-0 items-center gap-3">
<div className="text-right">
<div className="font-display text-[1.15rem] font-bold leading-tight tabular-nums">
{last?.oneRm != null ? `${last.oneRm} kg` : '—'}
</div>
<div className="text-[0.75rem] text-dim">
{last?.volumeKg != null
? `${t('progress.volumePrefix')}${fmtVolume(last.volumeKg)}`
: t('progress.noVolume')}
</div>
</div>
{oneRmDelta != null && oneRmDelta !== 0 && (
<span
className={`flex items-center gap-1 text-[0.8125rem] font-semibold tabular-nums ${
oneRmDelta > 0 ? 'text-accent-text' : 'text-warn'
}`}
>
{oneRmDelta > 0 ? (
<TrendingUp className="h-3.5 w-3.5" />
) : (
<TrendingDown className="h-3.5 w-3.5" />
)}
{oneRmDelta > 0 ? '+' : '−'}
{Math.abs(oneRmDelta).toLocaleString(resolveLocaleTag(i18n.language))} kg
</span>
)}
{open ? (
<ChevronUp className="h-4 w-4 text-dim" />
) : (
<ChevronDown className="h-4 w-4 text-dim" />
)}
</div>
</div>
</button>
{/* Rozwinięta karta: zakładki 1RM/Objętość + jeden wykres */}
{open && (
<div className="border-t border-line px-4 pb-4">
<Tabs
tabs={[
{ id: 'onerm', label: '1RM' },
{ id: 'volume', label: t('progress.tabVolume') },
]}
active={tab}
onChange={(id) => setTab(id as 'onerm' | 'volume')}
/>
{tab === 'onerm' ? <OneRmChart ex={ex} /> : <VolumeChart ex={ex} />}
</div>
)}
</div>
);
})}
</div>
);
}
function OneRmChart({ ex }: { ex: ExerciseProgress }) {
const { t } = useTranslation();
const oneRmPoints = ex.points.filter((p) => p.oneRm != null);
if (oneRmPoints.length < 2) {
return <p className="mt-3 text-[0.875rem] text-dim">{t('progress.notEnough1rm')}</p>;
}
return (
<div className="mt-3">
<ResponsiveContainer width="100%" height={180}>
<LineChart data={oneRmPoints.map((p) => ({ date: fmtDate(p.date), oneRm: p.oneRm }))}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Line
type="monotone"
dataKey="oneRm"
name="1RM (kg)"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
</div>
);
}
function VolumeChart({ ex }: { ex: ExerciseProgress }) {
const { t } = useTranslation();
const volumePoints = ex.points.filter((p) => p.volumeKg != null);
if (volumePoints.length < 1) {
return <p className="mt-3 text-[0.875rem] text-dim">{t('progress.noVolumeData')}</p>;
}
return (
<div className="mt-3">
<ResponsiveContainer width="100%" height={180}>
<BarChart data={volumePoints.map((p) => ({ date: fmtDate(p.date), volumeKg: p.volumeKg }))}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Bar
dataKey="volumeKg"
name={t('progress.volumeKgName')}
fill="var(--info)"
radius={[4, 4, 0, 0]}
/>
</BarChart>
</ResponsiveContainer>
</div>
);
}

View File

@@ -1,202 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, ChevronUp, MessageSquare } from 'lucide-react';
import type { HistorySession } from '../api/types';
import { fmtDate, fmtDuration, fmtVolume } from '../lib/format';
import { localizedName } from '../lib/localizedName';
import { muscleName, SESSION_STATUS } from '../lib/labels';
import { Badge } from './ui';
interface HistoryTableProps {
sessions: HistorySession[];
/** Sesja otwarta od razu (np. po kliknięciu linku). */
initialOpenSessionId?: string;
}
/**
* Historia sesji tylko do odczytu: plan vs. wykonanie per seria + komentarze przy ćwiczeniach.
* Port odpowiednika z aplikacji (`app/src/components/HistoryTable`) bez dodawania komentarzy.
*/
export default function HistoryTable({ sessions, initialOpenSessionId }: HistoryTableProps) {
const { t, i18n } = useTranslation();
const [openSession, setOpenSession] = useState<string | null>(initialOpenSessionId ?? null);
return (
<div className="divide-y divide-line">
{sessions.map((s) => {
const st = SESSION_STATUS[s.status];
const open = openSession === s.id;
const plannedTotal = s.exercises.reduce(
(n, ex) => n + ex.sets.filter((set) => set.planned).length,
0,
);
const plannedDone = s.exercises.reduce(
(n, ex) => n + ex.sets.filter((set) => set.planned && set.reps != null).length,
0,
);
// Serie wykonane ponad plan (bez planowanego odpowiednika) z zapisanymi powtórzeniami.
const extraSets = s.exercises.reduce(
(n, ex) => n + ex.sets.filter((set) => set.planned == null && set.reps != null).length,
0,
);
// Deficyt = niewyrobione serie normowe (bonus nie wchodzi w normę).
const deficit = plannedTotal - plannedDone;
// Objętość = Σ obciążenie × powtórzenia; seria bez planowanego obciążenia = masa ciała z profilu.
const volume = s.exercises
.flatMap((ex) => ex.sets)
.reduce(
(sum, set) =>
set.reps != null ? sum + (set.planned?.loadKg ?? s.bodyKg ?? 0) * set.reps : sum,
0,
);
const duration = s.endedAt ? fmtDuration(s.startedAt, s.endedAt) : null;
return (
<div key={s.id} className="px-1">
<button
type="button"
onClick={() => setOpenSession(open ? null : s.id)}
aria-expanded={open}
className="w-full cursor-pointer rounded-[10px] px-2 py-3 text-left transition-colors hover:bg-line/20"
>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="truncate font-display text-[0.95rem] font-semibold tabular-nums">
{s.date ? fmtDate(s.date) : '—'} · {s.plan}
</div>
<div className="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-dim text-[0.8125rem]">
{volume > 0 && <span className="tabular-nums">{fmtVolume(volume)}</span>}
{duration && <span className="tabular-nums">{duration}</span>}
{plannedTotal > 0 && (
<span className="tabular-nums">
{t('history.quota', { done: plannedDone, total: plannedTotal })}
</span>
)}
{extraSets > 0 && (
<span className="tabular-nums">
{t('history.bonusValue', { n: extraSets })}
</span>
)}
{deficit > 0 && (
<span className="tabular-nums">
{t('history.deficitValue', { n: deficit })}
</span>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<Badge color={st.color}>{t(st.labelKey)}</Badge>
{open ? (
<ChevronUp className="h-4 w-4 text-dim" />
) : (
<ChevronDown className="h-4 w-4 text-dim" />
)}
</div>
</div>
{plannedTotal > 0 && (
<div className="mt-2 h-[4px] overflow-hidden rounded-full bg-input">
<div
className="h-full rounded-full bg-(image:--progress-grad)"
style={{ width: `${Math.round((plannedDone / plannedTotal) * 100)}%` }}
/>
</div>
)}
</button>
{open && (
<div className="pb-1">
{s.exercises.length === 0 && (
<p className="py-3 text-dim text-[0.875rem]">{t('history.noExercises')}</p>
)}
{s.exercises.length > 0 && (
<div className="divide-y divide-line">
{s.exercises.map((ex) => (
<div key={ex.id} className="py-3">
<div className="mb-2 flex items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2">
<strong className="text-[0.95rem]">
{localizedName(ex, i18n.language)}
</strong>
{ex.isExtra && <Badge color="yellow">{t('history.added')}</Badge>}
</div>
<span className="text-dim text-[0.875rem]">
{muscleName(ex.muscle) || ex.muscle}
</span>
</div>
<div className="divide-y divide-line">
{ex.sets.map((set) => (
<div key={set.index} className="py-1.5">
<div className="flex items-center gap-2">
<span className="w-8 shrink-0 text-[0.8125rem] font-semibold text-dim tabular-nums">
S{set.index + 1}
</span>
{set.planned && set.reps == null ? (
<span className="rounded-full border border-danger/30 bg-danger/10 px-2 py-0.5 text-[0.75rem] font-semibold text-danger">
{t('history.notDone')}
</span>
) : (
<span className="font-display text-[0.95rem] font-semibold tabular-nums">
{set.reps ?? '—'}
<span className="ml-0.5 text-[0.75em] font-semibold text-dim">
{t('history.repsUnit')}
</span>
</span>
)}
</div>
{(set.planned || set.rir != null || set.difficulty != null) && (
<div className="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 pl-10 text-[0.75rem] text-dim tabular-nums">
{set.planned && (
<span>
{t('history.planPrefix')}
{set.planned.reps ?? '—'}
{set.planned.loadKg != null
? `/${set.planned.loadKg} kg`
: `/${t('history.bodyweight')}`}
{set.planned.restSec != null
? `/${set.planned.restSec} s`
: ''}
</span>
)}
{set.rir != null && <span>RIR {set.rir}</span>}
{set.difficulty != null && (
<span>
{t('history.difficultyWord', { n: set.difficulty })}
</span>
)}
</div>
)}
{set.note && (
<div className="mt-0.5 pl-10 text-[0.75rem] text-dim">
<MessageSquare className="mr-1 inline h-3 w-3 align-[-2px]" />
{set.note}
</div>
)}
</div>
))}
</div>
{ex.comments.length > 0 && (
<div className="mt-2.5 space-y-1.5">
{ex.comments.map((c) => (
<div
key={c.id}
className="flex items-start gap-2 py-1 text-[0.875rem]"
>
<div className="min-w-0 flex-1">
<span className="font-semibold">{c.authorName}</span>
<span className="text-dim"> · {fmtDate(c.createdAt)}</span>
<div>{c.body}</div>
</div>
</div>
))}
</div>
)}
</div>
))}
</div>
)}
</div>
)}
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,137 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { api } from '../api/client';
import type { GymRole } from '../api/types';
import { GymRolePicker } from './GymRolePicker';
import { Button, ErrorText, Field, Modal, Muted, Textarea } from './ui';
import { GYM_ROLE_ORDER } from '../lib/roles';
/**
* Wspólne menu członkostwa (konsola siłowni + profil usera): pełna lista ról (PATCH)
* oraz wyrzucenie z siłowni z wymagalnym powodem (DELETE + audyt membership.deleted).
*/
export function MembershipActionsModal({
userId,
titleName,
gymId,
roles: initialRoles,
showProfileLink = true,
onClose,
onChanged,
}: {
userId: string;
titleName: string;
gymId: string;
roles: string[];
showProfileLink?: boolean;
onClose: () => void;
onChanged: () => void;
}) {
const { t } = useTranslation('gyms');
const [roles, setRoles] = useState<GymRole[]>(
GYM_ROLE_ORDER.filter((r) => initialRoles.includes(r)),
);
const [reason, setReason] = useState('');
const [busy, setBusy] = useState<'' | 'roles' | 'remove'>('');
const [error, setError] = useState('');
const saveRoles = async () => {
if (roles.length === 0) return;
setError('');
setBusy('roles');
try {
await api(`/admin/users/${userId}/memberships/${gymId}`, {
method: 'PATCH',
body: { roles },
});
onChanged();
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
} finally {
setBusy('');
}
};
const remove = async () => {
const trimmed = reason.trim();
if (trimmed.length < 3) return;
setError('');
setBusy('remove');
try {
await api(`/admin/users/${userId}/memberships/${gymId}`, {
method: 'DELETE',
body: { reason: trimmed },
});
onChanged();
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
} finally {
setBusy('');
}
};
return (
<Modal open onClose={onClose} title={t('membershipMenuTitle', { name: titleName })}>
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
<Muted className="block text-[0.85rem]">{t('memberMenuDesc')}</Muted>
{showProfileLink && (
<Link
to={`/users/${userId}`}
className="text-[0.85rem] font-semibold text-accent-text hover:underline"
>
{t('memberProfileLink')}
</Link>
)}
</div>
<div className="mb-2 text-[10.5px] font-bold uppercase tracking-[0.11em] text-dim">
{t('memberRolesTitle')}
</div>
<GymRolePicker
value={roles}
onChange={setRoles}
labelPrefix={titleName}
showExplain={false}
/>
<div className="mt-3">
<Button
size="sm"
onClick={() => void saveRoles()}
disabled={busy !== '' || roles.length === 0}
>
{busy === 'roles' ? t('common:saving') : t('saveRoles')}
</Button>
</div>
<div className="my-4 border-t border-line" />
<div className="mb-1 text-[10.5px] font-bold uppercase tracking-[0.11em] text-dim">
{t('removeMemberTitle')}
</div>
<p className="mb-3 text-[0.8rem] text-dim">{t('removeMemberDesc')}</p>
<Field label={t('removeReasonLabel')}>
<Textarea
size="sm"
rows={2}
aria-label={t('removeReasonLabel')}
placeholder={t('removeReasonPh')}
value={reason}
onChange={(e) => setReason(e.target.value)}
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Button
variant="danger"
size="sm"
className="mt-3"
onClick={() => void remove()}
disabled={busy !== '' || reason.trim().length < 3}
>
{busy === 'remove' ? t('removing') : t('removeMemberAction')}
</Button>
</Modal>
);
}

View File

@@ -87,8 +87,7 @@ export function SectionHeader({
);
}
/* Meta item: small icon + muted text */
export function MetaItem({
/* Meta item: small icon + muted text */ export function MetaItem({
icon: Icon,
children,
className = '',
@@ -107,6 +106,34 @@ export function MetaItem({
);
}
/* Komórka paska statystyk w panelu podsumowania (konsola siłowni / profil usera). */
export function StatCell({
label,
value,
icon,
children,
}: {
label: string;
value: string;
icon: ReactNode;
children?: ReactNode;
}) {
return (
<div className="min-w-0 px-4 py-3.5 sm:px-5">
<div className="flex items-center gap-1.5 text-[10.5px] font-bold uppercase tracking-[0.12em] text-dim">
<span aria-hidden className="text-dim">
{icon}
</span>
<span className="truncate">{label}</span>
</div>
<div className="mt-1.5 font-display text-[1.3rem] font-bold leading-none tabular-nums">
{value}
</div>
{children}
</div>
);
}
/* List row: płaski wiersz (tytuł + meta lewo, akcje prawo); w listach w karcie
rodzic używa `divide-y divide-line` (dłuższe) albo `space-y-1` (krótkie). */
export function ListRow({

View File

@@ -86,12 +86,11 @@
"roleFilterOwners": "Owners",
"roleFilterTrainers": "Trainers",
"roleFilterMembers": "Members",
"memberMenuTitle": "Member: {{name}}",
"membershipMenuTitle": "Membership: {{name}}",
"memberMenuDesc": "Manage roles or remove this member from the gym.",
"memberProfileLink": "Open profile in panel",
"memberRolesTitle": "Gym roles",
"saveRoles": "Save roles",
"rolesSaved": "Roles saved.",
"removeMemberTitle": "Remove from gym",
"removeMemberDesc": "The membership is removed immediately. The reason is stored in the audit log.",
"removeReasonLabel": "Reason",

View File

@@ -1,5 +1,22 @@
{
"newUser": "New user",
"consoleTitle": "User",
"backToList": "Back",
"logsAction": "Logs",
"logsCardTitle": "Account logs",
"allLogs": "All logs",
"logsPage": {
"title": "User logs",
"subtitle": "Audit events performed on this account.",
"emptyTitle": "No logs",
"emptyDesc": "No audit events on this account.",
"showMore": "Show {{count}} more"
},
"statMemberships": "Memberships",
"statClaims": "Requests",
"statCreated": "Account since",
"colGym": "Gym",
"colRoles": "Roles",
"ageWord": "age: {{age}}",
"statusSuspended": "Suspended",
"statusBanned": "Banned",
@@ -8,7 +25,6 @@
"noUsersTitle": "No users",
"noUsersDesc": "No users.",
"noResultsDesc": "No results for the given query.",
"userFallback": "User",
"notFound": "User not found.",
"suspend": "Suspend",
"ban": "Ban",
@@ -16,38 +32,12 @@
"deleteConfirmDesc": "Their plans and sessions will be deleted. This operation cannot be undone.",
"createdOn": "Created {{date}}",
"until": " until {{dt}}",
"statKillstreak": "Killstreak",
"statVolume7d": "7-day volume",
"statSessions": "Sessions",
"statLastLogin": "Last login",
"accountHistory": "Account history",
"noActivity": "No account events.",
"byActor": "by {{actor}}",
"lastLoginWord": "login: {{date}}",
"ageValue": "{{age}} years",
"personalInfo": "Personal details",
"bodyParams": "Body parameters",
"trainingHistory": "Training history",
"progress": "Progress",
"membershipsTitle": "Gym memberships",
"claims": "Requests",
"noData": "no data",
"none": "none",
"weightSummary": "{{value}} kg · {{date}}",
"noMeasurements": "no measurements",
"sessionsWordOne": "session",
"sessionsWordFew": "sessions",
"sessionsWordMany": "sessions",
"lastSession": "last {{date}}",
"noSessions": "no sessions",
"pendingClaims": "{{count}} pending",
"resolvedClaims": "{{count}} resolved",
"exercisesWordOne": "exercise",
"exercisesWordFew": "exercises",
"exercisesWordMany": "exercises",
"profileFallback": "Profile",
"profileTitle": "Profile {{name}}",
"affiliations": "Affiliations",
"noMemberships": "No memberships.",
"accessTitle": "Account access",
"statusLabel": "Account status",
@@ -59,43 +49,21 @@
"optionalPh": "optional",
"errUntilRequired": "Provide the date until which the account should be suspended.",
"errUntilFuture": "The suspension date must be in the future.",
"errReasonRequired": "Provide the reason for banning the account.",
"errReasonRequired": "Provide the reason for blocking the account.",
"saveError": "Save error",
"claimStatusPending": "Pending",
"claimStatusApproved": "Approved",
"claimStatusRejected": "Rejected",
"noClaimsTitle": "No requests",
"noClaimsDesc": "The user has not submitted any gym requests yet.",
"typeNew": "New gym",
"typeVerification": "Verification",
"submittedOn": "submitted {{date}}",
"details": "Details",
"reasonPrefix": "Reason: ",
"noSessionsTitle": "No sessions",
"noSessionsMonthTitle": "No sessions in the selected month",
"noSessionsMonthDesc": "Choose another month or clear the filter to see the full history.",
"noSessionsDesc": "The user has no training sessions yet.",
"noProgressTitle": "No progress",
"noProgressDesc": "Progress will appear after the user's first completed workout.",
"progressWord": "Progress",
"changeSinceFirst": "{{diff}} {{unit}} since first",
"noChange": "no change",
"secondMeasurementHint": "a second measurement will show the change",
"firstToLast": "{{n}} · first → last",
"measurementWordOne": "measurement",
"measurementWordFew": "measurements",
"measurementWordMany": "measurements",
"chartNotEnough": "Not enough data for a chart (min. 2 measurements).",
"bpNoMeasurements": "No measurements",
"bpNoMeasurementsDesc": "Measurements will appear here when the user adds weight or circumference in the app.",
"editUser": "Edit user",
"emailRequired": "Provide an email address.",
"emailRequired": "Enter an e-mail address.",
"passMin8": "Password must be at least 8 characters long.",
"newPassMin8": "New password must be at least 8 characters long.",
"passMismatch": "Passwords must match.",
"fallbackThis": "this",
"roleNoGym": "You cannot add someone to a gym without a role. Select a role for \"{{name}}\" or remove this row.",
"rolesNeedGym": "Roles ({{labels}}) require a selected gym. Choose a gym or deselect the roles.",
"roleNoGym": "You cannot add someone to a gym without a role. Select a role for “{{name}}” or remove this row.",
"rolesNeedGym": "Roles ({{labels}}) require a selected gym. Choose a gym or clear the roles.",
"stepData": "Details",
"stepRoles": "Roles",
"firstName": "First name",
@@ -104,13 +72,12 @@
"passwordMin8": "Password (min. 8)",
"repeatNewPassword": "Repeat new password",
"repeatPassword": "Repeat password",
"age": "Age",
"birthDate": "Date of birth",
"adminPlatformTitle": "Platform administrator",
"ariaShowAdmin": "Show admin permissions",
"ariaHideAdmin": "Hide admin permissions",
"ariaHideAdmin": "Collapse admin permissions",
"noGymsYet": "No gyms yet",
"noGymsYetDesc": "Add the first gym and select a role — memberships are granted and changed only here.",
"noGymsYetDesc": "Add the first gym and select a role — memberships are granted and changed in the wizard.",
"addFirstGym": "Add the first gym",
"addNextGym": "Add another gym",
"removeGymAria": "Remove {{name}}",
@@ -118,29 +85,5 @@
"gymLabel": "Gym",
"gymFallback": "gym {{n}}",
"cannotSave": "Cannot save",
"understand": "Got it",
"toneDevelop": "To develop",
"toneCanDo": "Can do",
"toneDifficult": "Difficult",
"toneAvoid": "To avoid",
"chainPrefixDevelop": "to develop: ",
"chainPrefixAvoid": "avoid: ",
"chainTitle": "Cause-and-effect chain",
"chainDesc": "Exercises from the active plan in the context of priorities and exclusions.",
"chainNoFocus": "no focus in the plan",
"chainNotInPlan": "not in the active plan",
"accountCard": "Account",
"fullAccess": "Full access",
"accountNone": "None",
"createdLabel": "Created",
"basicData": "Basic details",
"height": "Height",
"phone": "Phone",
"nick": "Nickname",
"availabilityLabel": "Availability",
"noAvailability": "No availability set",
"prioritiesTitle": "Priorities and exclusions",
"nothingAdded": "nothing added",
"socialMediaTitle": "Social media",
"noSocialProfiles": "No profiles added."
"understand": "Got it"
}

View File

@@ -86,12 +86,11 @@
"roleFilterOwners": "Właściciele",
"roleFilterTrainers": "Trenerzy",
"roleFilterMembers": "Członkowie",
"memberMenuTitle": "Członek: {{name}}",
"membershipMenuTitle": "Członkostwo: {{name}}",
"memberMenuDesc": "Zarządzaj rolami albo usuń członkostwo w tej siłowni.",
"memberProfileLink": "Otwórz profil w panelu",
"memberRolesTitle": "Role w siłowni",
"saveRoles": "Zapisz role",
"rolesSaved": "Role zapisane.",
"removeMemberTitle": "Wyrzuć z siłowni",
"removeMemberDesc": "Członkostwo zostanie usunięte natychmiast. Powód trafi do logów audytu.",
"removeReasonLabel": "Powód",

View File

@@ -1,5 +1,22 @@
{
"newUser": "Nowy użytkownik",
"consoleTitle": "Użytkownik",
"backToList": "Wróć",
"logsAction": "Logi",
"logsCardTitle": "Logi konta",
"allLogs": "Wszystkie logi",
"logsPage": {
"title": "Logi użytkownika",
"subtitle": "Zdarzenia audytu wykonane na tym koncie.",
"emptyTitle": "Brak logów",
"emptyDesc": "Brak zdarzeń audytu na tym koncie.",
"showMore": "Pokaż kolejne {{count}}"
},
"statMemberships": "Członkostwa",
"statClaims": "Wnioski",
"statCreated": "Konto od",
"colGym": "Siłownia",
"colRoles": "Role",
"ageWord": "wiek: {{age}}",
"statusSuspended": "Zawieszone",
"statusBanned": "Zablokowane",
@@ -8,7 +25,6 @@
"noUsersTitle": "Brak użytkowników",
"noUsersDesc": "Brak użytkowników.",
"noResultsDesc": "Brak wyników dla podanego zapytania.",
"userFallback": "Użytkownik",
"notFound": "Nie znaleziono użytkownika.",
"suspend": "Zawieś",
"ban": "Zbanuj",
@@ -16,38 +32,12 @@
"deleteConfirmDesc": "Jego plany i sesje zostaną usunięte. Tej operacji nie da się cofnąć.",
"createdOn": "Utworzony {{date}}",
"until": " do {{dt}}",
"statKillstreak": "Killstreak",
"statVolume7d": "Objętość 7 dni",
"statSessions": "Sesje",
"statLastLogin": "Ostatnie logowanie",
"accountHistory": "Historia konta",
"noActivity": "Brak zdarzeń konta.",
"byActor": "przez {{actor}}",
"lastLoginWord": "log: {{date}}",
"ageValue": "{{age}} lat",
"personalInfo": "Dane osobowe",
"bodyParams": "Parametry ciała",
"trainingHistory": "Historia treningów",
"progress": "Postępy",
"membershipsTitle": "Członkostwa w siłowniach",
"claims": "Wnioski",
"noData": "brak danych",
"none": "brak",
"weightSummary": "{{value}} kg · {{date}}",
"noMeasurements": "brak pomiarów",
"sessionsWordOne": "sesja",
"sessionsWordFew": "sesje",
"sessionsWordMany": "sesji",
"lastSession": "ostatnia {{date}}",
"noSessions": "brak sesji",
"pendingClaims": "{{count}} oczekujących",
"resolvedClaims": "{{count}} rozstrzygniętych",
"exercisesWordOne": "ćwiczenie",
"exercisesWordFew": "ćwiczenia",
"exercisesWordMany": "ćwiczeń",
"profileFallback": "Profil",
"profileTitle": "Profil {{name}}",
"affiliations": "Przynależności",
"noMemberships": "Brak członkostw.",
"accessTitle": "Dostęp do konta",
"statusLabel": "Status konta",
@@ -64,30 +54,8 @@
"claimStatusPending": "Oczekuje",
"claimStatusApproved": "Zatwierdzony",
"claimStatusRejected": "Odrzucony",
"noClaimsTitle": "Brak wniosków",
"noClaimsDesc": "Użytkownik nie złożył jeszcze żadnych wniosków o siłownię.",
"typeNew": "Nowa siłownia",
"typeVerification": "Weryfikacja",
"submittedOn": "złożono {{date}}",
"details": "Szczegóły",
"reasonPrefix": "Powód: ",
"noSessionsTitle": "Brak sesji",
"noSessionsMonthTitle": "Brak sesji w wybranym miesiącu",
"noSessionsMonthDesc": "Wybierz inny miesiąc lub odznacz filtr, aby zobaczyć pełną historię.",
"noSessionsDesc": "Użytkownik nie ma jeszcze żadnych sesji treningowych.",
"noProgressTitle": "Brak postępów",
"noProgressDesc": "Postępy pojawią się po pierwszym ukończonym treningu użytkownika.",
"progressWord": "Postęp",
"changeSinceFirst": "{{diff}} {{unit}} od pierwszego",
"noChange": "bez zmian",
"secondMeasurementHint": "drugi pomiar pokaże zmianę",
"firstToLast": "{{n}} · pierwszy → ostatni",
"measurementWordOne": "pomiar",
"measurementWordFew": "pomiary",
"measurementWordMany": "pomiarów",
"chartNotEnough": "Za mało danych na wykres (min. 2 pomiary).",
"bpNoMeasurements": "Brak pomiarów",
"bpNoMeasurementsDesc": "Pomiary pojawią się tutaj, gdy użytkownik doda wagę lub obwód w aplikacji.",
"editUser": "Edycja użytkownika",
"emailRequired": "Podaj adres e-mail.",
"passMin8": "Hasło musi mieć co najmniej 8 znaków.",
@@ -104,13 +72,12 @@
"passwordMin8": "Hasło (min. 8)",
"repeatNewPassword": "Powtórz nowe hasło",
"repeatPassword": "Powtórz hasło",
"age": "Wiek",
"birthDate": "Data urodzenia",
"adminPlatformTitle": "Administrator platformy",
"ariaShowAdmin": "Pokaż uprawnienia admina",
"ariaHideAdmin": "Zwiń uprawnienia admina",
"noGymsYet": "Jeszcze bez siłowni",
"noGymsYetDesc": "Dodaj pierwszą siłownię i zaznacz rolę — członkostwa nadajesz i zmieniasz tylko tutaj.",
"noGymsYetDesc": "Dodaj pierwszą siłownię i zaznacz rolę — członkostwa nadajesz w kreatorze albo w konsoli siłowni.",
"addFirstGym": "Dodaj pierwszą siłownię",
"addNextGym": "Dodaj kolejną siłownię",
"removeGymAria": "Usuń {{name}}",
@@ -118,29 +85,5 @@
"gymLabel": "Siłownia",
"gymFallback": "siłownia {{n}}",
"cannotSave": "Nie można zapisać",
"understand": "Rozumiem",
"toneDevelop": "Co rozwija",
"toneCanDo": "Co potrafi",
"toneDifficult": "Co trudne",
"toneAvoid": "Co unikać",
"chainPrefixDevelop": "do rozwoju: ",
"chainPrefixAvoid": "unikamy: ",
"chainTitle": "Ciąg przyczynowo-skutkowy",
"chainDesc": "Ćwiczenia z aktywnego planu w kontekście priorytetów i wykluczeń.",
"chainNoFocus": "brak akcentów w planie",
"chainNotInPlan": "brak w aktywnym planie",
"accountCard": "Konto",
"fullAccess": "Pełny dostęp",
"accountNone": "Brak",
"createdLabel": "Utworzony",
"basicData": "Podstawowe dane",
"height": "Wzrost",
"phone": "Telefon",
"nick": "Nick",
"availabilityLabel": "Dostępność",
"noAvailability": "Brak ustawionej dostępności",
"prioritiesTitle": "Priorytety i wykluczenia",
"nothingAdded": "nic nie dodano",
"socialMediaTitle": "Social media",
"noSocialProfiles": "Brak dodanych profili."
"understand": "Rozumiem"
}

View File

@@ -1,20 +0,0 @@
import { useTranslation } from 'react-i18next';
import { measurementType, type Gender, type Side } from './body-measurements';
/**
* Etykiety pomiarów ciała z namespace `body`. Etykieta strony zależy od rodzaju
* gramatycznego części (PL: Lewy/Lewa/Lewe), więc klucz to `side.<strona>_<rodzaj>`.
*/
export function useMeasurementLabels() {
const { t } = useTranslation('body');
const measurementLabel = (typeId: string): string => t(typeId);
const genderOf = (typeId: string | null): Gender =>
(typeId ? measurementType(typeId)?.gender : undefined) ?? 'm';
const sideLabel = (side: Side, gender: Gender): string =>
t(`side.${side}_${gender === 'p' ? 'n' : gender}`);
return { measurementLabel, genderOf, sideLabel };
}

View File

@@ -8,7 +8,7 @@ import { api } from '../../api/client';
import { APP_URL } from '../../config';
import GymQrModal from '../../components/gyms/GymQrModal';
import { ExceptionsEditor } from '../../components/gyms/ExceptionsBlock';
import { GymRolePicker } from '../../components/GymRolePicker';
import { MembershipActionsModal } from '../../components/MembershipActionsModal';
import { UserPicker } from '../../components/UserPicker';
import { AddressFields, addressPayload, isAddressComplete } from '../../components/AddressFields';
import { actionLabel, actorName, formatLogDate } from '../../components/LogTable';
@@ -27,8 +27,8 @@ import {
Modal,
Muted,
Select,
StatCell,
SuccessText,
Textarea,
} from '../../components/ui';
import { AvailabilityEditor } from '../../components/AvailabilityEditor';
import { dayFull, formatDayRangeClock, normalizeAvailability } from '../../lib/availability';
@@ -69,34 +69,6 @@ function HoursList({ gym }: { gym: Gym }) {
);
}
/* Komórka paska statystyk w panelu podsumowania. */
function StatCell({
label,
value,
icon,
children,
}: {
label: string;
value: string;
icon: React.ReactNode;
children?: React.ReactNode;
}) {
return (
<div className="min-w-0 px-4 py-3.5 sm:px-5">
<div className="flex items-center gap-1.5 text-[10.5px] font-bold uppercase tracking-[0.12em] text-dim">
<span aria-hidden className="text-dim">
{icon}
</span>
<span className="truncate">{label}</span>
</div>
<div className="mt-1.5 font-display text-[1.3rem] font-bold leading-none tabular-nums">
{value}
</div>
{children}
</div>
);
}
function memberLabel(m: AdminGymMemberItem): string {
return [m.user.firstName, m.user.lastName].filter(Boolean).join(' ') || m.user.email;
}
@@ -166,120 +138,6 @@ function MembersTable({
);
}
/* Menu członka (klik w wiersz): edycja ról (PATCH pełnej listy) + wyrzucenie z powodem (DELETE). */
function MemberActionsModal({
gym,
member,
onClose,
onChanged,
}: {
gym: Gym;
member: AdminGymMemberItem;
onClose: () => void;
onChanged: () => void;
}) {
const { t } = useTranslation('gyms');
const label = memberLabel(member);
const [roles, setRoles] = useState<GymRole[]>(
GYM_ROLE_ORDER.filter((r) => member.roles.includes(r)),
);
const [reason, setReason] = useState('');
const [busy, setBusy] = useState<'' | 'roles' | 'remove'>('');
const [error, setError] = useState('');
const saveRoles = async () => {
if (roles.length === 0) return;
setError('');
setBusy('roles');
try {
await api(`/admin/users/${member.user.id}/memberships/${gym.id}`, {
method: 'PATCH',
body: { roles },
});
onChanged();
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
} finally {
setBusy('');
}
};
const remove = async () => {
const trimmed = reason.trim();
if (trimmed.length < 3) return;
setError('');
setBusy('remove');
try {
await api(`/admin/users/${member.user.id}/memberships/${gym.id}`, {
method: 'DELETE',
body: { reason: trimmed },
});
onChanged();
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
} finally {
setBusy('');
}
};
return (
<Modal open onClose={onClose} title={t('memberMenuTitle', { name: label })}>
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
<Muted className="block text-[0.85rem]">{t('memberMenuDesc')}</Muted>
<Link
to={`/users/${member.user.id}`}
className="text-[0.85rem] font-semibold text-accent-text hover:underline"
>
{t('memberProfileLink')}
</Link>
</div>
<div className="mb-2 text-[10.5px] font-bold uppercase tracking-[0.11em] text-dim">
{t('memberRolesTitle')}
</div>
<GymRolePicker value={roles} onChange={setRoles} labelPrefix={label} showExplain={false} />
<div className="mt-3">
<Button
size="sm"
onClick={() => void saveRoles()}
disabled={busy !== '' || roles.length === 0}
>
{busy === 'roles' ? t('common:saving') : t('saveRoles')}
</Button>
</div>
<div className="my-4 border-t border-line" />
<div className="mb-1 text-[10.5px] font-bold uppercase tracking-[0.11em] text-dim">
{t('removeMemberTitle')}
</div>
<p className="mb-3 text-[0.8rem] text-dim">{t('removeMemberDesc')}</p>
<Field label={t('removeReasonLabel')}>
<Textarea
size="sm"
rows={2}
aria-label={t('removeReasonLabel')}
placeholder={t('removeReasonPh')}
value={reason}
onChange={(e) => setReason(e.target.value)}
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Button
variant="danger"
size="sm"
className="mt-3"
onClick={() => void remove()}
disabled={busy !== '' || reason.trim().length < 3}
>
{busy === 'remove' ? t('removing') : t('removeMemberAction')}
</Button>
</Modal>
);
}
/* Stan awaryjny: siłownia bez właściciela — alert + szybkie przypisanie w sekcji członków. */
function OwnerAlert({ gym, onAssigned }: { gym: Gym; onAssigned: () => void }) {
const { t } = useTranslation('gyms');
@@ -476,6 +334,7 @@ export default function GymDetail() {
queryClient.invalidateQueries({ queryKey: ['gyms'] }),
queryClient.invalidateQueries({ queryKey: ['gym', id] }),
queryClient.invalidateQueries({ queryKey: ['gym-members'] }),
queryClient.invalidateQueries({ queryKey: ['admin-users'] }),
]);
const remove = async () => {
@@ -814,10 +673,12 @@ export default function GymDetail() {
{/* MODALE */}
{manage && (
<MemberActionsModal
<MembershipActionsModal
key={manage.membershipId}
gym={gym}
member={manage}
userId={manage.user.id}
titleName={memberLabel(manage)}
gymId={gym.id}
roles={manage.roles}
onClose={() => setManage(null)}
onChanged={() => void invalidate()}
/>

View File

@@ -1,607 +0,0 @@
import { useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Ruler, Scale, TrendingDown, TrendingUp, type LucideIcon } from 'lucide-react';
import {
Area,
AreaChart,
XAxis,
YAxis,
Tooltip,
ResponsiveContainer,
CartesianGrid,
} from 'recharts';
import { useTopbar } from '../../topbar';
import {
BackButton,
Button,
Card,
EmptyState,
ErrorText,
H3,
PageHeader,
Skeleton,
Tabs,
} from '../../components/ui';
import { MEASUREMENT_TYPES, type Gender, type Side } from '../../lib/body-measurements';
import { useMeasurementLabels } from '../../lib/useMeasurementLabels';
import i18n from '../../i18n';
import { resolveLocaleTag } from '../../i18n/language';
import { fmtDate } from '../../lib/format';
import type { CircumferenceSeries } from '../../api/types';
import { useAdminUser, useUserBodyParameters } from './user-queries';
import { userDisplayName } from './UserDetail';
const TOOLTIP_STYLE = {
background: 'var(--bg-card)',
border: '1px solid var(--border)',
borderRadius: 12,
color: 'var(--text)',
};
/* Wykresy: oś bez linii i kresek, drobny dimowany tick — tło siatki tylko poziome. */
const AXIS_TICK = { fill: 'var(--text-dim)', fontSize: 12 };
const CHART_MARGIN = { top: 8, right: 8, left: 0, bottom: 0 };
/* Kolor linii wg jednostki: waga = accent, obwody = info. */
const unitStroke = (unit: PartGroup['unit']) => (unit === 'kg' ? 'var(--accent)' : 'var(--info)');
/* Tooltip: wartość z jednostką, nazwa serii bez zmian (formatter zwraca parę [wartość, nazwa]). */
const tooltipUnit =
(unit: PartGroup['unit']) =>
(value: number | string, name: string): [string, string] => [`${value} ${unit}`, name];
/* Punkty pomiarowe: pusty środek (karta pod spodem), ring w kolorze linii. */
const lineDot = (stroke: string) => ({ r: 3, strokeWidth: 2, fill: 'var(--bg-card)', stroke });
const lineActiveDot = (stroke: string) => ({
r: 5,
strokeWidth: 2,
fill: 'var(--bg-card)',
stroke,
});
interface CircGroup {
key: string;
typeId: string | null;
/** Swobodna nazwa starszego pomiaru — tylko gdy typeId jest null. */
legacyName: string | null;
series: CircumferenceSeries[];
}
/**
* Grupuje serie obwodów po części ciała (typie): `biceps/left` + `biceps/right` → jedna grupa.
* Serie z `typeId` układają się w kolejności listy; starsze (typeId = null) zostają osobno.
*/
function groupCircumferences(series: CircumferenceSeries[]): CircGroup[] {
const byKey = new Map<string, CircGroup>();
for (const s of series) {
const key = s.typeId ? `t:${s.typeId}` : `n:${s.name ?? ''}`;
const g = byKey.get(key) ?? {
key,
typeId: s.typeId,
legacyName: s.typeId ? null : (s.name ?? ''),
series: [],
};
g.series.push(s);
byKey.set(key, g);
}
const knownOrder = (g: CircGroup) => {
const idx = MEASUREMENT_TYPES.findIndex((t) => t.id === g.typeId);
return idx >= 0 ? idx : MEASUREMENT_TYPES.length;
};
const sideOrder = (s: Side | null) => (s === 'left' ? 0 : s === 'right' ? 1 : 2);
return [...byKey.values()]
.sort(
(a, b) =>
knownOrder(a) - knownOrder(b) ||
(a.typeId ?? a.legacyName ?? '').localeCompare(b.typeId ?? b.legacyName ?? '', 'pl'),
)
.map((g) => ({
...g,
series: [...g.series].sort((x, y) => sideOrder(x.side) - sideOrder(y.side)),
}));
}
/* Grupa pomiaru w ujednoliconej postaci: waga i obwody jako jeden model (panel + wykres). */
interface GroupPoint {
id: string;
value: number;
date: string;
side: Side | null;
name: string;
}
interface PartGroup {
key: string;
label: string;
/** Rodzaj gramatyczny → fleksja strony w nagłówkach/etykietach. */
gender: Gender;
unit: 'kg' | 'cm';
/** Wszystkie pomiary (pełna historia), rosnąco po dacie. */
points: GroupPoint[];
sidesPresent: Side[];
}
/* Pluralis dla „pomiar” (kategorie odpowiadające regułom PL). */
function pomN(n: number, words: { one: string; few: string; many: string }): string {
if (n === 1) return `${n} ${words.one}`;
if (n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14)) return `${n} ${words.few}`;
return `${n} ${words.many}`;
}
const WEIGHT_KEY = 'weight';
const localeTag = () => resolveLocaleTag(i18n.language);
const fmtVal = (n: number) => n.toLocaleString(localeTag(), { maximumFractionDigits: 1 });
const signed = (d: number) => `${d < 0 ? '−' : '+'}${fmtVal(Math.abs(d))}`;
/* Postęp części: zmiana najnowszego pomiaru od pierwszego; spadek wagi = dobry kierunek. */
function progressOf(
g: { unit: 'kg' | 'cm'; points: GroupPoint[] },
changeText: (diff: string, unit: string) => string,
): {
text: string;
className: string;
} | null {
if (g.points.length < 2) return null;
const d = g.points[g.points.length - 1].value - g.points[0].value;
if (d === 0) return null;
const className = g.unit === 'kg' ? (d < 0 ? 'text-accent-text' : 'text-warn') : 'text-ink';
return { text: changeText(signed(d), g.unit), className };
}
/* Osobny div postępu wybranej części: kierunek zmiany + wynik (strony osobno, gdy łączone). */
function ProgressCard({
down,
primary,
primaryClass,
sub,
title,
}: {
down: boolean;
primary: string;
primaryClass: string;
sub: string;
title: string;
}) {
const Icon = down ? TrendingDown : TrendingUp;
return (
<Card className="mb-4">
<div className="flex items-center gap-3">
<span className="grid h-9 w-9 flex-none place-items-center rounded-[10px] bg-input text-dim">
<Icon className="h-4 w-4" />
</span>
<div className="min-w-0">
<H3 className="mb-0.5">{title}</H3>
<p className={`text-[0.95rem] font-semibold tabular-nums ${primaryClass}`}>{primary}</p>
<p className="text-[0.8125rem] text-dim">{sub}</p>
</div>
</div>
</Card>
);
}
/** Etykieta osi X: `17.10`; gdy historia przekracza rok — `17.10.26`. */
function axisDateLabel(iso: string, withYear: boolean): string {
return new Date(iso).toLocaleDateString(localeTag(), {
day: '2-digit',
month: '2-digit',
...(withYear ? { year: '2-digit' } : {}),
});
}
/** Klucz dnia kalendarzowego (lokalnego) — jeden dzień to jedna kategoria osi X. */
function dayKey(iso: string): string {
const d = new Date(iso);
return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
}
/**
* Dane wykresu: wiersze po dniach kalendarzowych — ten sam dzień mierzony
* dwa razy (lub z obu stron) daje jeden punkt z osią X (ostatnia wartość dnia).
*/
function chartData(points: GroupPoint[]) {
const rows = new Map<string, { day: string; date: string; value: number }>();
for (const p of points) {
const day = dayKey(p.date);
const row = rows.get(day) ?? { day, date: p.date, value: p.value };
row.date = p.date;
row.value = p.value;
rows.set(day, row);
}
return [...rows.values()];
}
const SIDE_STROKE: Record<Side, string> = { left: 'var(--info)', right: 'var(--accent)' };
/* Pojedyncza seria: obszar z gradientem, oś X po dniach (pomiary z dnia w jednym punkcie). */
function PartAreaChart({
name,
points,
stroke,
unit,
withYear,
height,
}: {
name: string;
points: GroupPoint[];
stroke: string;
unit: 'kg' | 'cm';
withYear: boolean;
height: number;
}) {
const rows = chartData(points);
const labelAt = (v: string | number) => {
const row = rows.find((r) => r.day === String(v));
return row ? axisDateLabel(row.date, withYear) : '';
};
const areaId = `bp-area-${encodeURIComponent(name)}`;
return (
<ResponsiveContainer width="100%" height={height}>
<AreaChart data={rows} margin={CHART_MARGIN}>
<defs>
<linearGradient id={areaId} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={stroke} stopOpacity={0.25} />
<stop offset="100%" stopColor={stroke} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid stroke="var(--border)" vertical={false} />
<XAxis
dataKey="day"
tickFormatter={labelAt}
tickLine={false}
axisLine={false}
tickMargin={10}
minTickGap={32}
tick={AXIS_TICK}
/>
<YAxis
width={44}
tickLine={false}
axisLine={false}
tickMargin={8}
domain={['auto', 'auto']}
tick={AXIS_TICK}
/>
<Tooltip
contentStyle={TOOLTIP_STYLE}
formatter={tooltipUnit(unit)}
labelFormatter={labelAt}
/>
<Area
type="monotone"
dataKey="value"
name={name}
stroke={stroke}
strokeWidth={2}
fill={`url(#${areaId})`}
dot={lineDot(stroke)}
activeDot={lineActiveDot(stroke)}
/>
</AreaChart>
</ResponsiveContainer>
);
}
/* Panel wybranej części. Strony mierzone (lewy/prawy) = dwa niezależne divy,
każdy z własnym nagłówkiem, postępem, wykresem i listą — lewy zawsze pierwszy. */
function MeasurementPanel({
group,
icon: Icon,
visible,
onShowMore,
sideLabel,
}: {
group: PartGroup;
icon: LucideIcon;
visible: number;
onShowMore: () => void;
sideLabel: (side: Side, gender: Gender) => string;
}) {
const sideName = (s: Side) => sideLabel(s, group.gender);
const sided = group.sidesPresent.length > 1;
if (!sided) {
return (
<Card>
<PartSection
title={group.label}
icon={Icon}
unit={group.unit}
points={group.points}
stroke={unitStroke(group.unit)}
chartName={group.label}
visible={visible}
onShowMore={onShowMore}
sideName={sideName}
/>
</Card>
);
}
const unsidePoints = group.points.filter((p) => p.side == null);
return (
<div className="flex flex-col gap-4">
{(['left', 'right'] as Side[])
.filter((s) => group.sidesPresent.includes(s))
.map((s) => (
<Card key={s}>
<PartSection
title={`${group.label} — ${sideName(s).toLowerCase()}`}
icon={Icon}
unit={group.unit}
points={group.points.filter((p) => p.side === s)}
stroke={SIDE_STROKE[s]}
chartName={sideName(s).toLowerCase()}
visible={visible}
onShowMore={onShowMore}
sideName={sideName}
/>
</Card>
))}
{unsidePoints.length > 0 && (
<Card>
<PartSection
title={group.label}
icon={Icon}
unit={group.unit}
points={unsidePoints}
stroke={unitStroke(group.unit)}
chartName={group.label}
visible={visible}
onShowMore={onShowMore}
sideName={sideName}
/>
</Card>
)}
</div>
);
}
/* Sekcja części/strony: nagłówek (nazwa + ostatni pomiar) + postęp + wykres historii + lista pomiarów.
Tylko do odczytu — pomiary dodaje i usuwa wyłącznie użytkownik w aplikacji. */
function PartSection({
title,
icon: Icon,
unit,
points,
stroke,
chartName,
visible,
onShowMore,
sideName,
}: {
title: string;
icon: LucideIcon;
unit: 'kg' | 'cm';
points: GroupPoint[];
stroke: string;
chartName: string;
visible: number;
onShowMore: () => void;
sideName: (side: Side) => string;
}) {
const { t } = useTranslation('users');
const latest = points[points.length - 1];
// historia przekracza rok → oś X z rokiem (również przy przerwie >12 mies. w jednym roku)
const withYear =
new Date(points[points.length - 1].date).getTime() - new Date(points[0].date).getTime() >
300 * 86_400_000;
// postęp sekcji (dla strony: osobna, przy łączonej: per strona): zmiana od pierwszego pomiaru
const prog = progressOf({ unit, points }, (diff, u) => t('changeSinceFirst', { diff, unit: u }));
const primary = prog?.text ?? t('noChange');
const primaryClass = prog?.className ?? 'text-dim';
const sub =
points.length < 2
? t('secondMeasurementHint')
: t('firstToLast', {
n: pomN(points.length, {
one: t('measurementWordOne'),
few: t('measurementWordFew'),
many: t('measurementWordMany'),
}),
});
return (
<>
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2.5">
<span
className="grid h-8 w-8 place-items-center rounded-[10px] bg-input"
style={{ color: stroke }}
>
<Icon className="h-4 w-4" />
</span>
<H3 className="mb-0">{title}</H3>
</div>
<span className="flex flex-col items-end">
<span className="flex items-baseline gap-2">
<span className="font-display text-[1.35rem] font-bold leading-none tabular-nums">
{latest.value} {unit}
</span>
<span className="text-[0.75rem] text-dim">{fmtDate(latest.date)}</span>
</span>
</span>
</div>
<ProgressCard
down={prog != null && prog.text.startsWith('−')}
primary={primary}
primaryClass={primaryClass}
sub={sub}
title={t('progressWord')}
/>
{points.length >= 2 ? (
<PartAreaChart
name={chartName}
points={points}
stroke={stroke}
unit={unit}
withYear={withYear}
height={220}
/>
) : (
<p className="text-dim">{t('chartNotEnough')}</p>
)}
{/* lista: najnowsze 3 + „Pokaż więcej" (kolejne 3); pełna historia w wykresie */}
<div>
<ul className="mt-3 flex flex-col gap-1.5 sm:flex-row sm:overflow-x-auto sm:pb-1">
{[...points]
.reverse()
.slice(0, visible)
.map((p) => {
const sideSuffix = p.side ? ` · ${sideName(p.side)}` : '';
return (
<li
key={p.id}
className="border border-line bg-input rounded-xl px-3.5 py-2.5 text-[0.95rem] sm:w-44 sm:shrink-0"
>
<strong className="text-ink">
{p.value} {unit}
</strong>
<div className="mt-0.5 text-[0.875rem] text-dim">
{fmtDate(p.date)}
{sideSuffix}
</div>
</li>
);
})}
</ul>
{points.length > visible && (
<Button variant="ghost" size="sm" className="mt-2" onClick={onShowMore}>
{t('common:showMore')}
</Button>
)}
</div>
</>
);
}
/**
* Parametry ciała użytkownika (admin) — tylko do odczyt: układ 1:1 z `/profile/body-parameters`
* aplikacji (zakładki części z pełną historią, panel postępu, wykresy obszarowe, strony
* osobno). Pomiary dodaje i usuwa wyłącznie użytkownik — brak kontrolek edycji.
*/
export default function UserBodyParameters() {
const { t } = useTranslation('users');
const { id } = useParams();
const { user } = useAdminUser(id);
const { data: bp, isLoading: bpLoading, error: bpError } = useUserBodyParameters(id);
const { measurementLabel, genderOf, sideLabel } = useMeasurementLabels();
const [visible, setVisible] = useState<Record<string, number>>({});
const [selected, setSelected] = useState<string | null>(null);
useTopbar({
// topbar = rodzic („Profil [nazwa]”), nazwa podstrony w PageHeader poniżej (h2)
title: user ? t('profileTitle', { name: userDisplayName(user) }) : t('profileFallback'),
back: id ? `/users/${id}` : '/users',
});
// lista panelu: 3 najnowsze + „Pokaż więcej" (kolejne 3)
const countFor = (key: string) => visible[key] ?? 3;
const showMore = (key: string) => setVisible((v) => ({ ...v, [key]: (v[key] ?? 3) + 3 }));
// pełna historia: waga + obwody jako jednolite grupy (bez filtra miesiąca)
const groups = useMemo<PartGroup[]>(() => {
const list: PartGroup[] = [];
const weightPoints = [...(bp?.weight ?? [])].sort((a, b) => a.date.localeCompare(b.date));
if (weightPoints.length > 0) {
const label = measurementLabel(WEIGHT_KEY);
list.push({
key: WEIGHT_KEY,
label,
gender: 'f',
unit: 'kg',
points: weightPoints.map((w) => ({
id: w.id,
value: w.value,
date: w.date,
side: null,
name: 'wagi',
})),
sidesPresent: [],
});
}
for (const g of groupCircumferences(bp?.circumferences ?? [])) {
const gender = genderOf(g.typeId);
const label = g.typeId ? measurementLabel(g.typeId) : (g.legacyName ?? '');
const points = g.series
.flatMap((s) =>
s.points.map((p) => ({
id: p.id,
value: p.value,
date: p.date,
side: s.side,
name: s.side ? `${label} · ${sideLabel(s.side, gender)}` : label,
})),
)
.sort((a, b) => a.date.localeCompare(b.date));
const sidesPresent = [
...new Set(g.series.map((s) => s.side).filter((s): s is Side => s != null)),
];
list.push({
key: g.key,
label,
gender,
unit: 'cm',
points,
sidesPresent,
});
}
return list;
}, [bp, measurementLabel, genderOf, sideLabel]);
// wybrana część odpada (brak danych) → pierwsza dostępna
const active = groups.find((g) => g.key === selected) ?? groups[0];
if (bpLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-64" />
</div>
);
}
return (
<>
<PageHeader
title={t('bodyParams')}
actions={<BackButton to={id ? `/users/${id}` : '/users'} />}
/>
{bpError ? (
<ErrorText>
{t('common:errorPrefix')}
{(bpError as Error).message}
</ErrorText>
) : active == null ? (
<EmptyState
icon={Scale}
title={t('bpNoMeasurements')}
description={t('bpNoMeasurementsDesc')}
/>
) : (
<>
{/* zakładki części: pełna nazwa (pasek jest przewijalny); szczegóły w panelu poniżej */}
<Tabs
tabs={groups.map((g) => ({ id: g.key, label: g.label }))}
active={active.key}
onChange={(id) => setSelected(id)}
/>
<div className="mt-4">
<MeasurementPanel
group={active}
icon={active.key === WEIGHT_KEY ? Scale : Ruler}
visible={countFor(active.key)}
onShowMore={() => showMore(active.key)}
sideLabel={sideLabel}
/>
</div>
</>
)}
</>
);
}

View File

@@ -1,110 +0,0 @@
import { Link, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { FileText } from 'lucide-react';
import { useTopbar } from '../../topbar';
import {
Badge,
BackButton,
Card,
EmptyState,
ErrorText,
ListRow,
PageHeader,
Skeleton,
} from '../../components/ui';
import { fmtDate } from '../../lib/format';
import { useAdminUser, useUserClaims } from './user-queries';
import { userDisplayName } from './UserDetail';
const STATUS_BADGE: Record<string, { labelKey: string; color: 'green' | 'yellow' | 'red' }> = {
PENDING: { labelKey: 'claimStatusPending', color: 'yellow' },
APPROVED: { labelKey: 'claimStatusApproved', color: 'green' },
REJECTED: { labelKey: 'claimStatusRejected', color: 'red' },
};
/**
* Wnioski siłowni złożone przez użytkownika (tylko podgląd — decyzje
* zapadają na stronie Weryfikacje). Dodatek admina do profilu użytkownika.
*/
export default function UserClaims() {
const { t } = useTranslation('users');
const { id } = useParams();
const { user } = useAdminUser(id);
useTopbar({
// topbar = rodzic („Profil [nazwa]”), nazwa podstrony w PageHeader poniżej (h2)
title: user ? t('profileTitle', { name: userDisplayName(user) }) : t('profileFallback'),
back: id ? `/users/${id}` : '/users',
});
const { data, isLoading, error } = useUserClaims(id);
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-40" />
</div>
);
}
const claims = data?.claims ?? [];
return (
<>
<PageHeader
title={t('claims')}
actions={
<>
{claims.length > 0 && <Badge>{claims.length}</Badge>}
<BackButton to={id ? `/users/${id}` : '/users'} />
</>
}
/>
<Card>
{error && (
<ErrorText>
{t('common:errorPrefix')}
{(error as Error).message}
</ErrorText>
)}
{!error && claims.length === 0 && (
<EmptyState icon={FileText} title={t('noClaimsTitle')} description={t('noClaimsDesc')} />
)}
{!error && claims.length > 0 && (
<div className="divide-y divide-line">
{claims.map((c) => {
const st = STATUS_BADGE[c.status];
const name = c.gym?.name || c.gymName || '—';
return (
<ListRow
key={c.id}
title={name}
meta={`${c.type === 'new' ? t('typeNew') : t('typeVerification')} · ${t('submittedOn', { date: fmtDate(c.createdAt) })}`}
actions={
<Link
to={`/verifications/${c.id}`}
className="text-accent-text text-[0.875rem] font-semibold hover:underline"
>
{t('details')}
</Link>
}
>
<div className="flex flex-wrap items-center gap-1.5 pt-1">
<Badge color={st?.color ?? 'gray'}>{st ? t(st.labelKey) : c.status}</Badge>
{c.documentCount != null && <Badge color="gray">{c.documentCount}</Badge>}
</div>
{c.status === 'REJECTED' && c.rejectReason && (
<p className="mt-1.5 text-[0.875rem] text-danger">
{t('reasonPrefix')}
{c.rejectReason}
</p>
)}
</ListRow>
);
})}
</div>
)}
</Card>
</>
);
}

View File

@@ -1,47 +1,43 @@
import { useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';
import {
Ban,
Building2,
ChevronRight,
Dumbbell,
CalendarDays,
FileText,
Flame,
History,
LogIn,
Pause,
Pencil,
Scale,
TrendingUp,
User,
type LucideIcon,
ScrollText,
} from 'lucide-react';
import { useTopbar } from '../../topbar';
import { api } from '../../api/client';
import { MembershipActionsModal } from '../../components/MembershipActionsModal';
import { Avatar } from '../../components/Avatar';
import {
BackButton,
Badge,
BackButton,
Card,
ConfirmDialog,
ErrorText,
H2,
H3,
Loading,
Muted,
SectionHeader,
StatCell,
} from '../../components/ui';
import { Avatar } from '../../components/Avatar';
import { ageFromBirthDate, displayName, fmtDate, fmtDateTime, fmtVolume } from '../../lib/format';
import { actionColor, actionLabel, actorName, detailsText, formatLogDate } from '../Logs';
import { UserRestrictionModal } from './UserRestrictionModal';
import { fmtDate, fmtDateTime, displayName } from '../../lib/format';
import {
useAdminUser,
useUserActivity,
useUserBodyParameters,
useUserClaims,
useUserExerciseProgress,
useUserHistory,
useUserKillstreak,
} from './user-queries';
detailsText,
actionLabel,
actorName,
formatLogDate,
actionColor,
} from '../../components/LogTable';
import { GYM_ROLE_META, GYM_ROLE_ORDER } from '../../lib/roles';
import { UserRestrictionModal } from './UserRestrictionModal';
import { useAdminUser, useUserActivity, useUserClaims } from './user-queries';
/** Nazwa wyświetlana użytkownika (nick → imię+nazwisko → e-mail). */
export function userDisplayName(u: {
@@ -53,95 +49,50 @@ export function userDisplayName(u: {
return displayName(u) === '—' ? u.email : displayName(u);
}
function sessionCountLabel(n: number, words: { one: string; few: string; many: string }): string {
const mod10 = n % 10;
const mod100 = n % 100;
if (mod10 === 1 && mod100 !== 11) return `${n} ${words.one}`;
if (mod10 >= 2 && mod10 <= 4 && !(mod100 >= 12 && mod100 <= 14)) return `${n} ${words.few}`;
return `${n} ${words.many}`;
}
/** Mini-statystyka: ikona + etykieta + wartość. */
function MiniStat({
icon: Icon,
label,
value,
}: {
icon: LucideIcon;
label: string;
value: string;
}) {
/* Rola jako pigułki — te same etykiety co w konsoli siłowni. */
function RoleBadges({ roles }: { roles: string[] }) {
const { t } = useTranslation();
const ordered = GYM_ROLE_ORDER.filter((r) => roles.includes(r));
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">
{value}
</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>
<span className="flex flex-wrap gap-1.5">
{ordered.map((r) => (
<Badge key={r} color={r === 'OWNER' ? 'blue' : 'gray'}>
{t(`common:${GYM_ROLE_META[r].labelKey}`)}
</Badge>
))}
</span>
);
}
/**
* Przegląd użytkownika (admin): hero + pasek mini-statystyk + sekcje jako wiersze-listy.
* Struktura wzorowana na profilu z aplikacji (`/profile`) z dodatkami admina.
* Konsola użytkownika (admin): tożsamość i status konta, członkostwa w siłowniach
* z menu edycji, wnioski usera oraz logi audytu na koncie — układ lustrzany
* względem konsoli siłowni (`GymDetail`). Statystyki treningowe są poza zakresem admina.
*/
export default function UserDetail() {
const { t } = useTranslation('users');
const { id } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
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 { data: progressData } = useUserExerciseProgress(id);
const { data: activityData } = useUserActivity(id);
const { data: activityData } = useUserActivity(id, 10);
const [confirmOpen, setConfirmOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [removeError, setRemoveError] = useState('');
const [restriction, setRestriction] = useState<'SUSPENDED' | 'BANNED' | null>(null);
const [manage, setManage] = useState<{ gymId: string; gymName: string; roles: string[] } | null>(
null,
);
// Menu trzyma tylko akcje (edycja/kary/usunięcie); nawigacja do podstron = wiersze w treści.
// Menu trzyma tylko akcje (edycja/logi/kary/usunięcie); resztą admin zarządza w treści.
useTopbar({
title: user ? userDisplayName(user) : t('userFallback'),
title: t('consoleTitle'),
back: '/users',
actions: user
? [
{ label: t('common:edit'), icon: Pencil, to: `/users/${user.id}/edit` },
{ label: t('logsAction'), icon: ScrollText, to: `/users/${user.id}/logs` },
{ label: t('suspend'), icon: Pause, onClick: () => setRestriction('SUSPENDED') },
{
label: t('ban'),
@@ -168,6 +119,7 @@ export default function UserDetail() {
setBusy(true);
try {
await api(`/admin/users/${user.id}`, { method: 'DELETE' });
await queryClient.invalidateQueries({ queryKey: ['admin-users'] });
navigate('/users');
} catch (err) {
setRemoveError(err instanceof Error ? err.message : t('common:error'));
@@ -176,209 +128,213 @@ export default function UserDetail() {
}
};
const invalidateUsers = () => queryClient.invalidateQueries({ queryKey: ['admin-users'] });
const name = userDisplayName(user);
const memberships = user.memberships ?? [];
// ostatnia waga (summary wiersza „Parametry ciała")
const weightPoints = [...(bp?.weight ?? [])].sort((a, b) => a.date.localeCompare(b.date));
const latestWeight = weightPoints[weightPoints.length - 1];
const weightSummary = latestWeight
? t('weightSummary', { value: latestWeight.value, date: fmtDate(latestWeight.date) })
: t('noMeasurements');
// 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, {
one: t('sessionsWordOne'),
few: t('sessionsWordFew'),
many: t('sessionsWordMany'),
})} · ${t('lastSession', { date: fmtDate(lastSession!) })}`
: t('noSessions');
const weekAgo = Date.now() - 7 * 24 * 3600 * 1000;
const volume7d = sessions
.filter((s) => new Date(s.startedAt).getTime() >= weekAgo)
.reduce(
(sum, s) =>
sum +
s.exercises
.flatMap((e) => e.sets)
.reduce(
(n, st) => (st.reps != null ? n + (st.planned?.loadKg ?? s.bodyKg ?? 0) * st.reps : n),
0,
),
0,
);
const gymsSummary =
memberships.length > 0
? memberships.map((m) => `${m.gym.name} (${m.roles.join(', ')})`).join(', ')
: t('none');
const claims = claimsData?.claims ?? [];
const pendingClaims = claims.filter((c) => c.status === 'PENDING').length;
const claimsSummary =
claims.length === 0
? t('none')
: pendingClaims > 0
? t('pendingClaims', { count: pendingClaims })
: t('resolvedClaims', { count: claims.length });
const progressCount = (progressData?.exercises ?? []).length;
const activityLogs = activityData?.logs ?? [];
const progressSummary =
progressCount > 0
? `${progressCount} ${
progressCount === 1
? t('exercisesWordOne')
: progressCount < 5 && progressCount % 10 >= 2 && progressCount % 10 <= 4
? t('exercisesWordFew')
: t('exercisesWordMany')
}`
: t('noData');
const logs = activityData?.logs ?? [];
return (
<>
{/* md+ „Wstecz” w treści (telefon: „<” w topbarze) — jak na GymDetail i podstronach */}
<BackButton to="/users" className="mb-4" />
<div className="flex flex-col gap-4">
{removeError && <ErrorText>{removeError}</ErrorText>}
{/* 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">
{t('createdOn', { date: fmtDate(user.createdAt) })}
</div>
{/* NAGŁÓWEK: nazwa usera (h2 — h1 należy do topbara) + powrót na listę */}
<div className="flex flex-wrap items-center justify-between gap-2">
<H2 className="mb-0 font-display text-[1.45rem] tracking-[-0.01em]">{name}</H2>
<BackButton to="/users">{t('backToList')}</BackButton>
</div>
{/* PANEL PODSUMOWANIA: identyfikacja + status konta + pasek danych administracyjnych */}
<Card className="mb-0 overflow-hidden p-0 sm:p-0">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-line px-4 py-3 text-[0.85rem] text-dim sm:px-5">
<span className="flex items-center gap-2.5">
<Avatar name={name} size={30} />
<b className="text-ink">{user.email}</b>
</span>
<span className="flex flex-wrap items-center gap-1.5">
{user.status === 'SUSPENDED' && (
<Badge color="yellow">
{t('statusSuspended')}
{user.suspensionUntil ? t('until', { dt: fmtDateTime(user.suspensionUntil) }) : ''}
</Badge>
)}
{user.status === 'BANNED' && <Badge color="red">{t('statusBanned')}</Badge>}
{user.status === 'BANNED' && user.restrictionReason && (
<span>{`${t('reasonPrefix')}${user.restrictionReason}`}</span>
)}
{user.nickname && <Badge color="blue">@{user.nickname}</Badge>}
{user.isAdmin && <Badge color="blue">{t('adminBadge')}</Badge>}
</span>
<span>{t('createdOn', { date: fmtDate(user.createdAt) })}</span>
</div>
<span className="flex flex-wrap items-center gap-1.5">
{user.status === 'SUSPENDED' && (
<Badge color="yellow">
{t('statusSuspended')}
{user.suspensionUntil ? t('until', { dt: fmtDateTime(user.suspensionUntil) }) : ''}
</Badge>
)}
{user.status === 'BANNED' && <Badge color="red">{t('statusBanned')}</Badge>}
{user.nickname && <Badge color="blue">@{user.nickname}</Badge>}
{user.isAdmin && <Badge color="blue">{t('adminBadge')}</Badge>}
{memberships.length > 0 && (
<Badge color="gray">{t('gymsShort', { count: memberships.length })}</Badge>
)}
</span>
</div>
{/* Pasek mini-statystyk: 2 na mobile, 3 w rzędzie na desktop */}
<div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-3">
<MiniStat
icon={Flame}
label={t('statKillstreak')}
value={ks ? String(ks.killstreak) : '—'}
/>
<MiniStat
icon={Dumbbell}
label={t('statVolume7d')}
value={volume7d > 0 ? fmtVolume(volume7d) : '—'}
/>
<MiniStat
icon={History}
label={t('statSessions')}
value={sessions.length > 0 ? String(sessions.length) : '—'}
/>
<MiniStat
icon={LogIn}
label={t('statLastLogin')}
value={user.lastLoginAt ? fmtDateTime(user.lastLoginAt) : '—'}
/>
</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={t('personalInfo')}
icon={User}
summary={
[
ageFromBirthDate(user.birthDate) != null
? t('ageValue', { age: ageFromBirthDate(user.birthDate) })
: null,
user.heightCm != null ? `${user.heightCm} cm` : null,
]
.filter(Boolean)
.join(' · ') || t('noData')
}
/>
<SectionLink
to={`/users/${user.id}/body-parameters`}
title={t('bodyParams')}
icon={Scale}
summary={weightSummary}
/>
<SectionLink
to={`/users/${user.id}/history`}
title={t('trainingHistory')}
icon={History}
summary={historySummary}
/>
</div>
<div className="divide-y divide-line">
<SectionLink
to={`/users/${user.id}/progress`}
title={t('progress')}
icon={TrendingUp}
summary={progressSummary}
/>
<SectionLink
to={`/users/${user.id}/memberships`}
title={t('membershipsTitle')}
icon={Building2}
summary={gymsSummary}
/>
<SectionLink
to={`/users/${user.id}/claims`}
title={t('claims')}
icon={FileText}
summary={claimsSummary}
/>
</div>
<div className="grid grid-cols-2 divide-x divide-line sm:grid-cols-4">
<StatCell
label={t('statLastLogin')}
value={user.lastLoginAt ? fmtDateTime(user.lastLoginAt) : '—'}
icon={<LogIn className="h-3.5 w-3.5" />}
/>
<StatCell
label={t('statMemberships')}
value={String(memberships.length)}
icon={<Building2 className="h-3.5 w-3.5" />}
/>
<StatCell
label={t('statClaims')}
value={String(claims.length)}
icon={<FileText className="h-3.5 w-3.5" />}
/>
<StatCell
label={t('statCreated')}
value={fmtDate(user.createdAt)}
icon={<CalendarDays className="h-3.5 w-3.5" />}
/>
</div>
</Card>
{/* Historia konta: logi audytu NA użytkowniku (logowania z IP, kto edytował dane, kary/bany) */}
<Card className="mt-4">
<SectionHeader title={t('accountHistory')} />
{activityLogs.length === 0 ? (
<Muted>{t('noActivity')}</Muted>
) : (
<div className="divide-y divide-line">
{activityLogs.map((log) => {
const details = detailsText(log);
return (
<div key={log.id} className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2.5">
<span className="font-display text-dim text-[0.8rem] tabular-nums">
{formatLogDate(log.createdAt)}
</span>
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
<span className="text-[0.875rem]">{t('byActor', { actor: actorName(log) })}</span>
{details && <span className="text-[0.8rem] text-dim">{details}</span>}
</div>
);
})}
</div>
)}
</Card>
{/* SIATKA ROBOCZA: członkostwa + logi (lewa) / wnioski (prawa szyna) */}
<div className="grid grid-cols-1 items-start gap-4 lg:grid-cols-[minmax(0,1fr)_330px]">
<div className="flex min-w-0 flex-col gap-4">
{/* CZŁONKOSTWA: klik w wiersz = menu (role / wyrzucenie z powodem) — jak w konsoli siłowni */}
<Card className="mb-0">
<div className="mb-3 flex items-center justify-between gap-2">
<H3 className="mb-0">
{t('membershipsTitle')}{' '}
<span className="text-dim tabular-nums">({memberships.length})</span>
</H3>
</div>
{memberships.length === 0 ? (
<p className="text-[0.875rem] text-dim">{t('noMemberships')}</p>
) : (
<div className="overflow-x-auto rounded-[10px] border border-line">
<table className="w-full text-[0.9rem]">
<thead>
<tr className="border-b border-line text-left text-dim">
<th className="px-3 py-2.5 text-[10.5px] font-bold uppercase tracking-[0.11em]">
{t('colGym')}
</th>
<th className="px-3 py-2.5 text-[10.5px] font-bold uppercase tracking-[0.11em]">
{t('colRoles')}
</th>
</tr>
</thead>
<tbody>
{memberships.map((m) => (
<tr
key={m.gymId}
onClick={() =>
setManage({ gymId: m.gymId, gymName: m.gym.name, roles: m.roles })
}
className="cursor-pointer border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20"
>
<td className="px-3 py-2.5 align-top">
<div className="font-semibold">{m.gym.name}</div>
{m.gym.location && (
<div className="text-[0.78rem] text-dim">{m.gym.location}</div>
)}
</td>
<td className="px-3 py-2.5 align-top">
<RoleBadges roles={m.roles} />
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Card>
{/* LOGI KONTA: ostatnie 10 + przejście do pełnej podstrony (jak logi w konsoli siłowni) */}
<Card className="mb-0">
<div className="mb-2 flex items-center justify-between gap-2">
<H3 className="mb-0">{t('logsCardTitle')}</H3>
<Link
to={`/users/${user.id}/logs`}
className="text-[0.85rem] font-semibold text-accent-text hover:underline"
>
{t('allLogs')}
</Link>
</div>
{logs.length === 0 ? (
<p className="text-[0.85rem] text-dim">{t('noActivity')}</p>
) : (
<div className="divide-y divide-line">
{logs.map((log) => {
const details = detailsText(log);
return (
<div
key={log.id}
className="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2.5"
>
<span className="font-display text-dim text-[0.8rem] tabular-nums">
{formatLogDate(log.createdAt)}
</span>
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
<span className="text-[0.875rem]">
{t('byActor', { actor: actorName(log) })}
</span>
{details && <span className="text-[0.8rem] text-dim">{details}</span>}
</div>
);
})}
</div>
)}
</Card>
</div>
<aside className="flex min-w-0 flex-col gap-4">
{/* WNIOSKI siłowni złożone przez usera (read-only; decyzje w /verifications) */}
<Card className="mb-0">
<H3 className="mb-2">{t('claims')}</H3>
{claims.length === 0 ? (
<p className="text-[0.85rem] text-dim">{t('noClaimsDesc')}</p>
) : (
<div className="-mb-1 flex flex-col">
{claims.map((c) => (
<div
key={c.id}
className="flex flex-wrap items-center gap-2 border-b border-line/50 py-2 text-[0.83rem] last:border-b-0"
>
<Link
to={`/verifications/${c.id}`}
className="font-semibold hover:text-accent-text"
>
{c.gym?.name ?? c.gymName ?? '—'}
</Link>
<Badge
color={
c.status === 'PENDING'
? 'yellow'
: c.status === 'APPROVED'
? 'green'
: 'red'
}
>
{t(`claimStatus${c.status.charAt(0)}${c.status.slice(1).toLowerCase()}`)}
</Badge>
<span className="ml-auto text-[0.76rem] tabular-nums text-dim">
{fmtDate(c.createdAt)}
</span>
</div>
))}
</div>
)}
</Card>
</aside>
</div>
{manage && (
<MembershipActionsModal
key={manage.gymId}
userId={user.id}
titleName={manage.gymName}
gymId={manage.gymId}
roles={manage.roles}
showProfileLink={false}
onClose={() => setManage(null)}
onChanged={() => void invalidateUsers()}
/>
)}
<ConfirmDialog
open={confirmOpen}
@@ -398,6 +354,6 @@ export default function UserDetail() {
onClose={() => setRestriction(null)}
/>
)}
</>
</div>
);
}

View File

@@ -1,89 +0,0 @@
import { useState } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { History } from 'lucide-react';
import { useTopbar } from '../../topbar';
import { MonthPickerCore } from '../../topbar/MonthPicker';
import { BackButton, Card, EmptyState, ErrorText, PageHeader, Skeleton } from '../../components/ui';
import { useAdminUser, useUserHistory } from './user-queries';
import { userDisplayName } from './UserDetail';
import HistoryTable from '../../components/HistoryTable';
/**
* Historia treningów użytkownika (admin, tylko do odczyt) z filtrem miesiąca.
* Układ wzorowany na `/profile/history` z aplikacji.
*/
export default function UserHistory() {
const { t } = useTranslation('users');
const { id } = useParams();
const { user } = useAdminUser(id);
const [params] = useSearchParams();
const initialOpenSessionId = params.get('session') ?? undefined;
const [month, setMonth] = useState('');
// pełna historia (cache) → lista miesięcy do selektora + widok „Wszystkie”
const { data: fullHist, isLoading: fullLoading } = useUserHistory(id);
const { data: hist, isLoading, error } = useUserHistory(id, month || undefined);
const availableMonths = [
...new Set((fullHist?.sessions ?? []).map((s) => (s.date ?? s.startedAt).slice(0, 7))),
]
.sort()
.reverse();
useTopbar({
// topbar = rodzic („Profil [nazwa]”), nazwa podstrony w PageHeader poniżej (h2)
title: user ? t('profileTitle', { name: userDisplayName(user) }) : t('profileFallback'),
back: id ? `/users/${id}` : '/users',
dateFilter: (
<MonthPickerCore
month={month}
setMonth={setMonth}
availableMonths={availableMonths}
allowAll
/>
),
filterActive: month !== '',
});
// „Wszystkie” = pełny fetch; miesiąc = filtr API
const sessions = month === '' ? (fullHist?.sessions ?? []) : (hist?.sessions ?? []);
const loading = month === '' ? fullLoading : isLoading;
if (loading) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-64" />
</div>
);
}
return (
<>
<PageHeader
title={t('trainingHistory')}
actions={<BackButton to={id ? `/users/${id}` : '/users'} />}
/>
<Card>
{error && (
<ErrorText>
{t('common:errorPrefix')}
{(error as Error).message}
</ErrorText>
)}
{!error && sessions.length === 0 && (
<EmptyState
icon={History}
title={month ? t('noSessionsMonthTitle') : t('noSessionsTitle')}
description={month ? t('noSessionsMonthDesc') : t('noSessionsDesc')}
/>
)}
{!error && sessions.length > 0 && (
<HistoryTable sessions={sessions} initialOpenSessionId={initialOpenSessionId} />
)}
</Card>
</>
);
}

View File

@@ -1,436 +0,0 @@
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import {
ArrowRight,
AtSign,
Cake,
Clock,
Link2,
Phone,
Ruler,
Sparkles,
User,
type LucideIcon,
} from 'lucide-react';
import { useTopbar } from '../../topbar';
import { api } from '../../api/client';
import type {
FocusArea,
FocusChain,
SocialMediaEntry,
SocialMediaPlatform,
User as UserT,
} from '../../api/types';
import {
BackButton,
Badge,
Card,
Loading,
PageHeader,
SectionHeader,
Skeleton,
} from '../../components/ui';
import { Avatar } from '../../components/Avatar';
import { MUSCLE_COLORS, muscleName, SOCIAL_MEDIA_LABELS } from '../../lib/labels';
import { ageFromBirthDate, fmtDate } from '../../lib/format';
import { localizedName } from '../../lib/localizedName';
import { formatAvailabilityParts } from '../../lib/availability';
import { useAdminUser } from './user-queries';
import { userDisplayName } from './UserDetail';
type MuscleTone = 'develop' | 'canDo' | 'difficult' | 'avoid';
/* 4 niezależne grupy mięśni. Ton = kolor chipa/badge'a + etykieta sekcji. */
const MUSCLE_TONES = {
develop: {
badge: 'green',
text: 'text-accent-text',
/* podświetlenie grupy w karcie ciągu (bg + border lewy + kolor tekstu) */
tint: 'border-accent/40 bg-accent/10',
dot: 'bg-accent',
labelKey: 'toneDevelop',
chainPrefixKey: 'chainPrefixDevelop',
},
canDo: {
badge: 'blue',
text: 'text-info',
tint: 'border-info/40 bg-info/10',
dot: 'bg-info',
labelKey: 'toneCanDo',
chainPrefixKey: '',
},
difficult: {
badge: 'yellow',
text: 'text-warn',
tint: 'border-warn/40 bg-warn/10',
dot: 'bg-warn',
labelKey: 'toneDifficult',
chainPrefixKey: '',
},
avoid: {
badge: 'red',
text: 'text-danger',
tint: 'border-danger/40 bg-danger/10',
dot: 'bg-danger',
labelKey: 'toneAvoid',
chainPrefixKey: 'chainPrefixAvoid',
},
} as const;
const MUSCLE_FIELD_BY_TONE: Record<MuscleTone, keyof UserT> = {
develop: 'developMuscles',
canDo: 'canDoMuscles',
difficult: 'difficultMuscles',
avoid: 'avoidMuscles',
};
/* Płytka informacyjna: ikona w tonie akcentu + etykieta + wartość (spójna z
mini-statystykami przeglądu profilu). Puste wartości wyciszone. */
function InfoTile({
icon: Icon,
label,
value,
}: {
icon: LucideIcon;
label: string;
value: string;
}) {
const empty = value === '—';
return (
<div className="flex items-center gap-3 rounded-[10px] border border-line bg-input/40 px-3 py-2.5">
<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 text-[0.95rem] font-semibold ${empty ? 'text-dim' : ''}`.trim()}>
{value}
</div>
</div>
</div>
);
}
/* Płytki link społecznościowy: markowa kropka z inicjałem + nazwa + adres + strzałka. */
const SOCIAL_BRAND: Record<SocialMediaPlatform, { color: string; initial: string }> = {
INSTAGRAM: { color: 'linear-gradient(150deg,#f09433,#dc2743,#bc1888)', initial: 'i' },
TIKTOK: { color: 'linear-gradient(150deg,#25f4ee,#000 60%,#fe2c55)', initial: 'T' },
YOUTUBE: { color: 'linear-gradient(150deg,#ff5b4a,#c4302b)', initial: 'Y' },
FACEBOOK: { color: 'linear-gradient(150deg,#5b8def,#1877f2)', initial: 'f' },
X: { color: 'linear-gradient(150deg,#6b7280,#111)', initial: 'X' },
OTHER: { color: 'linear-gradient(150deg,#8fa3b8,#5f7183)', initial: '·' },
};
function hostOf(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, '');
} catch {
return url;
}
}
function SocialTile({ entry }: { entry: SocialMediaEntry }) {
const { t } = useTranslation();
const label =
entry.platform === 'OTHER'
? entry.label || t('socialMedia.OTHER')
: SOCIAL_MEDIA_LABELS[entry.platform];
const brand = SOCIAL_BRAND[entry.platform];
return (
<a
href={entry.url}
target="_blank"
rel="noopener noreferrer"
aria-label={label}
className="group flex items-center gap-3 rounded-xl border border-line bg-input/40 px-3.5 py-3 transition-colors hover:border-accent/45 hover:bg-accent/[0.06]"
>
<span
aria-hidden="true"
className="grid h-9 w-9 shrink-0 place-items-center rounded-full text-[0.85rem] font-extrabold text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.25)]"
style={{ background: brand.color }}
>
{brand.initial}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[0.95rem] font-semibold">{label}</span>
<span className="block truncate text-[0.8125rem] text-dim">{hostOf(entry.url)}</span>
</span>
<ArrowRight className="h-4 w-4 shrink-0 text-dim transition-transform group-hover:translate-x-0.5 group-hover:text-accent-text" />
</a>
);
}
/* Ciąg przyczynowo-skutkowy: 4 kafelki w tonie grupy (kolor spójny z „Priorytety
i wykluczenia”); puste tony wyciszone. Nazwy mięśni ujednolicone z resztą aplikacji. */
function FocusChainCard({ chain }: { chain: FocusChain | undefined }) {
const { t, i18n } = useTranslation('users');
return (
<Card>
<SectionHeader
title={
<span className="flex items-center gap-2">
<Sparkles className="h-4.5 w-4.5 text-accent-text" />
{t('chainTitle')}
</span>
}
description={t('chainDesc')}
/>
{chain ? (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
{(Object.keys(MUSCLE_TONES) as MuscleTone[]).map((tone) => {
const entries = chain[tone] ?? [];
const toneMeta = MUSCLE_TONES[tone];
return (
<div
key={tone}
className={`rounded-xl border-l-[3px] border-y border-r px-4 py-3 ${
entries.length > 0 ? toneMeta.tint : 'border-line bg-input/40'
}`}
>
<div className="mb-2 flex items-center gap-2">
<span
className={`h-2 w-2 shrink-0 rounded-full ${
entries.length > 0 ? toneMeta.dot : 'bg-dim/40'
}`}
aria-hidden="true"
/>
<span
className={`text-[11px] font-bold uppercase tracking-[0.1em] ${
entries.length > 0 ? toneMeta.text : 'text-dim'
}`}
>
{t(toneMeta.labelKey)}
</span>
</div>
{entries.length === 0 ? (
<span className="text-[0.875rem] text-dim">{t('chainNoFocus')}</span>
) : (
<div className="space-y-3">
{entries.map((e) => (
<div key={e.muscle}>
<div className="flex items-center gap-2">
<Badge color={MUSCLE_COLORS[e.muscle] ?? 'gray'}>
{muscleName(e.muscle) || localizedName(e, i18n.language)}
</Badge>
{(e.exercises ?? []).length > 0 && (
<span className="text-[0.75rem] font-bold tabular-nums text-dim">
{(e.exercises ?? []).length}
</span>
)}
</div>
<div className="mt-1 text-[0.875rem] text-dim">
{(e.exercises ?? []).length > 0
? `${toneMeta.chainPrefixKey ? t(toneMeta.chainPrefixKey) : ''}${(
e.exercises ?? []
)
.map((x) => localizedName(x, i18n.language))
.join(', ')}`
: t('chainNotInPlan')}
</div>
</div>
))}
</div>
)}
</div>
);
})}
</div>
) : (
<Loading />
)}
</Card>
);
}
function InfoRow({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-baseline justify-between gap-4 px-2 py-2.5">
<span className="shrink-0 text-[0.9rem] text-dim">{label}</span>
<span className="min-w-0 truncate text-right text-[0.95rem] font-semibold">{value}</span>
</div>
);
}
/**
* Tylko do odczytu: układ 1:1 z podstroną `/profile/info` aplikacji (kafelki
* z ikonami, tone'owane grupy mięśni, kafelki social, ciąg przyczynowo-skutkowy).
* Profil (nick, telefon, wzrost, dostępność, mięśnie, social) edytuje wyłącznie
* użytkownik w aplikacji; admin zmienia tożsamość/dostęp w wizardzie `/users/:id/edit`.
* Karta „Konto” (e-mail, admin, data utworzenia) to dodatek admina.
*/
export default function UserInfo() {
const { t, i18n } = useTranslation('users');
const { id } = useParams();
const { user, isLoading } = useAdminUser(id);
const { data: areasData } = useQuery({
queryKey: ['focus-areas'],
queryFn: () => api<{ focusAreas: FocusArea[] }>('/admin/focus-areas'),
});
const { data: chain } = useQuery({
queryKey: ['focus-chain', id],
queryFn: () => api<FocusChain>(`/admin/users/${id}/focus-chain`),
enabled: !!id,
});
const areas = areasData?.focusAreas ?? [];
const areaName = (muscle: string) => {
const a = areas.find((x) => x.muscle === muscle);
return a ? localizedName(a, i18n.language) : muscle;
};
useTopbar({
// topbar = rodzic („Profil [nazwa]”), nazwa podstrony w PageHeader poniżej (h2)
title: user ? t('profileTitle', { name: userDisplayName(user) }) : t('profileFallback'),
back: id ? `/users/${id}` : '/users',
});
if (isLoading || !user) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-48" />
<Skeleton className="h-48" />
</div>
);
}
const name = userDisplayName(user);
const availabilityParts = formatAvailabilityParts(user.availability);
const age = ageFromBirthDate(user.birthDate);
return (
<>
<PageHeader
title={t('personalInfo')}
leading={<Avatar name={name} size={40} />}
actions={<BackButton to={`/users/${user.id}`} />}
/>
{/* Karta: konto (stan konta — edycja w wizardzie); dodatek admina */}
<Card>
<SectionHeader title={t('accountCard')} />
<div className="divide-y divide-line">
<InfoRow label={t('auth:email')} value={user.email} />
<InfoRow
label={t('common:roles.admin.label')}
value={user.isAdmin ? t('fullAccess') : t('accountNone')}
/>
<InfoRow label={t('createdLabel')} value={fmtDate(user.createdAt)} />
</div>
</Card>
{/* Karta 1: podstawowe dane — siatka płytek z ikonami + dostępność jako chipy */}
<Card>
<SectionHeader title={t('basicData')} />
<div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
<InfoTile icon={User} label={t('firstName')} value={user.firstName || '—'} />
<InfoTile icon={User} label={t('lastName')} value={user.lastName || '—'} />
<InfoTile icon={Cake} label={t('birthDate')} value={fmtDate(user.birthDate)} />
<InfoTile
icon={User}
label={t('age')}
value={age != null ? t('ageValue', { age }) : '—'}
/>
<InfoTile
icon={Ruler}
label={t('height')}
value={user.heightCm != null ? `${user.heightCm} cm` : '—'}
/>
<InfoTile icon={Phone} label={t('phone')} value={user.phone || '—'} />
<InfoTile icon={AtSign} label={t('nick')} value={user.nickname || '—'} />
</div>
<div className="mt-3 rounded-[10px] border border-line bg-input/40 px-3.5 py-3">
<div className="mb-2 flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
<Clock className="h-3.5 w-3.5" />
{t('availabilityLabel')}
</div>
{availabilityParts.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{availabilityParts.map((p) => (
<Badge key={p} color="blue" className="font-semibold">
{p}
</Badge>
))}
</div>
) : (
<span className="text-[0.875rem] text-dim">{t('noAvailability')}</span>
)}
</div>
</Card>
{/* Karta 2: priorytety i wykluczenia — 4 kafelki w tonie grupy */}
<Card>
<SectionHeader title={t('prioritiesTitle')} />
<div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
{(Object.keys(MUSCLE_TONES) as MuscleTone[]).map((tone) => {
const musclesList = (user[MUSCLE_FIELD_BY_TONE[tone]] as string[] | undefined) ?? [];
const toneMeta = MUSCLE_TONES[tone];
return (
<div
key={tone}
className={`rounded-xl border-l-[3px] border-y border-r px-4 py-3 ${
musclesList.length > 0 ? toneMeta.tint : 'border-line bg-input/40'
}`}
>
<div className="mb-2 flex items-center gap-2">
<span
className={`h-2 w-2 shrink-0 rounded-full ${
musclesList.length > 0 ? toneMeta.dot : 'bg-dim/40'
}`}
aria-hidden="true"
/>
<span
className={`text-[11px] font-bold uppercase tracking-[0.1em] ${
musclesList.length > 0 ? toneMeta.text : 'text-dim'
}`}
>
{t(toneMeta.labelKey)}
</span>
{musclesList.length > 0 && (
<span className="ml-auto text-[11px] font-bold tabular-nums text-dim">
{musclesList.length}
</span>
)}
</div>
<div className="flex flex-wrap gap-1.5">
{musclesList.length > 0 ? (
musclesList.map((m) => (
<Badge
key={m}
color={toneMeta.badge as 'green' | 'blue' | 'yellow' | 'red'}
className="bg-card/70"
>
{areaName(m)}
</Badge>
))
) : (
<span className="text-[0.875rem] text-dim">{t('nothingAdded')}</span>
)}
</div>
</div>
);
})}
</div>
</Card>
{/* Karta 3: social media — kafelki linków z markową kropką i domeną */}
<Card>
<SectionHeader title={t('socialMediaTitle')} />
{(user.socialMedia ?? []).length > 0 ? (
<div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
{(user.socialMedia ?? []).map((s, i) => (
<SocialTile key={i} entry={s} />
))}
</div>
) : (
<div className="flex items-center gap-3 rounded-xl border border-dashed border-line bg-input/40 px-4 py-4 text-[0.875rem] text-dim">
<Link2 className="h-4 w-4 shrink-0" />
{t('noSocialProfiles')}
</div>
)}
</Card>
<FocusChainCard chain={chain} />
</>
);
}

View File

@@ -0,0 +1,84 @@
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ScrollText } from 'lucide-react';
import { useAdminUser, useUserActivity } from './user-queries';
import { userDisplayName } from './UserDetail';
import { BackButton, EmptyState, ErrorText, Loading } from '../../components/ui';
import { LogTable } from '../../components/LogTable';
import { useTopbar } from '../../topbar';
/* Podstrona logów użytkownika (read-only): audyt wykonany NA koncie — logowania (IP),
edycje, kary, zmiany ról. Układ lustrzany względem podstrony logów siłowni. */
const PAGE_SIZE = 50;
export default function UserLogsPage() {
const { t } = useTranslation('users');
const { id } = useParams();
const [limit, setLimit] = useState(PAGE_SIZE);
const { user, isLoading, error } = useAdminUser(id);
const { data, isLoading: logsLoading } = useUserActivity(id, limit);
const logs = data?.logs ?? [];
const total = data?.total ?? 0;
useTopbar({ title: t('logsPage.title'), back: `/users/${id}` });
if (isLoading) return <Loading />;
if (error)
return (
<>
<BackButton to={`/users/${id}`} className="mb-4" />
<ErrorText>
{t('common:errorPrefix')}
{(error as Error).message}
</ErrorText>
</>
);
if (!user) {
return (
<>
<BackButton to={`/users/${id}`} className="mb-4" />
<ErrorText>{t('notFound')}</ErrorText>
</>
);
}
return (
<>
{/* HERO-LITE: nazwa użytkownika (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]">
{userDisplayName(user)}
</span>
<p className="mt-0.5 text-[0.85rem] text-dim">{t('logsPage.subtitle')}</p>
</div>
<BackButton to={`/users/${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,88 +0,0 @@
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useTopbar } from '../../topbar';
import { GYM_ROLE_META } from '../../lib/roles';
import {
BackButton,
Badge,
Card,
ErrorText,
ListRow,
Muted,
PageHeader,
SectionHeader,
Skeleton,
} from '../../components/ui';
import { useAdminUser } from './user-queries';
import { userDisplayName } from './UserDetail';
/**
* Członkostwa użytkownika w siłowniach (admin): tylko do odczytu.
* Edycja członkostw istnieje wyłącznie w edytorze (wizard „Nowy/Edycja
* użytkownika") — zgodnie z zasadą: read-only wszędzie, czego admin nie edytuje
* poza swoim edytorem.
*/
export default function UserMemberships() {
const { t } = useTranslation('users');
const { id } = useParams();
const { user, isLoading, error } = useAdminUser(id);
// topbar = rodzic („Profil [nazwa]”), nazwa podstrony w PageHeader poniżej (h2)
useTopbar({
title: user ? t('profileTitle', { name: userDisplayName(user) }) : t('profileFallback'),
back: id ? `/users/${id}` : '/users',
});
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-48" />
</div>
);
}
if (error)
return (
<ErrorText>
{t('common:errorPrefix')}
{(error as Error).message}
</ErrorText>
);
if (!user) return <ErrorText>{t('notFound')}</ErrorText>;
const memberships = user.memberships ?? [];
return (
<>
<PageHeader
title={t('membershipsTitle')}
badge={memberships.length > 0 ? <Badge>{memberships.length}</Badge> : undefined}
actions={<BackButton to={`/users/${user.id}`} />}
/>
<Card>
<SectionHeader
title={t('affiliations')}
actions={memberships.length > 0 ? <Badge>{memberships.length}</Badge> : undefined}
/>
{memberships.length > 0 ? (
<div className="divide-y divide-line">
{memberships.map((m) => (
<ListRow key={m.gymId} title={m.gym.name} meta={m.gym.location || undefined}>
<div className="flex flex-wrap gap-2 pt-1">
{m.roles.map((r) => (
<Badge key={r} color="gray">
{t(`common:${GYM_ROLE_META[r].labelKey}`)}
</Badge>
))}
</div>
</ListRow>
))}
</div>
) : (
<Muted>{t('noMemberships')}</Muted>
)}
</Card>
</>
);
}

View File

@@ -1,61 +0,0 @@
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { TrendingUp } from 'lucide-react';
import { useTopbar } from '../../topbar';
import { BackButton, Card, EmptyState, ErrorText, PageHeader, Skeleton } from '../../components/ui';
import ExerciseProgressCards from '../../components/ExerciseProgressCards';
import { useAdminUser, useUserExerciseProgress } from './user-queries';
import { userDisplayName } from './UserDetail';
/**
* Postępy per ćwiczenie użytkownika — widok admina 1:1 z `/profile/progress`
* z aplikacji (czyt. opis wzoru 1RM usunięty z obu stron).
*/
export default function UserProgress() {
const { t } = useTranslation('users');
const { id } = useParams();
const { user } = useAdminUser(id);
useTopbar({
// topbar = rodzic („Profil [nazwa]”), nazwa podstrony w PageHeader poniżej (h2)
title: user ? t('profileTitle', { name: userDisplayName(user) }) : t('profileFallback'),
back: id ? `/users/${id}` : '/users',
});
const { data, isLoading, error } = useUserExerciseProgress(id);
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-64" />
</div>
);
}
const exercises = data?.exercises ?? [];
return (
<>
<PageHeader
title={t('progress')}
actions={<BackButton to={id ? `/users/${id}` : '/users'} />}
/>
<Card>
{error && (
<ErrorText>
{t('common:errorPrefix')}
{(error as Error).message}
</ErrorText>
)}
{!error && exercises.length === 0 && (
<EmptyState
icon={TrendingUp}
title={t('noProgressTitle')}
description={t('noProgressDesc')}
/>
)}
{!error && exercises.length > 0 && <ExerciseProgressCards exercises={exercises} />}
</Card>
</>
);
}

View File

@@ -1,15 +1,6 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '../../api/client';
import type {
ActivityLogPage,
CircumferenceSeries,
ExerciseProgress,
Gym,
GymClaim,
HistorySession,
User,
WeightPoint,
} from '../../api/types';
import type { ActivityLogPage, Gym, GymClaim, User } from '../../api/types';
/** Lista użytkowników admina — wspólne źródło danych dla podstron /users/:id/*. */
export function useAdminUsers() {
@@ -38,46 +29,6 @@ export function useUserGyms(enabled = true) {
});
}
export interface BodyParameters {
weight: WeightPoint[];
circumferences: CircumferenceSeries[];
}
export function useUserBodyParameters(id?: string) {
return useQuery({
queryKey: ['user-body-parameters', id],
queryFn: () => api<BodyParameters>(`/admin/users/${id}/body-parameters`),
enabled: !!id,
});
}
export function useUserHistory(id?: string, month?: string) {
return useQuery({
queryKey: ['user-history', id, month ?? 'all'],
queryFn: () =>
api<{ sessions: HistorySession[] }>(
`/admin/users/${id}/history${month ? `?month=${month}` : ''}`,
),
enabled: !!id,
});
}
export function useUserExerciseProgress(id?: string) {
return useQuery({
queryKey: ['user-exercise-progress', id],
queryFn: () => api<{ exercises: ExerciseProgress[] }>(`/admin/users/${id}/exercise-progress`),
enabled: !!id,
});
}
export function useUserKillstreak(id?: string) {
return useQuery({
queryKey: ['user-killstreak', id],
queryFn: () => api<{ killstreak: number }>(`/admin/users/${id}/killstreak`),
enabled: !!id,
});
}
/** Wnioski siłowni złożone przez użytkownika (lista adminowa, filtr userId). */
export function useUserClaims(id?: string) {
return useQuery({

View File

@@ -1,165 +0,0 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserBodyParameters from '../src/pages/users/UserBodyParameters';
import { setAccessToken } from '../src/api/client';
const BP = {
weight: [
{ id: 'w1', value: 82, date: '2026-09-01T10:00:00.000Z' },
{ id: 'w2', value: 81.5, date: '2026-09-10T10:00:00.000Z' },
],
circumferences: [
{
typeId: 'biceps',
side: 'left',
name: null,
points: [
{ id: 'c1', value: 35, date: '2026-09-01T10:00:00.000Z' },
{ id: 'c3', value: 36, date: '2026-09-20T10:00:00.000Z' },
],
},
{
typeId: 'biceps',
side: 'right',
name: null,
points: [{ id: 'c2', value: 35.5, date: '2026-09-09T10:00:00.000Z' }],
},
{
typeId: 'chest',
side: null,
name: null,
points: [{ id: 'c4', value: 100, date: '2026-09-05T10:00:00.000Z' }],
},
],
};
/** Mock fetch wg fragmentu URL (odwrócona kolejność = specyficzne trasy wygrywają). */
function mockFetchRoutes(routes: Array<[string, () => unknown]>) {
const calls: { url: string; init?: RequestInit }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
calls.push({ url, init });
const entry = [...routes].reverse().find(([frag]) => url.includes(frag));
if (!entry) throw new Error(`No mocked route for url: ${url}`);
const body = entry[1]();
if (body === null) return new Response(null, { status: 204 });
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
function renderPage() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/users/u1/body-parameters']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/users/:id/body-parameters" element={<UserBodyParameters />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserBodyParameters page', () => {
it('zakładki z pełną historią: waga + obwody grupowane po części (pełne nazwy)', async () => {
mockFetchRoutes([['/body-parameters', () => BP]]);
renderPage();
expect(
await screen.findByRole('heading', { name: 'Parametry ciała', level: 2 }),
).toBeInTheDocument();
// zakładki części z pełnymi nazwami (bez skrótu „Przedr.”)
expect(await screen.findByRole('button', { name: 'Waga' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Klatka piersiowa' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Biceps' })).toBeInTheDocument();
// panel Wagi (pierwsza zakładka): najnowszy pomiar + postęp + pełna historia
expect(screen.getByRole('heading', { name: 'Waga', level: 3 })).toBeInTheDocument();
expect(screen.getAllByText('81.5 kg').length).toBeGreaterThan(0);
expect(screen.getByRole('heading', { name: 'Postęp' })).toBeInTheDocument();
// separator dziesiętny bywa kropką lub przecinkiem zależnie od implementacji Intl
expect(screen.getByText(/−0[.,]5 kg od pierwszego/)).toBeInTheDocument();
// lista z pełnej historii (oba pomiary, nawet sprzed „bieżącego miesiąca”);
// wartość i jednostka to osobne węzły tekstowe w kafelku listy
const tiles = () =>
Array.from(document.querySelectorAll('li')).map((li) =>
(li.textContent ?? '').replace(/\s+/g, ' ').trim(),
);
expect(tiles().some((t) => t.startsWith('82 kg'))).toBe(true);
});
it('strony mierzone jako dwa niezależne panele z własnym postępem', async () => {
mockFetchRoutes([['/body-parameters', () => BP]]);
renderPage();
const bicepsTab = await screen.findByRole('button', { name: 'Biceps' });
fireEvent.click(bicepsTab);
// lewy zawsze pierwszy, potem prawy — każdy jako osobna karta
expect(await screen.findByRole('heading', { name: 'Biceps — lewy' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Biceps — prawy' })).toBeInTheDocument();
expect(screen.getAllByRole('heading', { name: 'Postęp' }).length).toBe(2);
expect(screen.getAllByText('Za mało danych na wykres (min. 2 pomiary).').length).toBe(1);
});
it('pokaż więcej odkrywa kolejne pomiary z historii', async () => {
const many = {
weight: Array.from({ length: 5 }, (_, i) => ({
id: `w${i}`,
value: 80 + i / 10,
date: `2026-08-0${i + 1}T10:00:00.000Z`,
})),
circumferences: [],
};
mockFetchRoutes([['/body-parameters', () => many]]);
renderPage();
await screen.findByRole('heading', { name: 'Waga', level: 3 });
// domyślnie 3 najnowsze, gwóźdź programu: 4. pomiar ukryty do kliknięcia
const tiles = () =>
Array.from(document.querySelectorAll('li')).map((li) =>
(li.textContent ?? '').replace(/\s+/g, ' ').trim(),
);
expect(tiles().some((t) => /^80[.,]1 kg/.test(t))).toBe(false);
fireEvent.click(screen.getByRole('button', { name: 'Pokaż więcej' }));
expect(tiles().some((t) => /^80[.,]1 kg/.test(t))).toBe(true);
});
it('pokazuje stan pusty, gdy użytkownik nie ma pomiarów', async () => {
mockFetchRoutes([['/body-parameters', () => ({ weight: [], circumferences: [] })]]);
renderPage();
expect(await screen.findByText('Brak pomiarów')).toBeInTheDocument();
expect(
screen.getByText(
'Pomiary pojawią się tutaj, gdy użytkownik doda wagę lub obwód w aplikacji.',
),
).toBeInTheDocument();
});
it('jest tylko do odczytu — brak kontrolek dodawania i usuwania pomiarów', async () => {
mockFetchRoutes([['/body-parameters', () => BP]]);
renderPage();
await screen.findByRole('heading', { name: 'Waga', level: 3 });
expect(screen.queryByRole('button', { name: '+ Waga' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Dodaj wagę' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Dodaj pomiar' })).not.toBeInTheDocument();
expect(screen.queryAllByRole('button', { name: /Usuń pomiar/ })).toHaveLength(0);
});
});

View File

@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
@@ -65,6 +65,12 @@ function mockFetchRoutes(routes: Array<[string, () => unknown]>) {
return calls;
}
const BASE_ROUTES: Array<[string, () => unknown]> = [
['/admin/users', () => ({ users: [U1] })],
['/claims', () => ({ claims: [] })],
['/activity', () => ({ logs: [], total: 0 })],
];
function renderUserDetail() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
@@ -86,26 +92,20 @@ afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserDetail (przegląd profilu)', () => {
describe('admin UserDetail (konsola użytkownika)', () => {
it('pokazuje badge bana na koncie zablokowanym', async () => {
mockFetchRoutes([
[
'/admin/users',
() => ({ users: [{ ...U1, status: 'BANNED', restrictionReason: 'Powód' }] }),
],
['/killstreak', () => ({ killstreak: 0 })],
['/body-parameters', () => ({ weight: [], circumferences: [] })],
['/history', () => ({ sessions: [] })],
['/claims', () => ({ claims: [] })],
['/exercise-progress', () => ({ exercises: [] })],
['/activity', () => ({ logs: [], total: 0 })],
...BASE_ROUTES,
['/admin/users', () => ({ users: [{ ...U1, status: 'BANNED', restrictionReason: 'Powód' }] })],
]);
renderUserDetail();
expect(await screen.findByText('Zablokowane')).toBeInTheDocument();
expect(screen.getByText('Powód: Powód')).toBeInTheDocument();
});
it('pokazuje badge zawieszenia z terminem', async () => {
mockFetchRoutes([
...BASE_ROUTES,
[
'/admin/users',
() => ({
@@ -119,85 +119,103 @@ describe('admin UserDetail (przegląd profilu)', () => {
],
}),
],
['/killstreak', () => ({ killstreak: 0 })],
['/body-parameters', () => ({ weight: [], circumferences: [] })],
['/history', () => ({ sessions: [] })],
['/claims', () => ({ claims: [] })],
['/exercise-progress', () => ({ exercises: [] })],
['/activity', () => ({ logs: [], total: 0 })],
]);
renderUserDetail();
expect(await screen.findByText(/Zawieszone do/)).toBeInTheDocument();
});
it('renderuje hero, mini-statystyki i wiersze sekcji', async () => {
it('renderuje konsolę: nagłówek h2, panel podsumowania i sekcje bez statystyk treningowych', async () => {
mockFetchRoutes([
['/admin/users', () => ({ users: [U1] })],
['/killstreak', () => ({ killstreak: 7 })],
[
'/body-parameters',
() => ({
weight: [{ id: 'w1', value: 81.5, date: '2026-09-10T10:00:00.000Z' }],
circumferences: [],
}),
],
['/history', () => ({ sessions: [] })],
['/claims', () => ({ claims: [] })],
['/exercise-progress', () => ({ exercises: [{ id: 'e1' }] })],
['/activity', () => ({ logs: [], total: 0 })],
...BASE_ROUTES,
['/claims', () => ({ claims: [{ id: 'c1', gymName: 'Gym B', status: 'PENDING', createdAt: '2026-09-01T10:00:00.000Z', user: { firstName: 'Jan', lastName: 'Kowalski', email: 'jan@test.local' } }] })],
]);
renderUserDetail();
// hero: nazwa + e-mail + nick + rola admina
expect(await screen.findByText('jano')).toBeInTheDocument();
// nagłówek: nazwa (h2) + powrót na listę
expect(await screen.findByRole('heading', { level: 2, name: 'jano' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Wróć' })).toHaveAttribute('href', '/users');
// panel podsumowania: e-mail + nick + badge admina + pasek danych administracyjnych
expect(screen.getByText('jan@test.local')).toBeInTheDocument();
expect(screen.getByText('@jano')).toBeInTheDocument();
expect(screen.getByText('Admin')).toBeInTheDocument();
expect(screen.getByText('Ostatnie logowanie')).toBeInTheDocument();
expect(screen.getByText('Członkostwa')).toBeInTheDocument();
expect(screen.getByText('Konto od')).toBeInTheDocument();
expect(screen.getByText('Utworzony 01.08.2026')).toBeInTheDocument();
// mini-statystyki z endpointów (pasek 3-kaflowy jak w aplikacji — bez „Ostatnia waga")
expect(screen.getByText('Killstreak')).toBeInTheDocument();
expect(screen.getByText('7')).toBeInTheDocument();
expect(screen.getByText('Objętość 7 dni')).toBeInTheDocument();
expect(screen.getByText('Sesje')).toBeInTheDocument();
expect(screen.queryByText('Ostatnia waga')).not.toBeInTheDocument();
// waga pozostaje w podsumowaniu wiersza „Parametry ciała”
expect(screen.getByText('81.5 kg · 10.09.2026')).toBeInTheDocument();
// podsumowanie Postępów = liczba ćwiczeń z endpointu
expect(screen.getByRole('link', { name: /Postępy/ })).toHaveTextContent('1 ćwiczenie');
// wiersze sekcji prowadzące na podstrony
for (const title of [
'Dane osobowe',
'Parametry ciała',
'Historia treningów',
'Postępy',
'Członkostwa w siłowniach',
'Wnioski',
]) {
expect(screen.getByRole('link', { name: new RegExp(title) })).toHaveAttribute(
'href',
`/users/u1/${kebab(title)}`,
);
// statystyki treningowe zniknęły z panelu admina
expect(screen.queryByText('Killstreak')).not.toBeInTheDocument();
expect(screen.queryByText('Objętość 7 dni')).not.toBeInTheDocument();
expect(screen.queryByText('Sesje')).not.toBeInTheDocument();
// brak linków do usuniętych podstron
for (const to of ['info', 'body-parameters', 'history', 'progress', 'memberships', 'claims']) {
expect(screen.queryByRole('link', { name: new RegExp(to, 'i') })).not.toBeInTheDocument();
}
// karta Wnioski: wiersz prowadzi do /verifications/:id ze statusem
const claimLink = screen.getByRole('link', { name: 'Gym B' });
expect(claimLink).toHaveAttribute('href', '/verifications/c1');
expect(claimLink.closest('div')).toHaveTextContent('Oczekuje');
});
it('podsumowanie członkostw pokazuje siłownie i role', async () => {
mockFetchRoutes([
['/admin/users', () => ({ users: [U1] })],
['/killstreak', () => ({ killstreak: 0 })],
['/body-parameters', () => ({ weight: [], circumferences: [] })],
['/history', () => ({ sessions: [] })],
['/claims', () => ({ claims: [] })],
['/exercise-progress', () => ({ exercises: [] })],
['/activity', () => ({ logs: [], total: 0 })],
it('karta członkostw: wiersz otwiera menu i zapis ról wysyła PATCH z pełną listą', async () => {
const calls = mockFetchRoutes([
...BASE_ROUTES,
['/memberships/', () => ({})],
]);
renderUserDetail();
const row = await screen.findByRole('link', { name: /Członkostwa w siłowniach/ });
expect(row).toHaveTextContent('Gym A');
expect(row).toHaveTextContent('OWNER, TRAINER');
// wiersz: siłownia + role jako pigułki (spójne z konsolą siłowni)
const row = await screen.findByText('Gym A');
expect(row.closest('tr')).toHaveTextContent('Warszawa');
expect(row.closest('tr')).toHaveTextContent('Właściciel');
expect(row.closest('tr')).toHaveTextContent('Trener');
fireEvent.click(row.closest('tr') as HTMLElement);
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('Członkostwo: Gym A');
// zmiana: odejmij TRAINER, zostaw OWNER → PATCH pełnej listy
fireEvent.click(within(dialog).getByRole('checkbox', { name: 'Trener — Gym A' }));
fireEvent.click(within(dialog).getByRole('button', { name: 'Zapisz role' }));
await waitFor(() => {
const patch = calls.find((c) => c.init?.method === 'PATCH');
expect(patch?.url).toContain('/admin/users/u1/memberships/g1');
expect(JSON.parse(String(patch?.init?.body))).toEqual({ roles: ['OWNER'] });
});
});
it('kafel historii konta: aktor, akcja, IP logowania i kara z powodem', async () => {
it('karta członkostw: wyrzucenie wymaga powodu i wysyła DELETE z powodem w ciele', async () => {
const calls = mockFetchRoutes([
...BASE_ROUTES,
['/memberships/', () => ({})],
]);
renderUserDetail();
const row = await screen.findByText('Gym A');
fireEvent.click(row.closest('tr') as HTMLElement);
const dialog = await screen.findByRole('dialog');
const removeBtn = within(dialog).getByRole('button', { name: 'Wyrzuć członka' });
expect(removeBtn).toBeDisabled();
fireEvent.change(within(dialog).getByRole('textbox', { name: 'Powód' }), {
target: { value: 'Wielokrotne łamanie regulaminu' },
});
fireEvent.click(removeBtn);
await waitFor(() => {
const del = calls.find((c) => c.init?.method === 'DELETE');
expect(del?.url).toContain('/admin/users/u1/memberships/g1');
expect(JSON.parse(String(del?.init?.body))).toEqual({
reason: 'Wielokrotne łamanie regulaminu',
});
});
});
it('karta logi konta: aktor, akcja, IP logowania i kara z powodem', async () => {
const logs = [
{
id: 'l1',
@@ -220,54 +238,31 @@ describe('admin UserDetail (przegląd profilu)', () => {
];
mockFetchRoutes([
['/admin/users', () => ({ users: [{ ...U1, lastLoginAt: '2026-10-19T18:30:00.000Z' }] })],
['/killstreak', () => ({ killstreak: 0 })],
['/body-parameters', () => ({ weight: [], circumferences: [] })],
['/history', () => ({ sessions: [] })],
['/claims', () => ({ claims: [] })],
['/exercise-progress', () => ({ exercises: [] })],
['/activity', () => ({ logs, total: logs.length })],
]);
renderUserDetail();
// mini-statystyka ostatniego logowania (ten sam dzień występuje też w wierszu logowania)
// komórka ostatniego logowania w panelu podsumowania
expect(await screen.findByText('Ostatnie logowanie')).toBeInTheDocument();
expect(screen.getAllByText(/19\.10\.2026/).length).toBeGreaterThanOrEqual(1);
// historia: kto (aktor-admin) wykonał akcję + szczegóły kary
expect(screen.getByText('Historia konta')).toBeInTheDocument();
// logi: kto (aktor-admin) wykonał akcję + szczegóły kary + IP logowania
expect(screen.getByText('Logi konta')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Wszystkie logi' })).toHaveAttribute(
'href',
'/users/u1/logs',
);
expect(screen.getByText('przez Ada Admin')).toBeInTheDocument();
expect(screen.getByText('Zmiana statusu konta')).toBeInTheDocument();
expect(screen.getByText(/powód kary: Sprzedaż kont/)).toBeInTheDocument();
// logowanie z adresem IP
expect(screen.getByText('Logowanie')).toBeInTheDocument();
expect(screen.getByText(/adres IP: 203\.0\.113\.9/)).toBeInTheDocument();
});
it('kafel historii konta: stan pusty', async () => {
mockFetchRoutes([
['/admin/users', () => ({ users: [U1] })],
['/killstreak', () => ({ killstreak: 0 })],
['/body-parameters', () => ({ weight: [], circumferences: [] })],
['/history', () => ({ sessions: [] })],
['/claims', () => ({ claims: [] })],
['/exercise-progress', () => ({ exercises: [] })],
['/activity', () => ({ logs: [], total: 0 })],
]);
it('karta logi konta: stan pusty', async () => {
mockFetchRoutes(BASE_ROUTES);
renderUserDetail();
expect(await screen.findByText('Historia konta')).toBeInTheDocument();
expect(await screen.findByText('Logi konta')).toBeInTheDocument();
expect(screen.getByText('Brak zdarzeń konta.')).toBeInTheDocument();
});
});
// tytuł sekcji → memberships | claims | info | body-parameters | history | progress
function kebab(title: string): string {
const map: Record<string, string> = {
'Dane osobowe': 'info',
'Parametry ciała': 'body-parameters',
'Historia treningów': 'history',
Postępy: 'progress',
'Członkostwa w siłowniach': 'memberships',
Wnioski: 'claims',
};
return map[title];
}

View File

@@ -1,160 +0,0 @@
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserInfo from '../src/pages/users/UserInfo';
import { setAccessToken } from '../src/api/client';
import type { FocusArea, User } from '../src/api/types';
const AREAS: FocusArea[] = [
{
id: 'fa-1',
name: 'Klatka piersiowa',
muscle: 'chest',
description: null,
exercisesCount: 0,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'fa-2',
name: 'Nogi',
muscle: 'legs',
description: null,
exercisesCount: 0,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
];
const CHAIN = {
develop: [
{ muscle: 'chest', name: 'Klatka piersiowa', exercises: [{ id: 'pz-1', name: 'Wyciskanie' }] },
],
canDo: [],
difficult: [],
avoid: [],
};
const U1: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: 'jano',
socialMedia: [{ platform: 'INSTAGRAM', url: 'https://instagram.com/jano' }],
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: '+48 500 100 200',
isAdmin: true,
availability: [
{ start: '18:00', end: '20:00' },
{ start: '18:00', end: '20:00' },
{ start: '18:00', end: '20:00' },
null,
null,
null,
null,
] as User['availability'],
priorities: null,
exclusions: null,
developMuscles: ['chest'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: ['legs'],
status: 'ACTIVE',
suspensionUntil: null,
restrictionReason: null,
createdAt: '2026-08-01T10:00:00.000Z',
memberships: [],
};
/** Mock fetch wg fragmentu URL (odwrócona kolejność = specyficzne trasy wygrywają). */
function mockFetchRoutes(routes: Array<[string, () => unknown]>) {
const calls: { url: string; init?: RequestInit }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
calls.push({ url, init });
const entry = [...routes].reverse().find(([frag]) => url.includes(frag));
if (!entry) throw new Error(`No mocked route for url: ${url}`);
return new Response(JSON.stringify(entry[1]()), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
function renderUserInfo() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/users/u1/info']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/users/:id/info" element={<UserInfo />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
function defaultRoutes() {
return mockFetchRoutes([
['/admin/users', () => ({ users: [U1] })],
['/focus-areas', () => ({ focusAreas: AREAS })],
['/focus-chain', () => CHAIN],
]);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserInfo page', () => {
it('renderuje karty konta, danych, priorytetów i social media', async () => {
defaultRoutes();
renderUserInfo();
expect(
await screen.findByRole('heading', { name: 'Dane osobowe', level: 2 }),
).toBeInTheDocument();
// karta „Konto” (dodatek admina) + dane adresowe
expect(screen.getByText('Konto')).toBeInTheDocument();
expect(screen.getByText('jan@test.local')).toBeInTheDocument();
expect(screen.getByText('30 lat')).toBeInTheDocument();
expect(screen.getByText('180 cm')).toBeInTheDocument();
expect(screen.getByText('+48 500 100 200')).toBeInTheDocument();
// dostępność jako chipy z pogrupowanymi dniami (jak w aplikacji)
expect(screen.getByText('Pon–Śr 18:00–20:00')).toBeInTheDocument();
// priorytety: nazwy mięśni rozwinięte z listy obszarów
expect(screen.getAllByText('Co rozwija').length).toBeGreaterThan(0);
expect(screen.getAllByText('Klatka piersiowa').length).toBeGreaterThan(0);
expect(screen.getAllByText('Co unikać').length).toBeGreaterThan(0);
expect(screen.getByText('Nogi')).toBeInTheDocument();
// social media jako link
const ig = screen.getByRole('link', { name: 'Instagram' });
expect(ig).toHaveAttribute('href', 'https://instagram.com/jano');
// ciąg przyczynowo-skutkowy z endpointu
expect(screen.getByText('Ciąg przyczynowo-skutkowy')).toBeInTheDocument();
expect(await screen.findByText('do rozwoju: Wyciskanie')).toBeInTheDocument();
});
it('jest wyłącznie do odczytu — brak kontrolek edycji', async () => {
defaultRoutes();
renderUserInfo();
await screen.findByRole('heading', { name: 'Dane osobowe', level: 2 });
expect(screen.queryAllByRole('button', { name: 'Edytuj' })).toHaveLength(0);
expect(screen.queryByRole('button', { name: 'Zapisz' })).not.toBeInTheDocument();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,120 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserLogsPage from '../src/pages/users/UserLogsPage';
import { setAccessToken } from '../src/api/client';
import type { ActivityLog, User } from '../src/api/types';
const U1: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: 'jano',
socialMedia: null,
birthDate: null,
heightCm: null,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
status: 'ACTIVE',
suspensionUntil: null,
restrictionReason: null,
createdAt: '2026-08-01T10:00:00.000Z',
};
const LOG1: ActivityLog = {
id: 'log-1',
action: 'user.logged_in',
entityType: 'user',
entityId: 'u1',
details: { actorId: 'u1', client: 'app', ip: '203.0.113.9' },
createdAt: '2026-10-19T18:30:00.000Z',
actor: { id: 'u1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' },
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function renderPage() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/users/u1/logs']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/users/:id/logs" element={<UserLogsPage />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserLogsPage', () => {
it('renderuje wspólną tabelę logów na koncie (IP w szczegółach)', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/activity')) {
return jsonResponse(200, { logs: [LOG1], total: 1 });
}
return jsonResponse(200, { users: [U1] });
}),
);
renderPage();
expect(await screen.findByText('Logowanie')).toBeInTheDocument();
expect(await screen.findByText('adres IP: 203.0.113.9')).toBeInTheDocument();
// powrót do konsoli użytkownika
expect(screen.getByRole('link', { name: /Wstecz/ })).toHaveAttribute('href', '/users/u1');
});
it('pusty stan, gdy brak zdarzeń na koncie', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/activity')) return jsonResponse(200, { logs: [], total: 0 });
return jsonResponse(200, { users: [U1] });
}),
);
renderPage();
expect(await screen.findByText('Brak zdarzeń audytu na tym koncie.')).toBeInTheDocument();
});
it('„Pokaż kolejne” dokłada limit i odpytuje API', async () => {
const urls: string[] = [];
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
urls.push(url);
if (url.includes('/activity')) return jsonResponse(200, { logs: [LOG1], total: 60 });
return jsonResponse(200, { users: [U1] });
}),
);
const user = userEvent.setup();
renderPage();
await user.click(await screen.findByRole('button', { name: 'Pokaż kolejne 59' }));
await vi.waitFor(() => expect(urls.some((u) => u.includes('limit=100'))).toBe(true));
});
});

View File

@@ -1,110 +0,0 @@
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserMemberships from '../src/pages/users/UserMemberships';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import type { Gym, User } from '../src/api/types';
const G1: Gym = {
id: 'g1',
name: 'Gym A',
location: 'Warszawa',
availability: null,
capacity: 50,
equipment: [],
_count: { memberships: 1 },
};
const U1: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
socialMedia: null,
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
status: 'ACTIVE',
suspensionUntil: null,
restrictionReason: null,
createdAt: '2026-08-01T10:00:00.000Z',
memberships: [{ gymId: 'g1', roles: ['OWNER', 'TRAINER'], gym: G1 }],
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockFetchSequence(...responses: Response[]) {
const fetchMock = vi.fn(async (url: string) => {
const next = responses.shift();
if (!next) throw new Error(`No more mocked responses for url: ${url}`);
return next;
});
vi.stubGlobal('fetch', fetchMock);
}
function renderMemberships(path: string) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={[path]}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/users/:id/memberships" element={<UserMemberships />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserMemberships page (tylko do odczytu)', () => {
it('lists memberships with role badges and no editing controls', async () => {
mockFetchSequence(jsonResponse(200, { users: [U1] }));
renderMemberships('/users/u1/memberships');
expect(
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }),
).toBeInTheDocument();
expect(screen.getByText('Gym A')).toBeInTheDocument();
expect(screen.getByText('Warszawa')).toBeInTheDocument();
expect(screen.getByText('Właściciel')).toBeInTheDocument();
expect(screen.getByText('Trener')).toBeInTheDocument();
// read-only: brak kontrolek edycji (role są badge'ami, nie checkboxami)
expect(screen.queryAllByRole('checkbox')).toHaveLength(0);
expect(screen.queryByRole('button', { name: 'Usuń' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Dodaj członkostwo' })).not.toBeInTheDocument();
// i w konfiguracji topbara żadnej akcji
expect(useTopbarStore.getState().config?.actions ?? []).toHaveLength(0);
});
it('shows an empty state when the user has no memberships', async () => {
mockFetchSequence(jsonResponse(200, { users: [{ ...U1, memberships: [] }] }));
renderMemberships('/users/u1/memberships');
expect(
await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }),
).toBeInTheDocument();
expect(screen.getByText('Brak członkostw.')).toBeInTheDocument();
});
});

View File

@@ -151,47 +151,56 @@ test('wyrzucenie członka z siłowni — wymagalny powód i DELETE z powodem w c
await expect(page.locator('tr', { hasText: 'Jan Kowalski' })).toHaveCount(0);
});
test('kliknięcie w użytkownika otwiera przegląd profilu (wzór z apki)', async ({ page }) => {
test('kliknięcie w użytkownika otwiera konsolę administracyjną', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await expect(page).toHaveURL(/\/users\/user-1$/);
// hero: e-mail + mini-statystyki (pasek 3-kaflowy jak w apce) + wiersze sekcji
// topbar = kategoria „Użytkownik”, nazwa dopiero w treści (h2) + „← Wróć”
await expect(page.getByRole('heading', { level: 1, name: 'Użytkownik' })).toBeVisible();
await expect(page.getByRole('heading', { level: 2, name: 'Jan Kowalski' })).toBeVisible();
// panel podsumowania: e-mail + pasek danych administracyjnych
await expect(page.getByText('jan@fitos.pl')).toBeVisible();
await expect(page.getByText('Killstreak')).toBeVisible();
await expect(page.getByText('Objętość 7 dni')).toBeVisible();
await expect(page.getByText('Sesje')).toBeVisible();
await expect(page.getByText('Ostatnia waga')).toHaveCount(0);
// waga pozostaje w podsumowaniu wiersza „Parametry ciała”
await expect(page.getByText('81.5 kg ·')).toBeVisible();
await expect(page.getByRole('link', { name: /Dane osobowe/ })).toBeVisible();
await expect(page.getByRole('link', { name: /Parametry ciała/ })).toBeVisible();
await expect(page.getByRole('link', { name: /Historia treningów/ })).toBeVisible();
await expect(page.getByRole('link', { name: /Postępy/ })).toBeVisible();
await expect(page.getByText('Ostatnie logowanie')).toBeVisible();
await expect(page.getByText('Członkostwa', { exact: true })).toBeVisible();
await expect(page.getByText('Konto od')).toBeVisible();
// statystyki treningowe i podstrony profilu apki poza zakresem admina
await expect(page.getByText('Killstreak')).toHaveCount(0);
await expect(page.getByText('Objętość 7 dni')).toHaveCount(0);
await expect(page.getByRole('link', { name: /Parametry ciała/ })).toHaveCount(0);
await expect(page.getByRole('link', { name: /Historia treningów/ })).toHaveCount(0);
// karta członkostw: wiersz z siłownią i rolą jako badge
await expect(page.getByRole('heading', { level: 3, name: /Członkostwa w siłowniach/ })).toBeVisible();
await expect(page.locator('tr', { hasText: 'Fit Factory' })).toBeVisible();
// (exact: „Admin · Ćwiczący” w stopce sidebaru też zawiera ten tekst)
await expect(page.getByText('Ćwiczący', { exact: true })).toBeVisible();
// w edycji konkretnego usera menu kontekstowe nie ma akcji „Nowy użytkownik” (brak ikony ➕)
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
});
test('strona członkostw jest tylko do odczytu — role jako badge, brak kontrolek edycji', async ({
test('edycja członkostwa z karty w profilu — klik w wiersz otwiera menu, zapis wysyła PATCH', async ({
page,
}) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await page.getByRole('link', { name: /Członkostwa w siłowniach/ }).click();
await expect(page).toHaveURL(/\/users\/user-1\/memberships$/);
// dane widoczne (nazwa siłowni + rola jako badge), ale żadnej kontroki edycji —
// jedyne miejsce zmiany członkostw to kreator edycji
await expect(page.getByText('Fit Factory')).toBeVisible();
// (exact: „Admin · Ćwiczący” w stopce sidebaru też zawiera ten tekst)
await expect(page.getByText('Ćwiczący', { exact: true })).toBeVisible();
await expect(page.getByRole('checkbox')).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Dodaj członkostwo' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Usuń', exact: true })).toHaveCount(0);
await expect(page.getByRole('heading', { level: 1 })).toHaveCount(1);
// klik w wiersz siłowni = menu członkostwa (jak w konsoli siłowni; bez linku do własnego profilu)
await page.locator('tr', { hasText: 'Fit Factory' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog.getByText('Członkostwo: Fit Factory')).toBeVisible();
await expect(dialog.getByRole('link', { name: 'Otwórz profil w panelu' })).toHaveCount(0);
// do pełnej listy MEMBER dopisujemy OWNER → PATCH z pełną listą
await dialog.getByRole('checkbox', { name: 'Właściciel — Fit Factory' }).click();
const patchReq = page.waitForRequest(
(req) =>
req.url().includes('/admin/users/user-1/memberships/gym-1') && req.method() === 'PATCH',
);
await dialog.getByRole('button', { name: 'Zapisz role' }).click();
expect((await patchReq).postDataJSON()).toEqual({ roles: ['MEMBER', 'OWNER'] });
});
test('zmiana roli członkostwa w kreatorze edycji — zapis wysyła PATCH z pełną listą', async ({
@@ -320,61 +329,47 @@ test('konto zbanowane — badge widoczny na liście i w szczegółach', async ({
await expect(page.getByText('Zablokowane')).toBeVisible();
});
test('zakładka danych osobowych jest tylko do odczytu (brak kontrolek edycji)', async ({
test('logi konta: akcja w topbarze otwiera podstronę — topbar = kategoria, w treści nazwa usera', async ({
page,
}) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
mockApi(page, {
gyms: { gyms: [TEST_GYM] },
users: { users: [TEST_USER] },
activity: {
logs: [
{
id: 'a-2',
action: 'user.logged_in',
entityType: 'user',
entityId: 'user-1',
details: { actorId: 'user-1', ip: '203.0.113.9' },
createdAt: '2026-10-19T18:30:00.000Z',
actor: { id: 'user-1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
},
],
total: 1,
},
});
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await page.getByRole('link', { name: /Dane osobowe/ }).click();
await expect(page).toHaveURL(/\/users\/user-1\/info$/);
// podgląd konta i danych — bez modali; edycja wyłącznie w wizardzie
await expect(page.getByText('Utworzony')).toBeVisible();
await expect(page.getByText(TEST_USER.email)).toBeVisible();
await expect(page.getByRole('button', { name: 'Edytuj' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Zapisz' })).toHaveCount(0);
// nawigacja do pełnych logów = akcja w topbarze (bez akcji w treści)
await page.getByRole('button', { name: 'Logi' }).click();
await expect(page).toHaveURL(/\/users\/user-1\/logs$/);
// topbar = kategoria „Logi użytkownika”, nazwa usera dopiero w treści (hero-lite, bez dubla <h1>)
await expect(page.getByRole('heading', { level: 1, name: 'Logi użytkownika' })).toBeVisible();
await expect(page.getByText('Zdarzenia audytu wykonane na tym koncie.')).toBeVisible();
// LogTable: akcja + szczegóły (adres IP)
await expect(page.getByText('Logowanie')).toBeVisible();
await expect(page.getByText('adres IP: 203.0.113.9')).toBeVisible();
// powrót do konsoli — link „Wstecz” (BackButton)
await page.getByRole('link', { name: 'Wstecz' }).click();
await expect(page).toHaveURL(/\/users\/user-1$/);
});
test('parametry ciała tylko do odczytu — brak kontrolek dodawania/usuwania pomiarów', async ({
page,
}) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await page.getByRole('link', { name: /Parametry ciała/ }).click();
await expect(page).toHaveURL(/\/users\/user-1\/body-parameters$/);
// dane widoczne, edycji brak (pomiary to domena aplikacji usera)
await expect(page.getByText('81.5 kg', { exact: true }).first()).toBeVisible();
await expect(page.getByRole('button', { name: 'Dodaj pomiar' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Dodaj wagę' })).toHaveCount(0);
await expect(page.getByRole('button', { name: '+ Waga' })).toHaveCount(0);
// koniec z dublem <h1>: topbar = jedyny <h1>, nagłówek treści to <h2>
await expect(page.getByRole('heading', { level: 1 })).toHaveCount(1);
await expect(page.getByRole('heading', { level: 2, name: 'Parametry ciała' })).toBeVisible();
});
test('podstrony usera: topbar = Profil [nazwa], nazwa sekcji dopiero w treści (bez dubla)', async ({
page,
}) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await page.getByRole('link', { name: /Historia treningów/ }).click();
await expect(page).toHaveURL(/\/users\/user-1\/history$/);
// topbar pokazuje rodzica z nazwą usera, a pod nim dopiero nazwę sekcji
await expect(page.getByRole('heading', { level: 1, name: 'Profil Jan Kowalski' })).toBeVisible();
await expect(page.getByRole('heading', { level: 2, name: 'Historia treningów' })).toBeVisible();
// ten sam tekst nie może dublować się w dwóch nagłówkach
await expect(page.getByRole('heading', { name: 'Historia treningów' })).toHaveCount(1);
});
test('historia konta: ostatnie logowanie, IP i kara z aktorem-adminem', async ({ page }) => {
test('logi konta w konsoli: ostatnie logowanie, IP i kara z aktorem-adminem', async ({ page }) => {
mockApi(page, {
gyms: { gyms: [TEST_GYM] },
users: {
@@ -410,9 +405,10 @@ test('historia konta: ostatnie logowanie, IP i kara z aktorem-adminem', async ({
await expect(page.getByText(/log: 19\.10\.2026/)).toBeVisible();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
// mini-statystyka + kafel historii
// pasek danych administracyjnych + karta ostatnich logów (link do pełnej podstrony)
await expect(page.getByText('Ostatnie logowanie')).toBeVisible();
await expect(page.getByText('Historia konta')).toBeVisible();
await expect(page.getByRole('heading', { level: 3, name: 'Logi konta' })).toBeVisible();
await expect(page.getByRole('link', { name: 'Wszystkie logi' })).toBeVisible();
await expect(page.getByText('przez Admin FitOS')).toBeVisible();
await expect(page.getByText(/powód kary: Sprzedaż kont/)).toBeVisible();
await expect(page.getByText(/adres IP: 203\.0\.113\.9/)).toBeVisible();
@@ -423,9 +419,9 @@ test('kreator edycji: zapis bez zmian członkostw wysyła tylko PATCH konta', as
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
// podział ról: akcja (Edytuj) w menu, nawigacja do podstron w treści
// podział ról: akcje (Edytuj, Logi) w topbarze; treść służy tylko danym
await expect(page.getByRole('button', { name: 'Edytuj' })).toBeVisible();
await expect(page.getByRole('link', { name: /Dane osobowe/ })).toBeVisible();
await expect(page.getByRole('button', { name: 'Logi' })).toBeVisible();
await page.getByRole('button', { name: 'Edytuj' }).click();
await expect(page).toHaveURL(/\/users\/user-1\/edit$/);
await expect(page.getByRole('heading', { name: 'Edycja użytkownika' })).toBeVisible();

View File

@@ -284,15 +284,6 @@ export const TEST_FOCUS_AREAS = [
},
];
export const TEST_FOCUS_CHAIN = {
develop: [
{ muscle: 'chest', name: 'Klatka piersiowa', exercises: [{ id: 'pz-2', name: 'Wyciskanie' }] },
],
canDo: [],
difficult: [],
avoid: [{ muscle: 'legs', name: 'Nogi', exercises: [{ id: 'pz-1', name: 'Przysiady' }] }],
};
export const TEST_LOGS: ActivityLog[] = [
{
id: 'log-1',
@@ -780,23 +771,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
}),
);
page.route('**/api/v1/admin/users/*/focus-chain', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_FOCUS_CHAIN),
}),
);
// Dane treningowe użytkownika (podstrony profilu admina).
page.route('**/api/v1/admin/users/*/killstreak', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ killstreak: 3 }),
}),
);
// Logi audytu na koncie (karta w konsoli + podstrona /users/:id/logs).
page.route('**/api/v1/admin/users/*/activity*', (route) =>
route.fulfill({
status: 200,
@@ -805,44 +780,6 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
}),
);
page.route('**/api/v1/admin/users/*/history', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ sessions: [] }),
}),
);
page.route('**/api/v1/admin/users/*/exercise-progress', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ exercises: [] }),
}),
);
page.route('**/api/v1/admin/users/*/body-parameters/*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'm-1', value: 80, date: '2026-09-01T10:00:00.000Z' }),
}),
);
page.route('**/api/v1/admin/users/*/body-parameters', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
weight: [
{ id: 'w-1', value: 81.5, date: '2026-09-10T10:00:00.000Z' },
{ id: 'w-2', value: 82.0, date: '2026-09-01T10:00:00.000Z' },
],
circumferences: [],
}),
}),
);
// PATCH ról / DELETE członkostwa (menu członka w konsoli siłowni) — stanowo (membersState).
page.route('**/api/v1/admin/users/*/memberships/*', (route) => {
const req = route.request();