Admin: parametry cial usera tylko do odczytu (bez dodawania/usuwania pomiarow, + komunikat bledu zapytania)

This commit is contained in:
tisachi
2026-10-16 23:33:17 +02:00
parent 930a54c003
commit b9aa738e1f
2 changed files with 191 additions and 543 deletions

View File

@@ -1,7 +1,6 @@
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { useEffect, useState, type ReactNode } from 'react';
import { useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { ChevronDown, Plus, Ruler, Scale, Trash2, type LucideIcon } from 'lucide-react';
import { ChevronDown, Ruler, Scale, type LucideIcon } from 'lucide-react';
import {
LineChart,
Line,
@@ -13,30 +12,21 @@ import {
} from 'recharts';
import { useTopbar } from '../../topbar';
import { MonthPicker } from '../../topbar/MonthPicker';
import { api } from '../../api/client';
import {
BackButton,
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
H3,
Input,
Modal,
PageHeader,
Select,
Skeleton,
Tabs,
} from '../../components/ui';
import {
MEASUREMENT_TYPES,
SIDE_LABELS,
bodyPartOf,
detectBodyPart,
measurementType,
measurementName,
sideOf,
type Side,
} from '../../lib/body-measurements';
@@ -101,18 +91,16 @@ function mergedSideData(series: CircumferenceSeries[]) {
}));
}
/* Karta pomiaru: nagłówek (ikona + H3 + najnowszy pomiar + akcje) + treść (wykres + lista). */
/* Karta pomiaru: nagłówek (ikona + H3 + najnowszy pomiar) + treść (wykres + lista). */
function MeasurementCard({
icon: Icon,
title,
latest,
actions,
children,
}: {
icon: LucideIcon;
title: string;
latest?: ReactNode;
actions?: ReactNode;
children: ReactNode;
}) {
return (
@@ -124,10 +112,7 @@ function MeasurementCard({
</span>
<H3 className="mb-0">{title}</H3>
</div>
<div className="flex flex-wrap items-center gap-2">
{latest}
{actions}
</div>
<div className="flex flex-wrap items-center gap-2">{latest}</div>
</div>
{children}
</Card>
@@ -136,24 +121,19 @@ function MeasurementCard({
interface MeasurementPoint {
id: string;
kind: 'weight' | 'circumference';
label: string;
meta: string;
deleteLabel: string;
removeLabel: string;
}
/* Lista pomiarów: najnowsze N + „Pokaż więcej"; wiersz = wartość + data (+ strona) + usuń. */
/* Lista pomiarów: najnowsze N + „Pokaż więcej"; wiersz = wartość + data (+ strona). */
function MeasurementList({
points,
visible,
onShowMore,
onDelete,
}: {
points: MeasurementPoint[];
visible: number;
onShowMore: () => void;
onDelete: (target: { kind: 'weight' | 'circumference'; id: string; label: string }) => void;
}) {
if (points.length === 0) return null;
return (
@@ -165,20 +145,8 @@ function MeasurementList({
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"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<strong className="text-ink">{p.label}</strong>
<div className="mt-0.5 text-[0.875rem] text-dim">{p.meta}</div>
</div>
<button
type="button"
aria-label={p.deleteLabel}
onClick={() => onDelete({ kind: p.kind, id: p.id, label: p.removeLabel })}
className="p-1.5 -m-1.5 text-dim hover:text-danger cursor-pointer shrink-0"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
<strong className="text-ink">{p.label}</strong>
<div className="mt-0.5 text-[0.875rem] text-dim">{p.meta}</div>
</li>
))}
</ul>
@@ -192,176 +160,19 @@ function MeasurementList({
);
}
/* Modal „Dodaj pomiar": zakładki Waga/Obwód + 2 formularze (stan na stronie). */
function AddMeasurementModal({
open,
onClose,
tab,
onTabChange,
weight,
onWeightChange,
weightDate,
onWeightDateChange,
circType,
onCircTypeChange,
circSide,
onCircSideChange,
circValue,
onCircValueChange,
circDate,
onCircDateChange,
busy,
error,
onSaveWeight,
onSaveCirc,
}: {
open: boolean;
onClose: () => void;
tab: 'weight' | 'circ';
onTabChange: (tab: 'weight' | 'circ') => void;
weight: string;
onWeightChange: (v: string) => void;
weightDate: string;
onWeightDateChange: (v: string) => void;
circType: string;
onCircTypeChange: (v: string) => void;
circSide: Side;
onCircSideChange: (s: Side) => void;
circValue: string;
onCircValueChange: (v: string) => void;
circDate: string;
onCircDateChange: (v: string) => void;
busy: boolean;
error: string;
onSaveWeight: (e: React.FormEvent) => void;
onSaveCirc: (e: React.FormEvent) => void;
}) {
return (
<Modal open={open} onClose={onClose} title="Dodaj pomiar">
<Tabs
tabs={[
{ id: 'weight', label: 'Waga' },
{ id: 'circ', label: 'Obwód' },
]}
active={tab}
onChange={(id) => onTabChange(id === 'circ' ? 'circ' : 'weight')}
/>
{error && <ErrorText>{error}</ErrorText>}
{tab === 'weight' ? (
<form onSubmit={onSaveWeight} className="flex flex-col gap-3 mt-4">
<Input
type="number"
step="0.1"
placeholder="waga (kg)"
value={weight}
onChange={(e) => onWeightChange(e.target.value)}
/>
<Field label="Data">
<Input
type="date"
value={weightDate}
onChange={(e) => onWeightDateChange(e.target.value)}
aria-label="Data wagi"
/>
</Field>
<Button type="submit" disabled={busy}>
<Plus className="w-4 h-4" />
Dodaj wagę
</Button>
</form>
) : (
<form onSubmit={onSaveCirc} className="flex flex-col gap-3 mt-4">
<Select
aria-label="Rodzaj pomiaru"
value={circType}
onChange={(e) => onCircTypeChange(e.target.value)}
>
{MEASUREMENT_TYPES.map((t) => (
<option key={t.id} value={t.id}>
{t.label}
</option>
))}
</Select>
{measurementType(circType)?.sided && (
<div
className="inline-flex self-start overflow-hidden rounded-xl border border-line bg-input"
role="group"
aria-label="Strona"
>
{(['left', 'right'] as Side[]).map((s) => (
<button
key={s}
type="button"
aria-pressed={circSide === s}
onClick={() => onCircSideChange(s)}
className={`px-3 py-2.5 text-[0.95rem] cursor-pointer transition-colors ${
circSide === s
? 'bg-accent/15 font-semibold text-accent-text'
: 'text-dim hover:text-ink'
}`}
>
{SIDE_LABELS[s]}
</button>
))}
</div>
)}
<Input
type="number"
step="0.1"
placeholder="wartość (cm)"
value={circValue}
onChange={(e) => onCircValueChange(e.target.value)}
/>
<Field label="Data">
<Input
type="date"
value={circDate}
onChange={(e) => onCircDateChange(e.target.value)}
aria-label="Data obwodu"
/>
</Field>
<Button type="submit" disabled={busy}>
<Plus className="w-4 h-4" />
Dodaj obwód
</Button>
</form>
)}
</Modal>
);
}
/**
* Parametry ciała użytkownika (admin): wykresy + lista pomiarów z edycją
* (dodawanie/usuwanie w imieniu użytkownika). Układ wzorowany na `/profile/body-parameters`.
* Parametry ciała użytkownika (admin) — tylko do odczytu: wykresy i listy pomiarów.
* Pomiary (waga, obwody) są w domenie read-only obok profilu — dodaje je wyłącznie
* użytkownik w aplikacji. Układ wzorowany na `/profile/body-parameters`.
*/
export default function UserBodyParameters() {
const { id } = useParams();
const queryClient = useQueryClient();
const { data: bp, isLoading: bpLoading } = useUserBodyParameters(id);
const { data: bp, isLoading: bpLoading, error: bpError } = useUserBodyParameters(id);
const today = () => new Date().toISOString().slice(0, 10);
const [weight, setWeight] = useState('');
const [weightDate, setWeightDate] = useState(today);
const [circType, setCircType] = useState(MEASUREMENT_TYPES[0].id);
const [circSide, setCircSide] = useState<Side>('left');
const [circValue, setCircValue] = useState('');
const [circDate, setCircDate] = useState(today);
const [removeTarget, setRemoveTarget] = useState<null | {
kind: 'weight' | 'circumference';
id: string;
label: string;
}>(null);
const [removeBusy, setRemoveBusy] = useState(false);
const [addOpen, setAddOpen] = useState(false);
const [addTab, setAddTab] = useState<'weight' | 'circ'>('weight');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [visible, setVisible] = useState<Record<string, number>>({});
// miesiąc w topmenu: '' = wszystkie; dostępność i lata liczone z danych
const [month, setMonth] = useState('');
const refresh = () => queryClient.invalidateQueries({ queryKey: ['user-body-parameters', id] });
// miesiące z danymi (nowe → stare) — do selektora w topmenu
const monthKeys = [
...(bp?.weight ?? []).map((w) => w.date.slice(0, 7)),
@@ -378,7 +189,6 @@ export default function UserBodyParameters() {
back: id ? `/users/${id}` : '/users',
dateFilter: <MonthPicker value={month} onChange={setMonth} years={monthYears} />,
filterActive: month !== '',
actions: [{ label: 'Dodaj pomiar', onClick: () => setAddOpen(true), icon: Plus }],
});
// lista: 3 najnowsze + „Pokaż więcej" (kolejne 3); zmiana miesiąca resetuje
@@ -393,76 +203,6 @@ export default function UserBodyParameters() {
}
}, [availableMonths.join(','), month]);
const savingRef = useRef(false);
const saveWeight = async (e: React.FormEvent) => {
e.preventDefault();
if (!weight || savingRef.current) return;
savingRef.current = true;
setBusy(true);
setError('');
try {
await api(`/admin/users/${id}/body-parameters/weight`, {
method: 'POST',
body: {
value: parseFloat(weight),
...(weightDate ? { date: new Date(weightDate).toISOString() } : {}),
},
});
setWeight('');
setWeightDate(today());
setAddOpen(false);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd zapisu');
} finally {
savingRef.current = false;
setBusy(false);
}
};
const saveCirc = async (e: React.FormEvent) => {
e.preventDefault();
if (!circValue || savingRef.current) return;
savingRef.current = true;
setBusy(true);
setError('');
try {
await api(`/admin/users/${id}/body-parameters/circumference`, {
method: 'POST',
body: {
name: measurementName(circType, circSide),
value: parseFloat(circValue),
...(circDate ? { date: new Date(circDate).toISOString() } : {}),
},
});
setCircValue('');
setCircDate(today());
setAddOpen(false);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd zapisu');
} finally {
savingRef.current = false;
setBusy(false);
}
};
const confirmRemove = async () => {
if (!removeTarget) return;
const { kind, id: pointId } = removeTarget;
setRemoveTarget(null);
setRemoveBusy(true);
try {
await api(`/admin/users/${id}/body-parameters/${kind}/${pointId}`, { method: 'DELETE' });
await refresh();
} catch (e) {
setError(e instanceof Error ? e.message : 'Błąd');
} finally {
setRemoveBusy(false);
}
};
// zakres: wybrany w topmenu miesiąc (YYYY-MM)
const inMonth = (date: string) => month === '' || date.startsWith(month);
@@ -507,179 +247,47 @@ export default function UserBodyParameters() {
actions={<BackButton to={id ? `/users/${id}` : '/users'} />}
/>
<MeasurementCard
icon={Scale}
title="Waga"
latest={
latestWeight && (
<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">
{latestWeight.value} kg
</span>
<span className="text-[0.75rem] text-dim">· {fmtDate(latestWeight.date)}</span>
</span>
{weightDelta != null && weightDelta !== 0 && (
<span
className={`text-[0.75rem] font-semibold ${
weightDelta < 0 ? 'text-accent-text' : 'text-warn'
}`}
>
{weightDelta < 0 ? '−' : '+'}
{Math.abs(weightDelta).toLocaleString('pl-PL')} kg w tym miesiącu
</span>
)}
</span>
)
}
actions={
<Button
size="sm"
variant="secondary"
onClick={() => {
setAddTab('weight');
setError('');
setAddOpen(true);
}}
>
<Plus className="w-4 h-4" />+ Waga
</Button>
}
>
{weightPoints.length === 0 ? (
<EmptyState
icon={Scale}
title="Brak pomiarów wagi"
description="Dodaj pomiar wagi w imieniu użytkownika, aby śledzić postęp."
action={
<Button
size="sm"
onClick={() => {
setAddTab('weight');
setError('');
setAddOpen(true);
}}
>
<Plus className="w-4 h-4" />
Dodaj wagę
</Button>
}
/>
) : (
<>
{weightData.length >= 2 ? (
<ResponsiveContainer width="100%" height={220}>
<LineChart data={weightData}>
<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="value"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
) : (
<p className="text-dim">Za mało danych na wykres (min. 2 pomiary).</p>
)}
<MeasurementList
points={[...weightPoints].reverse().map((p) => ({
id: p.id,
kind: 'weight' as const,
label: `${p.value} kg`,
meta: fmtDate(p.date),
deleteLabel: `Usuń pomiar wagi z ${fmtDate(p.date)}`,
removeLabel: `waga ${p.value} kg (${fmtDate(p.date)})`,
}))}
visible={countFor('weight')}
onShowMore={() => showMore('weight')}
onDelete={setRemoveTarget}
/>
</>
)}
</MeasurementCard>
{circGroups.length === 0 && (
<MeasurementCard icon={Ruler} title="Obwody">
<p className="text-dim">Brak pomiarów{month ? ' w wybranym miesiącu' : ''}.</p>
</MeasurementCard>
)}
{circGroups.map((g) => {
const allPoints = g.series.flatMap((s) =>
s.points.map((p) => ({ ...p, name: s.name, side: sideOf(s.name) })),
);
const latest = allPoints.reduce<(typeof allPoints)[number] | null>(
(max, p) => (max == null || p.date > max.date ? p : max),
null,
);
const sided = g.series.some((s) => sideOf(s.name) != null);
const sidesPresent = [
...new Set(g.series.map((s) => sideOf(s.name)).filter((s): s is Side => s != null)),
];
const sideData = mergedSideData(g.series);
const chartReady = sided ? sideData.length >= 2 : g.series[0].points.length >= 2;
return (
{bpError ? (
<ErrorText>Błąd: {(bpError as Error).message}</ErrorText>
) : (
<>
<MeasurementCard
key={g.part}
icon={Ruler}
title={g.part}
icon={Scale}
title="Waga"
latest={
latest && (
<span className="flex items-baseline gap-2">
<span className="font-display text-[1.35rem] font-bold leading-none tabular-nums">
{latest.value} cm
</span>
<span className="text-[0.75rem] text-dim">
{latest.side ? `${SIDE_LABELS[latest.side]} · ` : '· '}
{fmtDate(latest.date)}
latestWeight && (
<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">
{latestWeight.value} kg
</span>
<span className="text-[0.75rem] text-dim">· {fmtDate(latestWeight.date)}</span>
</span>
{weightDelta != null && weightDelta !== 0 && (
<span
className={`text-[0.75rem] font-semibold ${
weightDelta < 0 ? 'text-accent-text' : 'text-warn'
}`}
>
{weightDelta < 0 ? '−' : '+'}
{Math.abs(weightDelta).toLocaleString('pl-PL')} kg w tym miesiącu
</span>
)}
</span>
)
}
>
{chartReady ? (
{weightPoints.length === 0 ? (
<EmptyState
icon={Scale}
title="Brak pomiarów wagi"
description="Pomiary pojawią się tutaj, gdy użytkownik doda wagę w aplikacji."
/>
) : (
<>
<ResponsiveContainer width="100%" height={180}>
{sided ? (
<LineChart data={sideData}>
<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="lewy"
name="Lewy"
stroke="var(--info)"
strokeWidth={2}
dot={false}
connectNulls
/>
<Line
type="monotone"
dataKey="prawy"
name="Prawy"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
connectNulls
/>
</LineChart>
) : (
<LineChart
data={g.series[0].points.map((p) => ({
date: new Date(p.date).toLocaleDateString('pl-PL', {
day: '2-digit',
month: '2-digit',
}),
value: p.value,
}))}
>
{weightData.length >= 2 ? (
<ResponsiveContainer width="100%" height={220}>
<LineChart data={weightData}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
@@ -687,85 +295,155 @@ export default function UserBodyParameters() {
<Line
type="monotone"
dataKey="value"
stroke="var(--info)"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
/>
</LineChart>
)}
</ResponsiveContainer>
{sided && (
<div className="mt-2 flex flex-wrap gap-4 text-[0.875rem] text-dim">
{sidesPresent.includes('left') && (
<span className="flex items-center gap-1.5">
<span className="w-3 h-0.5 bg-info inline-block rounded-md" />
Lewy
</span>
)}
{sidesPresent.includes('right') && (
<span className="flex items-center gap-1.5">
<span className="w-3 h-0.5 bg-accent inline-block rounded-md" />
Prawy
</span>
)}
</div>
</ResponsiveContainer>
) : (
<p className="text-dim">Za mało danych na wykres (min. 2 pomiary).</p>
)}
<MeasurementList
points={[...weightPoints].reverse().map((p) => ({
id: p.id,
label: `${p.value} kg`,
meta: fmtDate(p.date),
}))}
visible={countFor('weight')}
onShowMore={() => showMore('weight')}
/>
</>
) : (
<p className="text-dim">Za mało danych na wykres.</p>
)}
<MeasurementList
points={[...allPoints]
.sort((a, b) => b.date.localeCompare(a.date))
.map((p) => ({
id: p.id,
kind: 'circumference' as const,
label: `${p.value} cm`,
meta: `${fmtDate(p.date)}${p.side ? ` · ${SIDE_LABELS[p.side]}` : ''}`,
deleteLabel: `Usuń pomiar ${p.name} z ${fmtDate(p.date)}`,
removeLabel: `${p.name} ${p.value} cm (${fmtDate(p.date)})`,
}))}
visible={countFor(g.part)}
onShowMore={() => showMore(g.part)}
onDelete={setRemoveTarget}
/>
</MeasurementCard>
);
})}
<AddMeasurementModal
open={addOpen}
onClose={() => setAddOpen(false)}
tab={addTab}
onTabChange={setAddTab}
weight={weight}
onWeightChange={setWeight}
weightDate={weightDate}
onWeightDateChange={setWeightDate}
circType={circType}
onCircTypeChange={setCircType}
circSide={circSide}
onCircSideChange={setCircSide}
circValue={circValue}
onCircValueChange={setCircValue}
circDate={circDate}
onCircDateChange={setCircDate}
busy={busy}
error={error}
onSaveWeight={(e) => void saveWeight(e)}
onSaveCirc={(e) => void saveCirc(e)}
/>
{circGroups.length === 0 && (
<MeasurementCard icon={Ruler} title="Obwody">
<p className="text-dim">Brak pomiarów{month ? ' w wybranym miesiącu' : ''}.</p>
</MeasurementCard>
)}
{circGroups.map((g) => {
const allPoints = g.series.flatMap((s) =>
s.points.map((p) => ({ ...p, name: s.name, side: sideOf(s.name) })),
);
const latest = allPoints.reduce<(typeof allPoints)[number] | null>(
(max, p) => (max == null || p.date > max.date ? p : max),
null,
);
const sided = g.series.some((s) => sideOf(s.name) != null);
const sidesPresent = [
...new Set(g.series.map((s) => sideOf(s.name)).filter((s): s is Side => s != null)),
];
const sideData = mergedSideData(g.series);
const chartReady = sided ? sideData.length >= 2 : g.series[0].points.length >= 2;
<ConfirmDialog
open={removeTarget != null}
onClose={() => setRemoveTarget(null)}
onConfirm={() => void confirmRemove()}
title="Usunąć pomiar?"
description={removeTarget ? `${removeTarget.label} zostanie trwale usunięty.` : ''}
confirmLabel="Usuń"
danger
busy={removeBusy}
/>
return (
<MeasurementCard
key={g.part}
icon={Ruler}
title={g.part}
latest={
latest && (
<span className="flex items-baseline gap-2">
<span className="font-display text-[1.35rem] font-bold leading-none tabular-nums">
{latest.value} cm
</span>
<span className="text-[0.75rem] text-dim">
{latest.side ? `${SIDE_LABELS[latest.side]} · ` : '· '}
{fmtDate(latest.date)}
</span>
</span>
)
}
>
{chartReady ? (
<>
<ResponsiveContainer width="100%" height={180}>
{sided ? (
<LineChart data={sideData}>
<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="lewy"
name="Lewy"
stroke="var(--info)"
strokeWidth={2}
dot={false}
connectNulls
/>
<Line
type="monotone"
dataKey="prawy"
name="Prawy"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
connectNulls
/>
</LineChart>
) : (
<LineChart
data={g.series[0].points.map((p) => ({
date: new Date(p.date).toLocaleDateString('pl-PL', {
day: '2-digit',
month: '2-digit',
}),
value: p.value,
}))}
>
<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="value"
stroke="var(--info)"
strokeWidth={2}
dot={false}
/>
</LineChart>
)}
</ResponsiveContainer>
{sided && (
<div className="mt-2 flex flex-wrap gap-4 text-[0.875rem] text-dim">
{sidesPresent.includes('left') && (
<span className="flex items-center gap-1.5">
<span className="w-3 h-0.5 bg-info inline-block rounded-md" />
Lewy
</span>
)}
{sidesPresent.includes('right') && (
<span className="flex items-center gap-1.5">
<span className="w-3 h-0.5 bg-accent inline-block rounded-md" />
Prawy
</span>
)}
</div>
)}
</>
) : (
<p className="text-dim">Za mało danych na wykres.</p>
)}
<MeasurementList
points={[...allPoints]
.sort((a, b) => b.date.localeCompare(a.date))
.map((p) => ({
id: p.id,
label: `${p.value} cm`,
meta: `${fmtDate(p.date)}${p.side ? ` · ${SIDE_LABELS[p.side]}` : ''}`,
}))}
visible={countFor(g.part)}
onShowMore={() => showMore(g.part)}
/>
</MeasurementCard>
);
})}
</>
)}
</>
);
}

View File

@@ -1,11 +1,9 @@
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 UserBodyParameters from '../src/pages/users/UserBodyParameters';
import { setAccessToken } from '../src/api/client';
import { API_BASE } from '../src/config';
const BP = {
weight: [{ id: 'w1', value: 81.5, date: '2026-09-10T10:00:00.000Z' }],
@@ -61,7 +59,9 @@ describe('admin UserBodyParameters page', () => {
mockFetchRoutes([['/body-parameters', () => BP]]);
renderPage();
expect(await screen.findByRole('heading', { name: 'Parametry ciała', level: 1 })).toBeInTheDocument();
expect(
await screen.findByRole('heading', { name: 'Parametry ciała', level: 2 }),
).toBeInTheDocument();
// karta Waga: najnowszy pomiar + wiersz listy
expect(screen.getAllByText('81.5 kg').length).toBeGreaterThan(0);
expect(screen.getByText('Za mało danych na wykres (min. 2 pomiary).')).toBeInTheDocument();
@@ -71,43 +71,13 @@ describe('admin UserBodyParameters page', () => {
expect(screen.getAllByText(/lewy/i).length).toBeGreaterThan(0);
});
it('dodanie wagi POSTuje na endpoint admina', async () => {
const calls = mockFetchRoutes([['/body-parameters', () => BP]]);
const user = userEvent.setup();
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 });
await user.click(screen.getByRole('button', { name: '+ Waga' }));
await user.type(screen.getByPlaceholderText('waga (kg)'), '80.3');
await user.click(screen.getByRole('button', { name: 'Dodaj wagę' }));
const post = calls.find(
(c) => c.init?.method === 'POST' && c.url === `${API_BASE}/admin/users/u1/body-parameters/weight`,
);
expect(post).toBeDefined();
const body = JSON.parse(post?.init?.body as string);
expect(body).toMatchObject({ value: 80.3 });
expect(typeof body.date).toBe('string');
});
it('usuniecie pomiaru DELETEuje go po potwierdzeniu', async () => {
const calls = mockFetchRoutes([
['/body-parameters', () => BP],
['/body-parameters/weight/w1', () => null],
]);
const user = userEvent.setup();
renderPage();
await screen.findByRole('heading', { name: 'Waga', level: 3 });
await user.click(screen.getByRole('button', { name: /Usuń pomiar wagi/ }));
await user.click(await screen.findByRole('button', { name: 'Usuń', exact: true }));
expect(
calls.some(
(c) =>
c.init?.method === 'DELETE' &&
c.url === `${API_BASE}/admin/users/u1/body-parameters/weight/w1`,
),
).toBe(true);
expect(screen.queryByRole('button', { name: '+ Waga' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Dodaj wagę' })).not.toBeInTheDocument();
expect(screen.queryAllByRole('button', { name: /Usuń pomiar/ })).toHaveLength(0);
});
});