diff --git a/admin/src/components/ui/content.tsx b/admin/src/components/ui/content.tsx index d439924..61d5624 100644 --- a/admin/src/components/ui/content.tsx +++ b/admin/src/components/ui/content.tsx @@ -8,16 +8,20 @@ import { cn } from '../../lib/utils'; /* Page header: title + optional badge, actions on the right (stacks on mobile) */ export function PageHeader({ title, + leading, badge, actions, }: { title: string; + /** Element przed tytułem (np. awatar). */ + leading?: ReactNode; badge?: ReactNode; actions?: ReactNode; }) { return (
+ {leading} {/* `

` należy do topbaru (tytuł strony) — nagłówek treści to `

` */}

{title}

{badge} diff --git a/admin/src/lib/availability.ts b/admin/src/lib/availability.ts index 25bc7cd..ecfff51 100644 --- a/admin/src/lib/availability.ts +++ b/admin/src/lib/availability.ts @@ -1,7 +1,15 @@ import type { Availability, DayAvailability } from '../api/types.js'; export const DAY_NAMES = ['Pon', 'Wt', 'Śr', 'Czw', 'Pt', 'Sob', 'Niedz'] as const; -export const DAY_NAMES_FULL = ['Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota', 'Niedziela'] as const; +export const DAY_NAMES_FULL = [ + 'Poniedziałek', + 'Wtorek', + 'Środa', + 'Czwartek', + 'Piątek', + 'Sobota', + 'Niedziela', +] as const; /** 30-minute slots from 05:00 to 23:00. */ export const TIME_SLOTS: string[] = (() => { @@ -30,14 +38,31 @@ export function normalizeAvailability(value: unknown): Availability { return emptyAvailability(); } -/** Human-readable summary, e.g. "Pon 18:00–20:00, Wt 18:00–20:00". Empty string if none. */ -export function formatAvailability(value: unknown): string { +/** Zakresy pogrupowane po dniach o tych samych godzinach, np. ["Pon–Pt 18:00–20:00"]. + Pusta tablica, gdy brak ustawionej dostępności. */ +export function formatAvailabilityParts(value: unknown): string[] { const arr = normalizeAvailability(value); const parts: string[] = []; - arr.forEach((day, i) => { - if (day) parts.push(`${DAY_NAMES[i]} ${day.start}–${day.end}`); - }); - return parts.join(', '); + let i = 0; + while (i < 7) { + const day = arr[i]; + if (!day) { + i++; + continue; + } + let j = i + 1; + while (j < 7 && arr[j] && arr[j]!.start === day.start && arr[j]!.end === day.end) j++; + const days = j - i > 1 ? `${DAY_NAMES[i]}–${DAY_NAMES[j - 1]}` : DAY_NAMES[i]; + parts.push(`${days} ${day.start}–${day.end}`); + i = j; + } + return parts; +} + +/** Human-readable summary with consecutive same-time days grouped, + e.g. "Pon–Pt 18:00–20:00, Sob 12:00–14:00". Empty string if none. */ +export function formatAvailability(value: unknown): string { + return formatAvailabilityParts(value).join(', '); } /** "18:00" -> "18", "21:30" -> "21:30" — forma skrócona do siatki tygodnia. */ diff --git a/admin/src/lib/body-measurements.ts b/admin/src/lib/body-measurements.ts index ac7a78e..ee2dd73 100644 --- a/admin/src/lib/body-measurements.ts +++ b/admin/src/lib/body-measurements.ts @@ -20,6 +20,31 @@ export const MEASUREMENT_TYPES: MeasurementType[] = [ export const SIDE_LABELS: Record = { left: 'Lewy', right: 'Prawy' }; +/* Rodzaj gramatyczny części ciała → poprawna fleksja przymiotnika strony. */ +const PART_GENDERS: Record = { + 'Klatka piersiowa': 'f', + Talia: 'f', + Biodra: 'p', + Kark: 'm', + Biceps: 'm', + Przedramię: 'n', + Udo: 'n', + Łydka: 'f', +}; + +/** Etykiety strony zgodne z rodzajem części: `Udo` → `Lewe`/`Prawe`, `Talia` → `Lewa`/`Prawa`. */ +export function sideLabelsFor(part: string): Record { + switch (PART_GENDERS[part]) { + case 'f': + return { left: 'Lewa', right: 'Prawa' }; + case 'n': + case 'p': + return { left: 'Lewe', right: 'Prawe' }; + default: + return SIDE_LABELS; + } +} + export function measurementType(typeId: string): MeasurementType | undefined { return MEASUREMENT_TYPES.find((t) => t.id === typeId); } diff --git a/admin/src/lib/labels.ts b/admin/src/lib/labels.ts index a85af2c..b34fd1f 100644 --- a/admin/src/lib/labels.ts +++ b/admin/src/lib/labels.ts @@ -14,6 +14,18 @@ export const MUSCLE_NAMES: Record = { calves: 'Łydki', }; +export const MUSCLE_COLORS: Record = { + chest: 'red', + back: 'blue', + legs: 'green', + shoulders: 'yellow', + biceps: 'blue', + triceps: 'yellow', + core: 'gray', + glutes: 'red', + forearms: 'gray', +}; + export const SESSION_STATUS: Record< HistorySession['status'], { label: string; color: BadgeColor } diff --git a/admin/src/pages/users/UserBodyParameters.tsx b/admin/src/pages/users/UserBodyParameters.tsx index aec9180..4b78bc2 100644 --- a/admin/src/pages/users/UserBodyParameters.tsx +++ b/admin/src/pages/users/UserBodyParameters.tsx @@ -1,9 +1,9 @@ -import { useEffect, useState, type ReactNode } from 'react'; +import { useMemo, useState } from 'react'; import { useParams } from 'react-router-dom'; -import { ChevronDown, Ruler, Scale, type LucideIcon } from 'lucide-react'; +import { Ruler, Scale, TrendingDown, TrendingUp, type LucideIcon } from 'lucide-react'; import { - LineChart, - Line, + Area, + AreaChart, XAxis, YAxis, Tooltip, @@ -11,7 +11,6 @@ import { CartesianGrid, } from 'recharts'; import { useTopbar } from '../../topbar'; -import { MonthPickerCore } from '../../topbar/MonthPicker'; import { BackButton, Button, @@ -21,12 +20,14 @@ import { H3, PageHeader, Skeleton, + Tabs, } from '../../components/ui'; import { MEASUREMENT_TYPES, SIDE_LABELS, bodyPartOf, detectBodyPart, + sideLabelsFor, sideOf, type Side, } from '../../lib/body-measurements'; @@ -41,6 +42,26 @@ const TOOLTIP_STYLE = { 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 { part: string; series: CircumferenceSeries[]; @@ -70,168 +91,420 @@ function groupCircumferences(series: CircumferenceSeries[]): CircGroup[] { })); } -/** Wspólna oś dat dla obu stron: `[{ date, lewy, prawy }]` (brak pomiaru = null). */ -function mergedSideData(series: CircumferenceSeries[]) { - const byDate = new Map(); - for (const s of series) { - const side = sideOf(s.name); - if (side == null) continue; - for (const p of s.points) { - const entry = byDate.get(p.date) ?? { date: p.date, lewy: null, prawy: null }; - entry[side === 'left' ? 'lewy' : 'prawy'] = p.value; - byDate.set(p.date, entry); - } - } - return [...byDate.values()] - .sort((a, b) => a.date.localeCompare(b.date)) - .map((e) => ({ - date: new Date(e.date).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit' }), - lewy: e.lewy, - prawy: e.prawy, - })); +/* 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; } -/* Karta pomiaru: nagłówek (ikona + H3 + najnowszy pomiar) + treść (wykres + lista). */ -function MeasurementCard({ - icon: Icon, - title, - latest, - children, +interface PartGroup { + part: string; + unit: 'kg' | 'cm'; + /** Wszystkie pomiary (pełna historia), rosnąco po dacie. */ + points: GroupPoint[]; + sidesPresent: Side[]; +} + +/* Polski pluralis dla „pomiar”. */ +function pomN(n: number): string { + if (n === 1) return '1 pomiar'; + if (n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14)) return `${n} pomiary`; + return `${n} pomiarów`; +} + +const WEIGHT_PART = 'Waga'; + +const fmtVal = (n: number) => n.toLocaleString('pl-PL', { 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: PartGroup): { 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: `${signed(d)} ${g.unit} od pierwszego`, className }; +} + +/* Osobny div postępu wybranej części: kierunek zmiany + wynik (strony osobno, gdy łączone). */ +function ProgressCard({ + down, + primary, + primaryClass, + sub, }: { - icon: LucideIcon; - title: string; - latest?: ReactNode; - children: ReactNode; + down: boolean; + primary: string; + primaryClass: string; + sub: string; }) { + const Icon = down ? TrendingDown : TrendingUp; return ( - -
-
- - - -

{title}

+ +
+ + + +
+

Postęp

+

{primary}

+

{sub}

-
{latest}
- {children}
); } -interface MeasurementPoint { - id: string; - label: string; - meta: string; +/** Etykieta osi X: `17.10`; gdy historia przekracza rok — `17.10.26`. */ +function axisDateLabel(iso: string, withYear: boolean): string { + return new Date(iso).toLocaleDateString('pl-PL', { + day: '2-digit', + month: '2-digit', + ...(withYear ? { year: '2-digit' } : {}), + }); } -/* Lista pomiarów: najnowsze N + „Pokaż więcej"; wiersz = wartość + data (+ strona). */ -function MeasurementList({ +/** 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(); + 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 = { 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 ( + + + + + + + + + + + + + + + + ); +} + +/* 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, }: { - points: MeasurementPoint[]; + group: PartGroup; + icon: LucideIcon; visible: number; onShowMore: () => void; }) { - if (points.length === 0) return null; + const sided = group.sidesPresent.length > 1; + if (!sided) { + return ( + + + + ); + } + const labels = sideLabelsFor(group.part); + const unsidePoints = group.points.filter((p) => p.side == null); return ( -
- {/* 3 najnowsze; duże ekrany: wiersz z poziomym scrollem, małe: kolumna */} -
    - {points.slice(0, visible).map((p) => ( -
  • - {p.label} -
    {p.meta}
    -
  • +
    + {(['left', 'right'] as Side[]) + .filter((s) => group.sidesPresent.includes(s)) + .map((s) => ( + + p.side === s)} + stroke={SIDE_STROKE[s]} + chartName={labels[s].toLowerCase()} + visible={visible} + onShowMore={onShowMore} + /> + ))} -
- {points.length > visible && ( - + {unsidePoints.length > 0 && ( + + + )}
); } +/* 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, +}: { + title: string; + icon: LucideIcon; + unit: 'kg' | 'cm'; + points: GroupPoint[]; + stroke: string; + chartName: string; + visible: number; + onShowMore: () => void; +}) { + 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({ part: title, unit, points, sidesPresent: [] }); + const primary = prog?.text ?? 'bez zmian'; + const primaryClass = prog?.className ?? 'text-dim'; + const sub = + points.length < 2 + ? 'drugi pomiar pokaże zmianę' + : `${pomN(points.length)} · pierwszy → ostatni`; + + return ( + <> +
+
+ + + +

{title}

+
+ + + + {latest.value} {unit} + + {fmtDate(latest.date)} + + +
+ + + + {points.length >= 2 ? ( + + ) : ( +

Za mało danych na wykres (min. 2 pomiary).

+ )} + + {/* lista: najnowsze 3 + „Pokaż więcej" (kolejne 3); pełna historia w wykresie */} +
+
    + {[...points] + .reverse() + .slice(0, visible) + .map((p) => { + const sideLabel = p.side ? ` · ${SIDE_LABELS[p.side]}` : ''; + return ( +
  • + + {p.value} {unit} + +
    + {fmtDate(p.date)} + {sideLabel} +
    +
  • + ); + })} +
+ {points.length > visible && ( + + )} +
+ + ); +} + /** - * 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`. + * 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 { id } = useParams(); const { data: bp, isLoading: bpLoading, error: bpError } = useUserBodyParameters(id); const [visible, setVisible] = useState>({}); - // miesiąc w topmenu: zawsze wybrany (domyślnie bieżący), jak w aplikacji; - // strzałki i siatka skaczą tylko po miesiącach z danymi - const [month, setMonth] = useState(() => { - const d = new Date(); - return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`; - }); - - // miesiące z danymi (nowe → stare) — do selektora w topmenu - const monthKeys = [ - ...(bp?.weight ?? []).map((w) => w.date.slice(0, 7)), - ...(bp?.circumferences ?? []).flatMap((s) => s.points.map((p) => p.date.slice(0, 7))), - ]; - const availableMonths = [...new Set(monthKeys)].sort().reverse(); + const [selected, setSelected] = useState(null); useTopbar({ title: 'Parametry ciała', back: id ? `/users/${id}` : '/users', - dateFilter: ( - - ), - filterActive: month !== '', }); - // lista: 3 najnowsze + „Pokaż więcej" (kolejne 3); zmiana miesiąca resetuje + // 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 })); - useEffect(() => setVisible({}), [month]); - // wybrany miesiąc bez danych → najnowszy miesiąc z danymi - useEffect(() => { - if (availableMonths.length > 0 && !availableMonths.includes(month)) { - setMonth(availableMonths[0]); + // pełna historia: waga + obwody jako jednolite grupy (bez filtra miesiąca) + const groups = useMemo(() => { + const list: PartGroup[] = []; + const weightPoints = [...(bp?.weight ?? [])].sort((a, b) => a.date.localeCompare(b.date)); + if (weightPoints.length > 0) { + list.push({ + part: WEIGHT_PART, + unit: 'kg', + points: weightPoints.map((w) => ({ + id: w.id, + value: w.value, + date: w.date, + side: null, + name: 'wagi', + })), + sidesPresent: [], + }); } - }, [availableMonths.join(','), month]); + for (const g of groupCircumferences(bp?.circumferences ?? [])) { + const points = g.series + .flatMap((s) => + s.points.map((p) => ({ + id: p.id, + value: p.value, + date: p.date, + side: sideOf(s.name), + name: s.name, + })), + ) + .sort((a, b) => a.date.localeCompare(b.date)); + const sidesPresent = [ + ...new Set(g.series.map((s) => sideOf(s.name)).filter((s): s is Side => s != null)), + ]; + list.push({ + part: g.part, + unit: 'cm', + points, + sidesPresent, + }); + } + return list; + }, [bp]); - // zakres: wybrany w topmenu miesiąc (YYYY-MM) - const inMonth = (date: string) => date.startsWith(month); - - const weightPoints = [...(bp?.weight ?? [])] - .filter((w) => inMonth(w.date)) - .sort((a, b) => a.date.localeCompare(b.date)); - const weightData = weightPoints.map((w) => ({ - date: new Date(w.date).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit' }), - value: w.value, - })); - const latestWeight = weightPoints[weightPoints.length - 1]; - // delta wagi w wybranym miesiącu: ostatni pomiar − pierwszy (spadek = accent, wzrost = warn) - const weightDelta = - weightPoints.length >= 2 - ? weightPoints[weightPoints.length - 1].value - weightPoints[0].value - : null; - - const circGroups = groupCircumferences( - (bp?.circumferences ?? []) - .map((s) => ({ - ...s, - points: s.points - .filter((p) => inMonth(p.date)) - .sort((a, b) => a.date.localeCompare(b.date)), - })) - .filter((s) => s.points.length > 0), - ); + // wybrana część odpada (brak danych) → pierwsza dostępna + const active = groups.find((g) => g.part === selected) ?? groups[0]; if (bpLoading) { return ( @@ -251,199 +524,29 @@ export default function UserBodyParameters() { {bpError ? ( Błąd: {(bpError as Error).message} + ) : active == null ? ( + ) : ( <> - - - - {latestWeight.value} kg - - · {fmtDate(latestWeight.date)} - - {weightDelta != null && weightDelta !== 0 && ( - - {weightDelta < 0 ? '−' : '+'} - {Math.abs(weightDelta).toLocaleString('pl-PL')} kg w tym miesiącu - - )} - - ) - } - > - {weightPoints.length === 0 ? ( - - ) : ( - <> - {weightData.length >= 2 ? ( - - - - - - - - - - ) : ( -

Za mało danych na wykres (min. 2 pomiary).

- )} - ({ - id: p.id, - label: `${p.value} kg`, - meta: fmtDate(p.date), - }))} - visible={countFor('weight')} - onShowMore={() => showMore('weight')} - /> - - )} -
+ {/* zakładki części: pełna nazwa (pasek jest przewijalny); szczegóły w panelu poniżej */} + ({ id: g.part, label: g.part }))} + active={active.part} + onChange={(id) => setSelected(id)} + /> - {circGroups.length === 0 && ( - -

Brak pomiarów w wybranym miesiącu.

-
- )} - {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 ( - - - {latest.value} cm - - - {latest.side ? `${SIDE_LABELS[latest.side]} · ` : '· '} - {fmtDate(latest.date)} - - - ) - } - > - {chartReady ? ( - <> - - {sided ? ( - - - - - - - - - ) : ( - ({ - date: new Date(p.date).toLocaleDateString('pl-PL', { - day: '2-digit', - month: '2-digit', - }), - value: p.value, - }))} - > - - - - - - - )} - - {sided && ( -
- {sidesPresent.includes('left') && ( - - - Lewy - - )} - {sidesPresent.includes('right') && ( - - - Prawy - - )} -
- )} - - ) : ( -

Za mało danych na wykres.

- )} - 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)} - /> -
- ); - })} +
+ showMore(active.part)} + /> +
)} diff --git a/admin/src/pages/users/UserClaims.tsx b/admin/src/pages/users/UserClaims.tsx index ff9cf90..924fda8 100644 --- a/admin/src/pages/users/UserClaims.tsx +++ b/admin/src/pages/users/UserClaims.tsx @@ -14,8 +14,8 @@ import { import { fmtDate } from '../../lib/format'; import { useUserClaims } from './user-queries'; -const STATUS_BADGE: Record = { - PENDING: { label: 'Oczekuje', color: 'gray' }, +const STATUS_BADGE: Record = { + PENDING: { label: 'Oczekuje', color: 'yellow' }, APPROVED: { label: 'Zatwierdzony', color: 'green' }, REJECTED: { label: 'Odrzucony', color: 'red' }, }; diff --git a/admin/src/pages/users/UserDetail.tsx b/admin/src/pages/users/UserDetail.tsx index 3b16c11..f741f34 100644 --- a/admin/src/pages/users/UserDetail.tsx +++ b/admin/src/pages/users/UserDetail.tsx @@ -25,6 +25,7 @@ import { useAdminUser, useUserBodyParameters, useUserClaims, + useUserExerciseProgress, useUserHistory, useUserKillstreak, } from './user-queries'; @@ -47,19 +48,15 @@ function sessionCountLabel(n: number) { return `${n} sesji`; } -/** Mini-statystyka: ikona + etykieta + wartość (+ meta). */ +/** Mini-statystyka: ikona + etykieta + wartość. */ function MiniStat({ icon: Icon, label, value, - meta, - valueClassName = '', }: { icon: LucideIcon; label: string; value: string; - meta?: string; - valueClassName?: string; }) { return (
@@ -68,12 +65,9 @@ function MiniStat({
{label}
-
+
{value}
- {meta &&
{meta}
}
); @@ -120,6 +114,7 @@ export default function UserDetail() { const { data: hist } = useUserHistory(id); const { data: ks } = useUserKillstreak(id); const { data: claimsData } = useUserClaims(id); + const { data: progressData } = useUserExerciseProgress(id); const [confirmOpen, setConfirmOpen] = useState(false); const [busy, setBusy] = useState(false); const [removeError, setRemoveError] = useState(''); @@ -163,11 +158,9 @@ export default function UserDetail() { const name = userDisplayName(user); const memberships = user.memberships ?? []; - // ostatnia waga + delta vs poprzedni pomiar (spadek = accent, wzrost = warn) + // 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 prevWeight = weightPoints[weightPoints.length - 2]; - const weightDelta = latestWeight && prevWeight ? latestWeight.value - prevWeight.value : null; const weightSummary = latestWeight ? `${latestWeight.value} kg · ${fmtDate(latestWeight.date)}` : 'brak pomiarów'; @@ -207,6 +200,18 @@ export default function UserDetail() { ? `${pendingClaims} oczekujących` : `${claims.length} rozstrzygniętych`; + const progressCount = (progressData?.exercises ?? []).length; + const progressSummary = + progressCount > 0 + ? `${progressCount} ${ + progressCount === 1 + ? 'ćwiczenie' + : progressCount < 5 && progressCount % 10 >= 2 && progressCount % 10 <= 4 + ? 'ćwiczenia' + : 'ćwiczeń' + }` + : 'brak danych'; + return ( <> {/* md+ „Wstecz” w treści (telefon: „<” w topbarze) — jak na GymDetail i podstronach */} @@ -242,28 +247,9 @@ export default function UserDetail() {
- {/* Pasek mini-statystyk: 2×2 na mobile, 4 w rzędzie na desktop */} -
+ {/* Pasek mini-statystyk: 2 na mobile, 3 w rzędzie na desktop */} +
- 0 ? '+' : '−'}${Math.abs(weightDelta).toLocaleString('pl-PL')} kg vs poprzedni` - : latestWeight - ? fmtDate(latestWeight.date) - : undefined - } - valueClassName={ - weightDelta != null && weightDelta !== 0 - ? weightDelta < 0 - ? 'text-accent-text' - : 'text-warn' - : '' - } - /> 0 ? String(sessions.length) : '—'} - meta={lastSession ? `ostatnia ${fmtDate(lastSession)}` : undefined} />
@@ -312,7 +297,7 @@ export default function UserDetail() { to={`/users/${user.id}/progress`} title="Postępy" icon={TrendingUp} - summary="1RM i objętość per ćwiczenie" + summary={progressSummary} /> = { +const MUSCLE_FIELD_BY_TONE: Record = { 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 ( +
+ + + +
+
{label}
+
+ {value} +
+
+
+ ); +} + +/* Płytki link społecznościowy: markowa kropka z inicjałem + nazwa + adres + strzałka. */ +const SOCIAL_BRAND: Record = { + 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 label = + entry.platform === 'OTHER' ? entry.label || 'Inne' : SOCIAL_MEDIA_LABELS[entry.platform]; + const brand = SOCIAL_BRAND[entry.platform]; + return ( + + + + {label} + {hostOf(entry.url)} + + + + ); +} + +/* 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 }) { + return ( + + + + Ciąg przyczynowo-skutkowy + + } + description="Ćwiczenia z aktywnego planu w kontekście priorytetów i wykluczeń." + /> + {chain ? ( +
+ {(Object.keys(MUSCLE_TONES) as MuscleTone[]).map((tone) => { + const entries = chain[tone] ?? []; + const t = MUSCLE_TONES[tone]; + return ( +
0 ? t.tint : 'border-line bg-input/40' + }`} + > +
+ 0 ? t.dot : 'bg-dim/40' + }`} + aria-hidden="true" + /> + 0 ? t.text : 'text-dim' + }`} + > + {t.label} + +
+ {entries.length === 0 ? ( + brak akcentów w planie + ) : ( +
+ {entries.map((e) => ( +
+
+ + {MUSCLE_NAMES[e.muscle] ?? e.name} + + {(e.exercises ?? []).length > 0 && ( + + {(e.exercises ?? []).length} + + )} +
+
+ {(e.exercises ?? []).length > 0 + ? `${t.chainPrefix}${(e.exercises ?? []).map((x) => x.name).join(', ')}` + : 'brak w aktywnym planie'} +
+
+ ))} +
+ )} +
+ ); + })} +
+ ) : ( + + )} +
+ ); +} + function InfoRow({ label, value }: { label: string; value: string }) { return (
@@ -65,9 +242,11 @@ function InfoRow({ label, value }: { label: string; value: string }) { } /** - * Tylko do odczytu: dane osobowe, priorytety i konto. + * 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 { id } = useParams(); @@ -99,14 +278,18 @@ export default function UserInfo() { ); } + const name = userDisplayName(user); + const availabilityParts = formatAvailabilityParts(user.availability); + return ( <> } actions={} /> - {/* Karta: konto (stan konta — edycja w wizardzie) */} + {/* Karta: konto (stan konta — edycja w wizardzie); dodatek admina */}
@@ -116,43 +299,87 @@ export default function UserInfo() {
- {/* Karta: podstawowe dane */} + {/* Karta 1: podstawowe dane — siatka płytek z ikonami + dostępność jako chipy */} -
- - - - - - - +
+ + + + + + +
+
+
+ + Dostępność +
+ {availabilityParts.length > 0 ? ( +
+ {availabilityParts.map((p) => ( + + {p} + + ))} +
+ ) : ( + Brak ustawionej dostępności + )}
- {/* Karta: priorytety i wykluczenia (4 grupy mięśni) */} + {/* Karta 2: priorytety i wykluczenia — 4 kafelki w tonie grupy */} -
+
{(Object.keys(MUSCLE_TONES) as MuscleTone[]).map((tone) => { const musclesList = (user[MUSCLE_FIELD_BY_TONE[tone]] as string[] | undefined) ?? []; + const t = MUSCLE_TONES[tone]; return ( -
-
- {MUSCLE_TONES[tone].label} +
0 ? t.tint : 'border-line bg-input/40' + }`} + > +
+ 0 ? t.dot : 'bg-dim/40' + }`} + aria-hidden="true" + /> + 0 ? t.text : 'text-dim' + }`} + > + {t.label} + + {musclesList.length > 0 && ( + + {musclesList.length} + + )}
{musclesList.length > 0 ? ( musclesList.map((m) => ( {areaName(m)} )) ) : ( - — + nic nie dodano )}
@@ -161,67 +388,24 @@ export default function UserInfo() {
- {/* Karta: social media */} + {/* Karta 3: social media — kafelki linków z markową kropką i domeną */} -
- {(user.socialMedia ?? []).length > 0 ? ( - (user.socialMedia ?? []).map((s, i) => ( - - {s.platform === 'OTHER' ? s.label || 'Inne' : SOCIAL_MEDIA_LABELS[s.platform]} - - )) - ) : ( - — - )} -
-
- - {/* Karta: ciąg przyczynowo-skutkowy (tylko odczyt) */} - - - {chain ? ( -
- {(Object.keys(MUSCLE_TONES) as MuscleTone[]).map((tone) => { - const entries = chain[tone] ?? []; - return ( -
-

{MUSCLE_TONES[tone].label}

- {entries.length === 0 ? ( - — - ) : ( -
- {entries.map((en) => ( -
-
{en.name}
-
- {(en.exercises ?? []).length > 0 - ? `${MUSCLE_TONES[tone].chainPrefix}${(en.exercises ?? []) - .map((x) => x.name) - .join(', ')}` - : 'brak w aktywnym planie'} -
-
- ))} -
- )} -
- ); - })} + {(user.socialMedia ?? []).length > 0 ? ( +
+ {(user.socialMedia ?? []).map((s, i) => ( + + ))}
) : ( - +
+ + Brak dodanych profili. +
)} + + ); } diff --git a/admin/src/pages/users/UserProgress.tsx b/admin/src/pages/users/UserProgress.tsx index 2b4b921..0c9b7e7 100644 --- a/admin/src/pages/users/UserProgress.tsx +++ b/admin/src/pages/users/UserProgress.tsx @@ -1,21 +1,13 @@ import { useParams } from 'react-router-dom'; import { TrendingUp } from 'lucide-react'; import { useTopbar } from '../../topbar'; -import { - BackButton, - Card, - EmptyState, - ErrorText, - Muted, - PageHeader, - Skeleton, -} from '../../components/ui'; +import { BackButton, Card, EmptyState, ErrorText, PageHeader, Skeleton } from '../../components/ui'; import ExerciseProgressCards from '../../components/ExerciseProgressCards'; import { useUserExerciseProgress } from './user-queries'; /** - * Postępy per ćwiczenie (1RM Epley + objętość) użytkownika — widok admina, - * wzorowany na `/profile/progress` z aplikacji. + * 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 { id } = useParams(); @@ -38,10 +30,6 @@ export default function UserProgress() { } /> - - 1RM Epley: zaplanowane obciążenie × (1 + powtórzenia/30), maks. per sesja; objętość = Σ - obciążenie × powtórzenia. - {error && Błąd: {(error as Error).message}} {!error && exercises.length === 0 && ( { }); describe('admin UserBodyParameters page', () => { - it('pokazuje ostatnie pomiary wagi i obwodów', async () => { + 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(); - // karta Waga: najnowszy pomiar + wiersz listy + + // 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.getByText('Za mało danych na wykres (min. 2 pomiary).')).toBeInTheDocument(); - // karta obwodu grupowana po części ciała (Biceps lewy → karta „Biceps”) - expect(screen.getByRole('heading', { name: 'Biceps' })).toBeInTheDocument(); - expect(screen.getAllByText('35 cm').length).toBeGreaterThan(0); - expect(screen.getAllByText(/lewy/i).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 () => { @@ -78,6 +153,7 @@ describe('admin UserBodyParameters page', () => { 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); }); }); diff --git a/admin/test/UserDetail.test.tsx b/admin/test/UserDetail.test.tsx index 53e3a6d..a63fd37 100644 --- a/admin/test/UserDetail.test.tsx +++ b/admin/test/UserDetail.test.tsx @@ -97,6 +97,7 @@ describe('admin UserDetail (przegląd profilu)', () => { ['/body-parameters', () => ({ weight: [], circumferences: [] })], ['/history', () => ({ sessions: [] })], ['/claims', () => ({ claims: [] })], + ['/exercise-progress', () => ({ exercises: [] })], ]); renderUserDetail(); expect(await screen.findByText('Zablokowane')).toBeInTheDocument(); @@ -121,6 +122,7 @@ describe('admin UserDetail (przegląd profilu)', () => { ['/body-parameters', () => ({ weight: [], circumferences: [] })], ['/history', () => ({ sessions: [] })], ['/claims', () => ({ claims: [] })], + ['/exercise-progress', () => ({ exercises: [] })], ]); renderUserDetail(); expect(await screen.findByText(/Zawieszone do/)).toBeInTheDocument(); @@ -139,6 +141,7 @@ describe('admin UserDetail (przegląd profilu)', () => { ], ['/history', () => ({ sessions: [] })], ['/claims', () => ({ claims: [] })], + ['/exercise-progress', () => ({ exercises: [{ id: 'e1' }] })], ]); renderUserDetail(); @@ -148,10 +151,16 @@ describe('admin UserDetail (przegląd profilu)', () => { expect(screen.getByText('@jano')).toBeInTheDocument(); expect(screen.getByText('Admin')).toBeInTheDocument(); - // mini-statystyki z endpointów + // 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('81.5 kg')).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 [ @@ -176,6 +185,7 @@ describe('admin UserDetail (przegląd profilu)', () => { ['/body-parameters', () => ({ weight: [], circumferences: [] })], ['/history', () => ({ sessions: [] })], ['/claims', () => ({ claims: [] })], + ['/exercise-progress', () => ({ exercises: [] })], ]); renderUserDetail(); const row = await screen.findByRole('link', { name: /Członkostwa w siłowniach/ }); diff --git a/admin/test/UserInfo.test.tsx b/admin/test/UserInfo.test.tsx index 5dfb832..399289e 100644 --- a/admin/test/UserInfo.test.tsx +++ b/admin/test/UserInfo.test.tsx @@ -47,7 +47,15 @@ const U1: User = { heightCm: 180, phone: '+48 500 100 200', isAdmin: true, - availability: null, + 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'], @@ -120,6 +128,9 @@ describe('admin UserInfo page', () => { 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); diff --git a/admin/test/e2e/admin.spec.ts b/admin/test/e2e/admin.spec.ts index ff07620..151ebb5 100644 --- a/admin/test/e2e/admin.spec.ts +++ b/admin/test/e2e/admin.spec.ts @@ -111,10 +111,14 @@ test('kliknięcie w użytkownika otwiera przegląd profilu (wzór z apki)', asyn 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 + wiersze sekcji + // hero: e-mail + mini-statystyki (pasek 3-kaflowy jak w apce) + wiersze sekcji await expect(page.getByText('jan@fitos.pl')).toBeVisible(); await expect(page.getByText('Killstreak')).toBeVisible(); - await expect(page.getByText('81.5 kg', { exact: true })).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(); diff --git a/admin/test/setup.ts b/admin/test/setup.ts index 116a56c..50fdf04 100644 --- a/admin/test/setup.ts +++ b/admin/test/setup.ts @@ -2,6 +2,27 @@ import '@testing-library/jest-dom/vitest'; import { afterEach } from 'vitest'; import { cleanup } from '@testing-library/react'; +// recharts (ResponsiveContainer) wymaga ResizeObserver, którego jsdom nie dostarcza. +// Stub wywołuje callback z fikcyjnym rozmiarem — wykresy renderują się w stałym 800×600. +class ResizeObserverStub { + private cb: (entries: { contentRect: { width: number; height: number } }[]) => void; + constructor(cb: (entries: { contentRect: { width: number; height: number } }[]) => void) { + this.cb = cb; + } + observe() { + this.cb([{ contentRect: { width: 800, height: 600 } }]); + } + unobserve() {} + disconnect() {} +} +if (typeof globalThis.ResizeObserver === 'undefined') { + Object.defineProperty(globalThis, 'ResizeObserver', { + value: ResizeObserverStub, + configurable: true, + writable: true, + }); +} + // vitest runs with globals:false, so RTL auto-cleanup is not registered // automatically; clean the DOM after every test. afterEach(() => {