From 89adaff0ff2627edad8df64235e1042ca92e565e Mon Sep 17 00:00:00 2001 From: tisachi Date: Thu, 29 Oct 2026 18:25:33 +0100 Subject: [PATCH] Admin: podglad tablicy sirowni (ranking, agregaty, ekwiwalenty i rekordy 1RM tylko do odczytu) --- admin/src/App.tsx | 2 + admin/src/api/queries.ts | 14 +- admin/src/api/types.ts | 44 +++++ admin/src/components/stats/MuscleSplit.tsx | 56 ++++++ admin/src/i18n/locales/en/gyms.json | 21 ++ admin/src/i18n/locales/pl/gyms.json | 23 +++ admin/src/lib/format.ts | 5 + admin/src/lib/labels.ts | 4 + admin/src/lib/stats-equiv.ts | 16 ++ admin/src/pages/gyms/GymBoard.tsx | 216 +++++++++++++++++++++ admin/src/pages/gyms/GymDetail.tsx | 26 +++ admin/test/GymBoard.test.tsx | 158 +++++++++++++++ admin/test/GymDetail.test.tsx | 8 +- 13 files changed, 591 insertions(+), 2 deletions(-) create mode 100644 admin/src/components/stats/MuscleSplit.tsx create mode 100644 admin/src/lib/stats-equiv.ts create mode 100644 admin/src/pages/gyms/GymBoard.tsx create mode 100644 admin/test/GymBoard.test.tsx diff --git a/admin/src/App.tsx b/admin/src/App.tsx index 0f65156..cebcc79 100644 --- a/admin/src/App.tsx +++ b/admin/src/App.tsx @@ -7,6 +7,7 @@ import Login from './pages/Login'; import GymsList from './pages/gyms/GymsList'; import GymForm from './pages/gyms/GymForm'; import GymDetail from './pages/gyms/GymDetail'; +import GymBoard from './pages/gyms/GymBoard'; import GymGalleryPage from './pages/gyms/GymGalleryPage'; import GymEquipmentPage from './pages/gyms/GymEquipmentPage'; import GymAnnouncementsPage from './pages/gyms/GymAnnouncementsPage'; @@ -48,6 +49,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/admin/src/api/queries.ts b/admin/src/api/queries.ts index e185653..008f657 100644 --- a/admin/src/api/queries.ts +++ b/admin/src/api/queries.ts @@ -1,6 +1,6 @@ import { useQuery } from '@tanstack/react-query'; import { api } from './client'; -import type { EquipmentUsageRow, User } from './types'; +import type { EquipmentUsageRow, GymBoardData, User } from './types'; /** Bieżący użytkownik (admin) — profil + członkostwa, jak `useMe` w aplikacji. */ export function useMe() { @@ -32,3 +32,15 @@ export function useAdminGymEquipmentUsage(gymId: string | undefined, rangeDays: enabled: !!gymId, }); } + +/** + * Tablica statystyk siłowni (GET /gyms/:id/board, tylko REAL) — te same dane co + * w apce; admin ma dostęp do endpointa, widok w panelu jest read-only (bez opt-in). + */ +export function useGymBoard(gymId: string | undefined, rangeDays: number) { + return useQuery({ + queryKey: ['gym-board', gymId, rangeDays], + queryFn: () => api(`/gyms/${gymId}/board?range=${rangeDays}`), + enabled: !!gymId, + }); +} diff --git a/admin/src/api/types.ts b/admin/src/api/types.ts index 6b98fe0..4a74736 100644 --- a/admin/src/api/types.ts +++ b/admin/src/api/types.ts @@ -215,6 +215,50 @@ export interface GymPresenceStatsResponse { stats: GymPresenceStatsData; } +/** Wiersz rankingu tablicy (GET /gyms/:id/board) — skuteczne sesje w zakresie. */ +export interface GymBoardRankRow { + userId: string; + nickname: string | null; + firstName: string; + lastName: string; + sessions: number; + tonnageKg: number; + days: number; +} + +/** Autor rekordu 1RM (atrybucja tylko po opt-in; null = anonim). */ +export interface GymBoardAuthor { + nickname: string | null; + firstName: string; + lastName: string; +} + +/** Rekord 1RM (Epley) z całej historii. */ +export interface GymBoardRecord { + exerciseId: string; + name: string; + nameEn: string | null; + muscle: string; + oneRm: number; + date: string; + author: GymBoardAuthor | null; +} + +/** Odpowiedź tablicy statystyk siłowni (tylko REAL); w adminie widok read-only. */ +export interface GymBoardData { + gym: { id: string; name: string }; + myStatsOptIn: boolean | null; + rangeDays: number; + ranking: GymBoardRankRow[]; + aggregate: { + tonnageKg: number; + sessions: number; + uniqueExercisers: number; + muscles: { muscle: string; sets: number; volumeKg: number }[]; + }; + records: GymBoardRecord[]; +} + /** Kafel godzinowy mapy ciepła urządzeń (0–23, godzina lokalna serwera). */ export interface EquipmentUsageCell { hour: number; diff --git a/admin/src/components/stats/MuscleSplit.tsx b/admin/src/components/stats/MuscleSplit.tsx new file mode 100644 index 0000000..0502fc1 --- /dev/null +++ b/admin/src/components/stats/MuscleSplit.tsx @@ -0,0 +1,56 @@ +import { Badge } from '../ui'; +import { fmtVolume } from '../../lib/format'; +import { MUSCLE_COLORS, muscleName, setCountLabel } from '../../lib/labels'; + +// Paleta segmentów paska partii (kolory dekoracyjne, stałe niezależnie od motywu). +export const MUSCLE_PALETTE = ['#ff6b4a', '#63b3e4', '#e8b04a', '#4ec97f', '#a78bfa', '#5eead4']; + +export interface MuscleSplitRow { + muscle: string; + sets: number; + volumeKg: number; +} + +/** + * Rozbicie na partie ciała: pasek udziału serii + legenda (badge partii, + * liczba serii, tonaż). Lustrzany komponent aplikacji (tablica siłowni). + */ +export function MuscleSplit({ + muscles, + ariaLabel, +}: { + muscles: MuscleSplitRow[]; + ariaLabel: string; +}) { + const muscleTotal = muscles.reduce((n, m) => n + m.sets, 0); + return ( +
+
+ {muscles.map((m, i) => ( +
+ ))} +
+
    + {muscles.map((m) => ( +
  • + {muscleName(m.muscle)} + + {setCountLabel(m.sets)} · {fmtVolume(m.volumeKg)} + +
  • + ))} +
+
+ ); +} diff --git a/admin/src/i18n/locales/en/gyms.json b/admin/src/i18n/locales/en/gyms.json index 7dfea57..32e2811 100644 --- a/admin/src/i18n/locales/en/gyms.json +++ b/admin/src/i18n/locales/en/gyms.json @@ -183,6 +183,27 @@ "qrCopy": "Copy link", "qrCopied": "Copied" }, + "board": { + "title": "Board", + "tileHint": "Ranking and records", + "rangeAria": "Board range", + "rangeDays_one": "{{count}} day", + "rangeDays_other": "{{count}} days", + "rankingTitle": "Training ranking", + "emptyRanking": "No information", + "aggregateTitle": "Gym aggregate", + "aggTonnage": "Tonnage", + "aggSessions": "Sessions", + "aggExercisers": "Exercisers", + "equivElephants": "African elephant (6 t)", + "equivBus": "city bus (12.5 t)", + "equivCar": "car (1.5 t)", + "musclesTitle": "Muscle groups of the gym", + "emptyMuscles": "No sets in this period.", + "recordsTitle": "1RM records", + "emptyRecords": "No measurable records.", + "anon": "anonymous" + }, "stats": { "cellTitle_one": "{{day}}, {{hour}}:00 — {{count}} visit", "cellTitle_other": "{{day}}, {{hour}}:00 — {{count}} visits" diff --git a/admin/src/i18n/locales/pl/gyms.json b/admin/src/i18n/locales/pl/gyms.json index 2448523..efe7390 100644 --- a/admin/src/i18n/locales/pl/gyms.json +++ b/admin/src/i18n/locales/pl/gyms.json @@ -195,6 +195,29 @@ "qrCopy": "Kopiuj link", "qrCopied": "Skopiowano" }, + "board": { + "title": "Tablica", + "tileHint": "Ranking i rekordy", + "rangeAria": "Zakres tablicy", + "rangeDays_one": "{{count}} dzień", + "rangeDays_few": "{{count}} dni", + "rangeDays_many": "{{count}} dni", + "rangeDays_other": "{{count}} dni", + "rankingTitle": "Ranking treningów", + "emptyRanking": "Brak informacji", + "aggregateTitle": "Zbiorowość siłowni", + "aggTonnage": "Tonaż", + "aggSessions": "Sesje", + "aggExercisers": "Ćwiczący", + "equivElephants": "słoń afrykański (6 t)", + "equivBus": "autobus (12,5 t)", + "equivCar": "samochód osobowy (1,5 t)", + "musclesTitle": "Partie ciała siłowni", + "emptyMuscles": "Brak serii w tym okresie.", + "recordsTitle": "Rekordy 1RM", + "emptyRecords": "Brak mierzalnych rekordów.", + "anon": "anonim" + }, "stats": { "cellTitle_one": "{{day}}, {{hour}}:00 — {{count}} wizyta", "cellTitle_few": "{{day}}, {{hour}}:00 — {{count}} wizyty", diff --git a/admin/src/lib/format.ts b/admin/src/lib/format.ts index 5ab24b1..b6091bd 100644 --- a/admin/src/lib/format.ts +++ b/admin/src/lib/format.ts @@ -90,6 +90,11 @@ export function fmtVolume(kg: number): string { return `${Math.round(kg).toLocaleString(currentTag())} kg`; } +/** Obciążenie w kg do wyświetlania: 62.5 → „62,5” (Intl, max 2 miejsca po przecinku). */ +export function fmtLoadKg(kg: number): string { + return kg.toLocaleString(currentTag(), { maximumFractionDigits: 2 }); +} + /** Czas trwania sesji: „45 min”, „1 h 30 min”. */ export function fmtDuration(startIso: string, endIso: string): string { const min = Math.round((new Date(endIso).getTime() - new Date(startIso).getTime()) / 60000); diff --git a/admin/src/lib/labels.ts b/admin/src/lib/labels.ts index 6fbe04a..92d826b 100644 --- a/admin/src/lib/labels.ts +++ b/admin/src/lib/labels.ts @@ -7,6 +7,10 @@ export function muscleName(muscle: string): string { return i18n.exists(key) ? i18n.t(key) : muscle; } +export function setCountLabel(n: number): string { + return i18n.t('counters.setCount', { count: n }); +} + export const MUSCLE_COLORS: Record = { chest: 'red', back: 'blue', diff --git a/admin/src/lib/stats-equiv.ts b/admin/src/lib/stats-equiv.ts new file mode 100644 index 0000000..cd599e8 --- /dev/null +++ b/admin/src/lib/stats-equiv.ts @@ -0,0 +1,16 @@ +/** + * Przyjęte masy jednostek do ekwiwalentów tonażu (kg) — lustrzana tabela + * aplikacji (klucze etykiet zostają w i18n poszczególnych pakietów nazw). + */ +export const EQUIV_UNITS = [ + { id: 'elephants', kg: 6000 }, + { id: 'bus', kg: 12500 }, + { id: 'car', kg: 1500 }, +] as const; + +export type EquivUnitId = (typeof EQUIV_UNITS)[number]['id']; + +/** Ile sztuk jednostki mieści się w podanym tonażu (zaokrąglenie). */ +export function equivCount(tonnageKg: number, kg: number): number { + return Math.round(tonnageKg / kg); +} diff --git a/admin/src/pages/gyms/GymBoard.tsx b/admin/src/pages/gyms/GymBoard.tsx new file mode 100644 index 0000000..b3a9a84 --- /dev/null +++ b/admin/src/pages/gyms/GymBoard.tsx @@ -0,0 +1,216 @@ +import { useState } from 'react'; +import { useParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { useGymBoard } from '../../api/queries'; +import type { GymBoardRecord } from '../../api/types'; +import { MuscleSplit } from '../../components/stats/MuscleSplit'; +import { + BackButton, + Badge, + Card, + ErrorText, + Loading, + PageHeader, + SectionHeader, + Select, +} from '../../components/ui'; +import { Avatar } from '../../components/Avatar'; +import { displayName, fmtDate, fmtLoadKg, fmtVolume } from '../../lib/format'; +import { localizedName } from '../../lib/localizedName'; +import { MUSCLE_COLORS, muscleName } from '../../lib/labels'; +import { EQUIV_UNITS, equivCount, type EquivUnitId } from '../../lib/stats-equiv'; +import { useTopbar } from '../../topbar'; + +const RANGE_OPTIONS = [7, 30, 90]; + +// Etykiety ekwiwalentów (wspólne masy jednostek w lib/stats-equiv). +const EQUIV_LABELS: Record = { + elephants: 'board.equivElephants', + bus: 'board.equivBus', + car: 'board.equivCar', +}; + +/* KPI: etykieta + duża wartość tabelaryczna (wzorzec statystyk siłowni). */ +function Kpi({ label, value }: { label: string; value: string | number }) { + return ( + +
{label}
+
{value}
+
+ ); +} + +/* Wiersz rekordu 1RM: nazwa ćwiczenia + partia + autor (lub „anonim") + wartość. */ +function RecordRow({ record, index }: { record: GymBoardRecord; index: number }) { + const { t, i18n } = useTranslation('gyms'); + const authorName = record.author ? displayName(record.author, t('board.anon')) : t('board.anon'); + return ( +
+
+
+ + {index + 1}. {localizedName(record, i18n.language)} + + + {muscleName(record.muscle) || record.muscle} + +
+
+ {authorName} · {fmtDate(record.date)} +
+
+
+ {fmtLoadKg(record.oneRm)} kg +
+
+ ); +} + +/** + * Tablica statystyk siłowni REAL w panelu admina (`/gyms/:id/board`) — te same + * dane co w apce: anonimowe agregaty wszystkich ćwiczących + ranking skutecznych + * sesji i rekordy 1RM (nick tylko członków z opt-in). Panel jest tutaj + * wyłącznie odczytowy: brak przełącznika zgody i trybu TV. + */ +export default function GymBoard() { + const { id } = useParams(); + const { t } = useTranslation('gyms'); + const [rangeDays, setRangeDays] = useState(30); + const { data, isLoading, error } = useGymBoard(id, rangeDays); + + useTopbar({ + // topbar = rodzic (lista siłowni); nazwa podstrony w PageHeader poniżej (h2) + title: t('common:nav.gyms'), + back: `/gyms/${id}`, + filters: [ + , + ], + filterActive: rangeDays !== 30, + }); + + if (isLoading) return ; + if (error || !data) { + return ( + <> + + + {t('common:errorPrefix')} + {(error as Error).message} + + + ); + } + + const { aggregate, ranking, records } = data; + + return ( +
+ {/* jeden wiersz: „Tablica" + nazwa siłowni (badge) + wstecz */} + + {data.gym.name} + + } + actions={} + /> + + {/* RANKING: skuteczne sesje w zakresie (nick po opt-in członka) */} + + + {ranking.length === 0 ? ( +

{t('board.emptyRanking')}

+ ) : ( +
    + {ranking.map((row, i) => { + const name = displayName(row); + return ( +
  1. + + {i + 1} + + + + {name} + + + {fmtVolume(row.tonnageKg)} ·{' '} + {t('common:counters.daysCount', { count: row.days })} + + + {t('common:counters.sessions', { count: row.sessions })} + +
  2. + ); + })} +
+ )} +
+ + {/* ZBIOROWOŚĆ: anonimowe agregaty wszystkich ćwiczących + ekwiwalenty tonażu */} + + +
+ + + +
+
+ {EQUIV_UNITS.map((u) => { + const count = equivCount(aggregate.tonnageKg, u.kg); + return ( +
+ {t(EQUIV_LABELS[u.id], { count })} + × {count} +
+ ); + })} +
+
+ + {/* PARTIE CIAŁA: serie i tonaż wg partii pierwotnej (współdzielony pasek + legenda) */} + + + {aggregate.muscles.length === 0 ? ( +

{t('board.emptyMuscles')}

+ ) : ( + + )} +
+ + {/* REKORDY 1RM: Epley z całej historii; autor tylko gdy wyraził zgodę */} + + + {records.length === 0 ? ( +

{t('board.emptyRecords')}

+ ) : ( +
+ {records.map((r, i) => ( + + ))} +
+ )} +
+
+ ); +} diff --git a/admin/src/pages/gyms/GymDetail.tsx b/admin/src/pages/gyms/GymDetail.tsx index 08f4613..fe8c35f 100644 --- a/admin/src/pages/gyms/GymDetail.tsx +++ b/admin/src/pages/gyms/GymDetail.tsx @@ -10,6 +10,7 @@ import { Settings, Star, Trash2, + Trophy, UserPlus, UserX, Users, @@ -248,6 +249,29 @@ function PresenceRow({ ); } +/* Kafelek Tablicy statystyk (tylko REAL): klik → podstrona tablicy (odczyt). */ +function BoardTile({ gymId }: { gymId: string }) { + const { t } = useTranslation('gyms'); + return ( + +
+
+
+ + {t('board.title')} + + + {t('board.tileHint')} + +
+ + ); +} + /* Kafelek Galerii (tylko REAL): mini-mozaika 4 miniatur + licznik; klik → podstrona galerii. */ function GalleryTile({ gym }: { gym: Gym }) { const { t } = useTranslation('gyms'); @@ -940,6 +964,8 @@ export default function GymDetail() {
+ {/* Tablica nad Bytnością: kafelek prowadzi na podstronę tablicy (odczyt) */} + {gym.kind === 'REAL' && } {gym.kind === 'REAL' && ( diff --git a/admin/test/GymBoard.test.tsx b/admin/test/GymBoard.test.tsx new file mode 100644 index 0000000..f2ff8ac --- /dev/null +++ b/admin/test/GymBoard.test.tsx @@ -0,0 +1,158 @@ +import { render, screen, fireEvent, 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'; +import GymBoard from '../src/pages/gyms/GymBoard'; +import { Topbar } from '../src/topbar'; +import { setAccessToken } from '../src/api/client'; +import type { GymBoardData } from '../src/api/types'; + +type Call = { url: string }; + +function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function boardBody(rangeDays: number): GymBoardData { + return { + gym: { id: 'g1', name: 'Gym A' }, + myStatsOptIn: null, + rangeDays, + ranking: [ + { + userId: 'u-ala', + nickname: 'żelazka', + firstName: 'Ala', + lastName: 'Nowak', + sessions: 8, + tonnageKg: 18200, + days: 6, + }, + { + userId: 'u-bob', + nickname: null, + firstName: 'Bob', + lastName: 'Kowal', + sessions: 5, + tonnageKg: 11000, + days: 4, + }, + ], + aggregate: { + tonnageKg: 42000, + sessions: 24, + uniqueExercisers: 9, + muscles: [ + { muscle: 'legs', sets: 40, volumeKg: 21000 }, + { muscle: 'chest', sets: 25, volumeKg: 9500 }, + ], + }, + records: [ + { + exerciseId: 'e-squat', + name: 'Przysiady', + nameEn: 'Squat', + muscle: 'legs', + oneRm: 140, + date: '2026-09-12T16:00:00.000Z', + author: { nickname: 'żelazka', firstName: 'Ala', lastName: 'Nowak' }, + }, + { + exerciseId: 'e-bench', + name: 'Wyciskanie leżąc', + nameEn: 'Bench press', + muscle: 'chest', + oneRm: 100, + date: '2026-08-30T16:00:00.000Z', + author: null, + }, + ], + }; +} + +function stubBoardFetch(calls: Call[]) { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + calls.push({ url }); + const range = Number(url.match(/board\?range=(\d+)/)?.[1] ?? 30); + if (url.includes('/gyms/g1/board')) return jsonResponse(200, boardBody(range)); + throw new Error(`Unexpected fetch: ${url}`); + }), + ); +} + +function renderBoard(path = '/gyms/g1/board') { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + detail
} /> + } /> + + + , + ); +} + +beforeEach(() => { + setAccessToken('admin-tok'); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('admin GymBoard — tablica siłowni (odczyt)', () => { + it('renders ranking, anonymous aggregates with equivalents and 1RM records', async () => { + stubBoardFetch([]); + renderBoard(); + + // jeden wiersz nagłówka: h2 „Tablica" + nazwa siłowni + expect(await screen.findByRole('heading', { name: 'Tablica', level: 2 })).toBeInTheDocument(); + expect(screen.getByText('Gym A')).toBeInTheDocument(); + + // ranking: nick z opt-in + nazwa bez nicka + const ranking = screen + .getByText('Ranking treningów') + .closest('[data-slot="card"]') as HTMLElement; + expect(within(ranking).getByText('żelazka')).toBeInTheDocument(); + expect(within(ranking).getByText('Bob Kowal')).toBeInTheDocument(); + + // zbiorowość anonimowa: tonaż 42 t + ekwiwalenty + const aggregate = screen + .getByText('Zbiorowość siłowni') + .closest('[data-slot="card"]') as HTMLElement; + expect(screen.getByText('42 t')).toBeInTheDocument(); + expect(screen.getByText('słoń afrykański (6 t)')).toBeInTheDocument(); + + // partie ciała: serie + tonaż + expect(screen.getByText('40 serii · 21 t')).toBeInTheDocument(); + + // rekordy: autor z opt-in po nicku, brak autora jako „anonim" + expect(screen.getByText('140 kg')).toBeInTheDocument(); + expect(screen.getByText(/anonim ·/)).toBeInTheDocument(); + }); + + it('panel jest read-only: brak przełącznika zgody; filtr zakresu refetchuje tablicę', async () => { + const calls: Call[] = []; + stubBoardFetch(calls); + renderBoard(); + + // w panelu admina nie ma opt-in nicka (to decyzja członka w apce) + expect(screen.queryByRole('switch')).not.toBeInTheDocument(); + + const select = screen.getByRole('combobox', { name: 'Zakres tablicy' }); + expect(select).toHaveValue('30'); + fireEvent.change(select, { target: { value: '7' } }); + await waitFor(() => + expect(calls.some((c) => c.url.includes('board?range=7'))).toBe(true), + ); + }); +}); diff --git a/admin/test/GymDetail.test.tsx b/admin/test/GymDetail.test.tsx index b4b8210..dcf293c 100644 --- a/admin/test/GymDetail.test.tsx +++ b/admin/test/GymDetail.test.tsx @@ -176,10 +176,16 @@ describe('admin GymDetail page', () => { // hero bez chipa miasta i karty „Dane" — zostają liczniki członków/urządzeń expect(screen.getByText('12 członków')).toBeInTheDocument(); - // kafelki sekcji prowadzą do podstron (galeria/urządzenia/ogłoszenia) + // kafelki sekcji prowadzą do podstron (galeria/urządzenia/ogłoszenia + tablica nad bytnością) expect(screen.getByRole('link', { name: /Galeria zdjęć/ })).toBeInTheDocument(); expect(screen.getByRole('link', { name: /Urządzenia/ })).toBeInTheDocument(); expect(screen.getByRole('link', { name: /Ogłoszenia/ })).toBeInTheDocument(); + const boardTile = screen.getByRole('link', { name: /Tablica/ }); + expect(boardTile).toHaveAttribute('href', '/gyms/g1/board'); + const presenceHeading = await screen.findByText('Bytność'); + expect( + boardTile.compareDocumentPosition(presenceHeading) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); // menu kontekstowe: JEDNA grupa „Zarządzaj” z akcjami strony (admin: + Właściciele) const config = useTopbarStore.getState().config;