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

@@ -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({