From 1629068bf06df95572a0e3ffcecbe12b7ee102b0 Mon Sep 17 00:00:00 2001 From: tisachi Date: Tue, 27 Oct 2026 05:32:55 +0100 Subject: [PATCH] =?UTF-8?q?API+App+Admin:=20telemetria=20bytnosci=20w=20og?= =?UTF-8?q?olnym=20widoku=20sirowni=20-=20GET=20/gyms/:id/presence-stats?= =?UTF-8?q?=20(heatmapa=20dzien=C3=97godzina,=20sredni=20pobyt,=20wizyty/d?= =?UTF-8?q?zien,=20szczyt,=20teraz=20w=20srodku,=20top=20urzadzenia;=20sta?= =?UTF-8?q?le=2030=20dni),=20wspoldzielony=20komponent=20PresenceHeatmap,?= =?UTF-8?q?=20telemetria=20wyciagnieta=20z=20podstrony=20statystyk;=20pase?= =?UTF-8?q?k=20godzin=20w=20forma=20zegarowa=20z=20minutami,=20usuniete=20?= =?UTF-8?q?karta=20Dane=20i=20filtr=20okresu;=20swagger=20+=20testy=20inte?= =?UTF-8?q?gracyjne,=20unit=20i=20e2e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- admin/src/components/gyms/PresenceHeatmap.tsx | 74 +++++ admin/src/i18n/locales/en/gyms.json | 30 +- admin/src/i18n/locales/pl/gyms.json | 30 +- admin/src/lib/availability.ts | 10 + admin/src/pages/gyms/GymDetail.tsx | 283 +++++++---------- admin/src/styles.css | 17 ++ admin/test/GymDetail.test.tsx | 44 ++- admin/test/e2e/admin.spec.ts | 15 +- admin/test/e2e/presence.spec.ts | 9 +- api/src/routes/gyms.ts | 34 ++- api/src/services/presence.ts | 24 ++ api/src/swagger.ts | 21 ++ .../integration/gym-presence-stats.test.ts | 176 +++++++++++ app/src/api/queries.ts | 18 ++ app/src/api/types.ts | 17 ++ app/src/components/gyms/PresenceHeatmap.tsx | 74 +++++ app/src/i18n/locales/en/gyms.json | 21 +- app/src/i18n/locales/pl/gyms.json | 21 +- app/src/lib/availability.ts | 10 + app/src/pages/gyms/GymDetail.tsx | 285 ++++++++++-------- app/src/pages/gyms/GymStatsPage.tsx | 70 +---- app/src/styles.css | 17 ++ app/test/availability.test.ts | 15 + app/test/e2e/gym-stats.spec.ts | 18 +- app/test/e2e/gyms.spec.ts | 16 +- app/test/e2e/mock-api.ts | 25 ++ app/test/e2e/presence.spec.ts | 13 +- app/test/e2e/virtual-gyms.spec.ts | 12 +- app/test/gym-detail.test.tsx | 69 ++++- app/test/gym-stats.test.tsx | 4 +- 30 files changed, 965 insertions(+), 507 deletions(-) create mode 100644 admin/src/components/gyms/PresenceHeatmap.tsx create mode 100644 api/test/integration/gym-presence-stats.test.ts create mode 100644 app/src/components/gyms/PresenceHeatmap.tsx diff --git a/admin/src/components/gyms/PresenceHeatmap.tsx b/admin/src/components/gyms/PresenceHeatmap.tsx new file mode 100644 index 0000000..e08f1d9 --- /dev/null +++ b/admin/src/components/gyms/PresenceHeatmap.tsx @@ -0,0 +1,74 @@ +import { useTranslation } from 'react-i18next'; +import { dayName } from '../../lib/format'; +import { dayShort } from '../../lib/availability'; + +export interface PresenceHeatCell { + day: number; + hour: number; + count: number; +} + +/* Mapa ciepła bytności 7 (dzień 0=pon) × 24 (godzina) — natężenie ~ udział w szczycie, + styl kafli jak mapa urządzeń. Lustrzana kopia komponentu z app (identyczny widok + w obu pakietach). Etykiety dni skrócone (pełna nazwa w tytulu wiersza), siatka + skaluje się do szerokosci kolumny — bez minimalnej szerokosci i przewijania. */ +export function PresenceHeatmapGrid({ cells }: { cells: PresenceHeatCell[] }) { + const max = cells.reduce((m, c) => Math.max(m, c.count), 0); + return ( +
+
+ + {Array.from({ length: 24 }, (_, hour) => ( + + {hour % 3 === 0 ? String(hour).padStart(2, '0') : ''} + + ))} + {Array.from({ length: 7 }, (_, day) => ( + + ))} +
+
+ ); +} + +function HeatmapRow({ day, cells, max }: { day: number; cells: PresenceHeatCell[]; max: number }) { + const { t } = useTranslation('gyms'); + return ( + <> + + {dayShort(day)} + + {Array.from({ length: 24 }, (_, hour) => { + const cell = cells.find((c) => c.day === day && c.hour === hour); + const count = cell?.count ?? 0; + const intensity = max > 0 ? count / max : 0; + return ( + 0 + ? `color-mix(in srgb, var(--accent) ${Math.round(18 + intensity * 82)}%, var(--bg-input))` + : 'var(--bg-input)', + }} + /> + ); + })} + + ); +} diff --git a/admin/src/i18n/locales/en/gyms.json b/admin/src/i18n/locales/en/gyms.json index 0672061..7dfea57 100644 --- a/admin/src/i18n/locales/en/gyms.json +++ b/admin/src/i18n/locales/en/gyms.json @@ -79,7 +79,7 @@ "tilePhotos_other": "{{count}} photos", "tileAnnouncementsCount_one": "{{count}} announcement", "tileAnnouncementsCount_other": "{{count}} announcements", - "basicInfo": "Basic information", + "basicInfo": "Information", "groupGallery": "Gallery", "groupEquipment": "Equipment", "groupOwners": "Owners", @@ -115,19 +115,7 @@ "newAction": "New announcement" }, "equipmentDesc": "Machines and equipment available at this gym.", - "hours": "Opening hours", "exceptions": "Exceptions", - "data": "Details", - "kindLabel": "Type", - "kindReal": "Real", - "kindVirtual": "Virtual", - "privateLabel": "Private", - "capacityLabel": "Capacity", - "streetLabel": "Street", - "cityCodeLabel": "Code and city", - "countryLabel": "Country", - "locationLabel": "Location", - "ownersLabel": "Owners", "exceptionsTitle": "Schedule exceptions", "exceptionsDesc": "One-off changes for a specific day (closure or other hours).", "manageGallery": "Manage gallery", @@ -176,19 +164,15 @@ "presenceNow_other": "now: {{count}} people", "presenceFull": "full", "presence": { - "title": "Presence", - "desc": "Gym check-ins (QR code / “I'm working out” button).", - "empty": "No presence data in this period.", + "title": "Attendance", + "empty": "No check-ins in the last 30 days.", "live": "inside now", - "visitsRange": "visits ({{days}} days)", - "rangeAria": "Presence date range", - "rangeDays_one": "{{count}} day", - "rangeDays_other": "{{count}} days", + "visits": "visits (30 days)", "avgStay": "avg stay", "visitsPerDay": "visits/day", "peak": "hourly peak", "minutesShort": "min", - "heatmap": "When people show up (day × hour)", + "heatmap": "When they train (day × hour)", "topEquipment": "Most used equipment", "qrGroup": "QR", "qrAction": "QR code", @@ -198,5 +182,9 @@ "qrDownload": "Download PNG", "qrCopy": "Copy link", "qrCopied": "Copied" + }, + "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 7c9796d..2448523 100644 --- a/admin/src/i18n/locales/pl/gyms.json +++ b/admin/src/i18n/locales/pl/gyms.json @@ -85,7 +85,7 @@ "tileAnnouncementsCount_few": "{{count}} ogłoszenia", "tileAnnouncementsCount_many": "{{count}} ogłoszeń", "tileAnnouncementsCount_other": "{{count}} ogłoszeń", - "basicInfo": "Podstawowe informacje", + "basicInfo": "Informacje", "groupGallery": "Galeria", "groupEquipment": "Urządzenia", "groupOwners": "Właściciele", @@ -127,19 +127,7 @@ "newAction": "Nowe ogłoszenie" }, "equipmentDesc": "Maszyny i urządzenia dostępne w tej siłowni.", - "hours": "Godziny otwarcia", "exceptions": "Wyjątki", - "data": "Dane", - "kindLabel": "Rodzaj", - "kindReal": "Realna", - "kindVirtual": "Wirtualna", - "privateLabel": "Prywatna", - "capacityLabel": "Pojemność", - "streetLabel": "Ulica", - "cityCodeLabel": "Kod i miasto", - "countryLabel": "Kraj", - "locationLabel": "Lokalizacja", - "ownersLabel": "Właściciele", "exceptionsTitle": "Wyjątki w harmonogramie", "exceptionsDesc": "Jednorazowe zmiany na konkretny dzień (zamknięcie lub inne godziny).", "manageGallery": "Zarządzaj galerią", @@ -189,15 +177,9 @@ "presenceFull": "pełno", "presence": { "title": "Bytność", - "desc": "Meldunki na siłowni (kod QR / przycisk „Idę ćwiczyć”).", - "empty": "Brak danych bytności w tym okresie.", + "empty": "Brak meldunków w ostatnich 30 dniach.", "live": "teraz w środku", - "visitsRange": "wizyty ({{days}} dni)", - "rangeAria": "Zakres dat bytności", - "rangeDays_one": "{{count}} dzień", - "rangeDays_few": "{{count}} dni", - "rangeDays_many": "{{count}} dni", - "rangeDays_other": "{{count}} dni", + "visits": "wizyty (30 dni)", "avgStay": "śr. pobyt", "visitsPerDay": "wizyt/dzień", "peak": "rekord godzinowy", @@ -212,5 +194,11 @@ "qrDownload": "Pobierz PNG", "qrCopy": "Kopiuj link", "qrCopied": "Skopiowano" + }, + "stats": { + "cellTitle_one": "{{day}}, {{hour}}:00 — {{count}} wizyta", + "cellTitle_few": "{{day}}, {{hour}}:00 — {{count}} wizyty", + "cellTitle_many": "{{day}}, {{hour}}:00 — {{count}} wizyt", + "cellTitle_other": "{{day}}, {{hour}}:00 — {{count}} wizyt" } } diff --git a/admin/src/lib/availability.ts b/admin/src/lib/availability.ts index bf19d80..6cea689 100644 --- a/admin/src/lib/availability.ts +++ b/admin/src/lib/availability.ts @@ -75,3 +75,13 @@ export function shortTime(t: string): string { export function formatDayRange(day: DayAvailability): string { return `${shortTime(day.start)}–${shortTime(day.end)}`; } + +/** "06:00" -> "6:00" — minuty zawsze widoczne, usuwane tylko zero wiodące. */ +export function clockTime(t: string): string { + return t.replace(/^0/, ''); +} + +/** Zakres dnia z minutami do paska godzin, np. "6:00–22:00". */ +export function formatDayRangeClock(day: DayAvailability): string { + return `${clockTime(day.start)}–${clockTime(day.end)}`; +} diff --git a/admin/src/pages/gyms/GymDetail.tsx b/admin/src/pages/gyms/GymDetail.tsx index 82a9091..08f4613 100644 --- a/admin/src/pages/gyms/GymDetail.tsx +++ b/admin/src/pages/gyms/GymDetail.tsx @@ -7,7 +7,6 @@ import { Crown, Dumbbell, Image as ImageIcon, - MapPin, Settings, Star, Trash2, @@ -20,6 +19,7 @@ import { useTopbar, type TopbarCustomGroup } from '../../topbar'; import { api } from '../../api/client'; import { AuthImage } from '../../components/AuthImage'; import GymQrModal from '../../components/gyms/GymQrModal'; +import { PresenceHeatmapGrid } from '../../components/gyms/PresenceHeatmap'; import { UserPicker } from '../../components/UserPicker'; import { AddressFields, addressPayload, isAddressComplete } from '../../components/AddressFields'; import { useAdminUsers } from '../users/user-queries'; @@ -63,11 +63,11 @@ import { AvailabilityEditor } from '../../components/AvailabilityEditor'; import { dayFull, dayShort, - formatDayRange, + formatDayRangeClock, normalizeAvailability, TIME_SLOTS, } from '../../lib/availability'; -import { fmtDate, fmtDateTime, fmtNumber } from '../../lib/format'; +import { fmtDate, fmtDateTime } from '../../lib/format'; /* Godziny otwarcia w całym wierszu pod hero — lustrzany widok jak w apce (informacja kluczowa, więc nie w kolumnie bocznej). Pasek tygodnia wzorowany na kartach listy: @@ -85,10 +85,9 @@ function HoursBand({ gym }: { gym: Gym }) { const hasHours = availability.some(Boolean); if (!hasHours && exceptions.length === 0) return null; return ( - + {hasHours && ( <> -
{availability.map((day, i) => (
- {/* telefon: skrót dnia + zwarty zakres; desktop: pełna nazwa + pełne godziny */} - {dayShort(i)} - - {dayFull(i)} - {i === todayIdx && ( - - {t('today')} - - )} + {/* pelna nazwa dnia tylko gdy miesci sie w kolumnie (container query karty), + ponizej skrot; minuty godzin sa zawsze widoczne — ponizej @3xl zakres + lamie sie do dwoch linii zamiast byc przycinany lub gubic minuty; + badge „dziś" rownolegle obok nazwy (od @2xl), nie osobna linia */} + + {dayShort(i)} + {dayFull(i)} + {i === todayIdx && ( + + {t('today')} + + )}
- {day ? formatDayRange(day) : '—'} - - {day ? `${day.start}–${day.end}` : t('closed')} + + {day ? formatDayRangeClock(day) : '—'} + + + {day ? formatDayRangeClock(day) : t('closed')}
@@ -174,44 +178,28 @@ function PresenceTelemetry({ gymId, rangeDays }: { gymId: string; rangeDays: num } return (
-
- {[ - { label: t('presence.live'), value: String(s.live) }, - { label: t('presence.visitsRange', { days: rangeDays }), value: String(s.visits) }, - { - label: t('presence.avgStay'), - value: - s.avgStayMinutes != null ? `${s.avgStayMinutes} ${t('presence.minutesShort')}` : '—', - }, - { label: t('presence.peak'), value: String(s.peak) }, - { label: t('presence.visitsPerDay'), value: fmtNumber(s.visitsPerDay) }, - ].map((k) => ( -
- {k.label} - {k.value} -
- ))} -
- {s.heatmap.length > 0 && ( -
+
{t('presence.heatmap')}
-
- {Array.from({ length: 7 }, (_, day) => ( - - ))} -
+
)} + {/* Metryki: etykieta lewa, wartość prawa — zwarta lista mieści się w każdym metrażu. */} +
+ 0} /> + + + + +
+ {s.topEquipment.length > 0 && (
@@ -233,31 +221,30 @@ function PresenceTelemetry({ gymId, rangeDays }: { gymId: string; rangeDays: num ); } -/* Wiersz heatmapy: etykieta dnia + 24 kafle godziny (kolor ~ natężenie). */ -function FragmentRow({ day, stats }: { day: number; stats: GymPresenceStatsResponse['stats'] }) { +/* Wiersz metryki bytności: etykieta po lewej, wartość (opcjonalna jednostka) po prawej. */ +function PresenceRow({ + label, + value, + unit, + live, +}: { + label: string; + value: string; + unit?: string; + live?: boolean; +}) { return ( - <> - - {dayFull(day).slice(0, 2)} - - {Array.from({ length: 24 }, (_, hour) => { - const cell = stats.heatmap.find((h) => h.day === day && h.hour === hour); - const intensity = cell && stats.peak > 0 ? cell.count / stats.peak : 0; - return ( - 0 - ? `color-mix(in srgb, var(--accent) ${Math.round(18 + intensity * 82)}%, var(--bg-input))` - : 'var(--bg-input)', - }} - /> - ); - })} - +
+
{label}
+
+ {value} + {unit && {` ${unit}`}} +
+
); } @@ -271,9 +258,9 @@ function GalleryTile({ gym }: { gym: Gym }) { to={`/gyms/${gym.id}/gallery`} className="flex flex-col rounded-2xl border border-line bg-card p-3 transition-colors hover:border-accent/55" > -
+
{preview.length === 0 ? ( -
+
) : ( @@ -305,20 +292,35 @@ function EquipmentTile({ gym }: { gym: Gym }) { to={`/gyms/${gym.id}/equipment`} className="flex flex-col rounded-2xl border border-line bg-card p-3 transition-colors hover:border-accent/55" > -
+
{preview.length === 0 ? ( -
+
) : ( - preview.map((e) => ( - - {formatGymEquipment(e, i18n.language)} - - )) + preview.map((e) => { + const photo = e.photos?.[0]; + return ( +
+ {photo ? ( +
+ +
+ ) : ( +
+
+ )} + + {formatGymEquipment(e, i18n.language)} + +
+ ); + }) )}
@@ -333,8 +335,8 @@ function EquipmentTile({ gym }: { gym: Gym }) { ); } -/* Kafelek Ogłoszeń: najnowsze ogłoszenie (tytuł + data) lub pusty stan + licznik; klik → podstrona. */ -function AnnouncementsTile({ gymId }: { gymId: string }) { +/* Kafelek Ogłoszeń (pełny wiersz): lista 3 najnowszych (tytuł + data) lub pusty stan + licznik; klik → podstrona. */ +function AnnouncementsTile({ gymId, className }: { gymId: string; className?: string }) { const { t } = useTranslation('gyms'); const { data } = useQuery({ queryKey: ['admin-announcements', gymId], @@ -344,20 +346,24 @@ function AnnouncementsTile({ gymId }: { gymId: string }) { ), }); const announcements = data?.announcements ?? []; - const latest = announcements[0]; return ( -
- {latest ? ( - <> - {latest.title} - - {fmtDateTime(latest.createdAt)} - - +
+ {announcements.length > 0 ? ( + announcements.slice(0, 3).map((a) => ( +
+ {a.title} + + {fmtDateTime(a.createdAt)} + +
+ )) ) : ( {t('noAnnouncements')} )} @@ -776,7 +782,6 @@ export default function GymDetail() { const [editOpen, setEditOpen] = useState(false); const [ownersOpen, setOwnersOpen] = useState(false); const [qrOpen, setQrOpen] = useState(false); - const [presenceRange, setPresenceRange] = useState(30); const [confirmOpen, setConfirmOpen] = useState(false); const [busy, setBusy] = useState(false); @@ -808,7 +813,8 @@ export default function GymDetail() { id: 'manage', label: t('groupManage'), icon: Settings, - // na lg+ zwinięta do jednej kontrolki „Zarządzaj” (dropdown) — nie inline + // akcje nigdy luzem na pasku: desktop = „Zarządzaj” + dropdown, tablet = zębatka + // rozwijająca się do „Zarządzaj”, telefon = zębatka w dolnym pasku z pełną listą collapsed: true, actions: [ { label: t('basicInfo'), onClick: () => setEditOpen(true) }, @@ -835,28 +841,6 @@ export default function GymDetail() { title: t('common:nav.gyms'), back: '/gyms', groups, - // okres telemetrii bytności (grupa filtrów) — tylko REAL - ...(gym?.kind === 'REAL' - ? { - filterActive: presenceRange !== 30, - filters: [ - , - ], - } - : {}), }); if (isLoading) return ; @@ -876,10 +860,6 @@ export default function GymDetail() { ); } - const ownerNames = (gym.owners ?? []).map( - (o) => [o.firstName, o.lastName].filter(Boolean).join(' ') || o.email, - ); - return ( <> {/* HERO: okładka (zdjęcie lub placeholder) + nazwa + chipy metadanych */} @@ -921,10 +901,6 @@ export default function GymDetail() { {gym.name}
- - - {gym.location || '—'} - {t('common:counters.members', { count: gym._count?.memberships ?? 0 })} @@ -952,59 +928,24 @@ export default function GymDetail() { {/* GODZINY: cały wiersz bezpośrednio pod hero (jak w apce) */} - {/* DWIE KOLUMNY: kafelki sekcji (klik → podstrony) + karta danych */} + {/* DWIE KOLUMNY: kafelki sekcji (klik → podstrony) + karta bytności (jak w apce) */}
-
+ {/* wiersz 1: galeria + urządzenia obok siebie; wiersz 2: ogłoszenia na całą szerokość */} +
{gym.kind === 'REAL' && } - +
{gym.kind === 'REAL' && ( - - + + )} - - -
- {t('kindLabel')} - {gym.kind === 'REAL' ? t('kindReal') : t('kindVirtual')} - {t('privateLabel')} - {gym.isPrivate ? t('common:yes') : t('common:no')} - {t('capacityLabel')} - {gym.capacity ?? '—'} - {gym.addressLine1 || gym.postalCode || gym.city ? ( - <> - {t('streetLabel')} - {[gym.addressLine1, gym.addressLine2].filter(Boolean).join(', ') || '—'} - {t('cityCodeLabel')} - {[gym.postalCode, gym.city].filter(Boolean).join(' ') || '—'} - {gym.countryCode && gym.countryCode !== 'PL' && ( - <> - {t('countryLabel')} - {gym.countryCode} - - )} - - ) : ( - <> - {t('locationLabel')} - {gym.location ?? '—'} - - )} - {t('ownersLabel')} - {ownerNames.length > 0 ? ownerNames.join(', ') : '—'} -
-
diff --git a/admin/src/styles.css b/admin/src/styles.css index b71bce5..0f06445 100644 --- a/admin/src/styles.css +++ b/admin/src/styles.css @@ -318,6 +318,23 @@ } } +/* Selecty w stylu aplikacji: natywna strzałka OS przylega do prawej ścianki — + własna (appearance:none + chevron w tle) odsunięta od krawędzi; poza + warstwami Tailwinda, więc padding-right wygrywa z px-3 komponentu */ +select[data-slot='select'] { + appearance: none; + -webkit-appearance: none; + padding-right: 2.25rem; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23a9b0ba' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 0.65rem center; + background-size: 1rem 1rem; +} + +.light select[data-slot='select'] { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%235f6772' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E"); +} + /* Checkbox w stylu aplikacji: ciemne pole z krawędzią; po zaznaczeniu wypełnienie akcentem i ciemny „ptaszek" (look kontrolowany przez design, nie przez natywne widgety OS) */ diff --git a/admin/test/GymDetail.test.tsx b/admin/test/GymDetail.test.tsx index 7dd4574..b4b8210 100644 --- a/admin/test/GymDetail.test.tsx +++ b/admin/test/GymDetail.test.tsx @@ -103,8 +103,7 @@ function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) { }, }); if (url.includes('/admin/users')) return jsonResponse(200, { users: [U1] }); - if (url.includes('/admin/announcements')) - return jsonResponse(200, { announcements: [] }); + if (url.includes('/admin/announcements')) return jsonResponse(200, { announcements: [] }); if (url.includes('/equipment-usage')) return jsonResponse(200, { equipment: [ @@ -174,12 +173,8 @@ describe('admin GymDetail page', () => { stubGymFetch(); renderGymDetail(); expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); - // hero pokazuje location (string derivowany), karta Dane pokazuje adres strukturalny - expect(screen.getByText('Polna 4, 00-001 Warszawa')).toBeInTheDocument(); - expect(screen.getByText('Polna 4', { exact: true })).toBeInTheDocument(); - expect(screen.getByText('00-001 Warszawa')).toBeInTheDocument(); + // hero bez chipa miasta i karty „Dane" — zostają liczniki członków/urządzeń expect(screen.getByText('12 członków')).toBeInTheDocument(); - expect(screen.getByText('Anna Kowalska')).toBeInTheDocument(); // kafelki sekcji prowadzą do podstron (galeria/urządzenia/ogłoszenia) expect(screen.getByRole('link', { name: /Galeria zdjęć/ })).toBeInTheDocument(); @@ -189,10 +184,10 @@ describe('admin GymDetail page', () => { // menu kontekstowe: JEDNA grupa „Zarządzaj” z akcjami strony (admin: + Właściciele) const config = useTopbarStore.getState().config; expect(config?.groups?.map((g) => g.id)).toEqual(['manage']); - // na lg+ grupa zwinięta do jednej kontrolki (opcja collapsed) + // akcje nigdy luzem na pasku — zebrane w kontrolce „Zarządzaj” (collapsed) expect(config?.groups?.[0]?.collapsed).toBe(true); expect(config?.groups?.[0]?.actions?.map((a) => a.label)).toEqual([ - 'Podstawowe informacje', + 'Informacje', 'Galeria', 'Kod QR', 'Urządzenia', @@ -289,33 +284,28 @@ describe('admin GymDetail page', () => { expect(await screen.findByText('Bytność')).toBeInTheDocument(); expect(screen.getByText('teraz w środku')).toBeInTheDocument(); expect(screen.getByText('40')).toBeInTheDocument(); // wizyty (30 dni) - expect(screen.getByText('62 min')).toBeInTheDocument(); - expect(screen.getByText('1,3')).toBeInTheDocument(); // wizyt/dzień (Intl PL) + expect( + screen.getByText((_, el) => el?.tagName === 'DD' && el.textContent === '62 min'), + ).toBeInTheDocument(); + expect(screen.getByText('1.3')).toBeInTheDocument(); // wizyt/dzień (jak w apce: surowa wartość) expect(screen.getByText('sztanga · 12')).toBeInTheDocument(); }); - it('filtr okresu w menu kontekstowym pyta presence-stats z from dla 7 dni', async () => { + it('telemetria bytności pyta presence-stats ze stałego zakresu 30 dni (bez filtra okresu)', async () => { const calls = stubGymFetch(); renderGymDetail(); expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); await screen.findByText('teraz w środku'); - // filtr okresu telemetrii jest w grupie lejka - fireEvent.click(screen.getByRole('button', { name: 'Filtry' })); - fireEvent.change(screen.getByRole('combobox', { name: 'Zakres dat bytności' }), { - target: { value: '7' }, - }); + // brak filtra okresu w topbarze — widok ogólny zawsze 30 dni + expect(screen.queryByRole('combobox', { name: 'Zakres dat bytności' })).not.toBeInTheDocument(); - await waitFor(() => { - const last = calls - .filter((c) => c.url.includes('presence-stats')) - .at(-1); - expect(last).toBeTruthy(); - const from = new Date(String(new URL(`http://x${last!.url}`).searchParams.get('from'))); - const days = (Date.now() - from.getTime()) / 86_400_000; - expect(days).toBeGreaterThan(5); - expect(days).toBeLessThan(9); - }); + const last = calls.filter((c) => c.url.includes('presence-stats')).at(-1); + expect(last).toBeTruthy(); + const from = new Date(String(new URL(`http://x${last!.url}`).searchParams.get('from'))); + const days = (Date.now() - from.getTime()) / 86_400_000; + expect(days).toBeGreaterThan(28); + expect(days).toBeLessThan(32); }); it('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async () => { diff --git a/admin/test/e2e/admin.spec.ts b/admin/test/e2e/admin.spec.ts index b405f6d..0358404 100644 --- a/admin/test/e2e/admin.spec.ts +++ b/admin/test/e2e/admin.spec.ts @@ -25,9 +25,8 @@ test('kliknięcie w siłownię otwiera podstronę z detalami', async ({ page }) await page.getByRole('link', { name: 'Fit Factory' }).click(); await expect(page).toHaveURL(/\/gyms\/gym-1$/); await expect(page.getByRole('heading', { name: 'Fit Factory' })).toBeVisible(); - // pasek godzin w całym wierszu pod hero (widok odczytu jak w apce) + wyjątek harmonogramu - await expect(page.getByRole('heading', { name: 'Godziny otwarcia' })).toBeVisible(); - await expect(page.getByText('06:00–22:00')).toBeVisible(); + // pasek godzin pod hero: forma zegarowa z minutami + wyjątek harmonogramu + await expect(page.locator('span:visible', { hasText: '6:00–22:00' })).toBeVisible(); await expect(page.getByText('10:00–14:00')).toBeVisible(); // menu kontekstowe podstrony detalu nie dziedziczy akcji ze strony listy (brak ikony ➕) await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible(); @@ -42,7 +41,7 @@ test('ponowne dodanie tego samego typu tworzy osobną instancję (bez inkrementa await expect(page).toHaveURL(/\/gyms\/gym-1$/); await expect(page.getByText('Dywan ×3')).toBeVisible(); - // akcja „Urządzenia" (grupa „Zarządzaj” na lg+ zwinięta do kontrolki → dropdown) → podstrona urządzeń; edycja modalem z menu + // akcja „Urządzenia" w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje) → podstrona urządzeń; edycja modalem z menu await page.getByRole('button', { name: 'Zarządzaj' }).click(); await page.getByRole('button', { name: 'Urządzenia' }).click(); await expect(page).toHaveURL(/\/gyms\/gym-1\/equipment$/); @@ -64,7 +63,7 @@ test('dodanie urządzenia z własnymi parametrami wysyła spec w POST', async ({ mockApi(page, { gyms: { gyms: [TEST_GYM] } }); await loginAsAdmin(page); await page.getByRole('link', { name: 'Fit Factory' }).click(); - // akcja „Urządzenia" (grupa na lg+ zwinięta → dropdown) → podstrona urządzeń; edycja modalem z menu + // akcja „Urządzenia" w rozwijanym „Zarządzaj” → podstrona urządzeń; edycja modalem z menu await page.getByRole('button', { name: 'Zarządzaj' }).click(); await page.getByRole('button', { name: 'Urządzenia' }).click(); await expect(page).toHaveURL(/\/gyms\/gym-1\/equipment$/); @@ -89,10 +88,8 @@ test('admin zarządza właścicielami siłowni z menu kontekstowego', async ({ p await page.getByRole('link', { name: 'Fit Factory' }).click(); await expect(page).toHaveURL(/\/gyms\/gym-1$/); - // właściciel widoczny w sekcji Dane - await expect(page.getByText('Anna Kowalska')).toBeVisible(); - - // modal Właściciele z grupy w menu kontekstowym (na lg+ zwiniętej do kontrolki → dropdown) + // modal Właściciele z rozwijanego „Zarządzaj” (desktop: kontrolka zbiera akcje) + // (karta „Dane" usunięta — lista właścicieli dostępna tylko w modalu) await page.getByRole('button', { name: 'Zarządzaj' }).click(); await page.locator('button[data-slot="button"]', { hasText: 'Właściciele' }).click(); const dialog = page.getByRole('dialog'); diff --git a/admin/test/e2e/presence.spec.ts b/admin/test/e2e/presence.spec.ts index 183892d..323c42b 100644 --- a/admin/test/e2e/presence.spec.ts +++ b/admin/test/e2e/presence.spec.ts @@ -30,15 +30,12 @@ test('detal REAL pokazuje kartę bytności z telemetrią', async ({ page }) => { await expect(page.getByText('ławka · 41')).toBeVisible(); }); -test('filtr okresu telemetrii zmienia etykietę wizyt', async ({ page }) => { +test('widok ogólny bytności ma stały zakres 30 dni (bez filtra okresu)', async ({ page }) => { mockApi(page, { gyms: { gyms: [TEST_GYM] } }); await loginAsAdmin(page); await page.getByRole('link', { name: 'Fit Factory' }).click(); await expect(page.getByText('wizyty (30 dni)')).toBeVisible(); - - // na lg+ treść grupy filtrów renderuje się inline w nagłówku (bez klikania lejka) - await page.getByRole('combobox', { name: 'Zakres dat bytności' }).selectOption('7'); - await expect(page.getByText('wizyty (7 dni)')).toBeVisible(); + await expect(page.getByRole('combobox', { name: 'Zakres dat bytności' })).toHaveCount(0); }); test('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', async ({ page }) => { @@ -47,7 +44,7 @@ test('akcja „Kod QR” otwiera modal z kodem i linkiem do strony check-inu', a await page.getByRole('link', { name: 'Fit Factory' }).click(); await expect(page).toHaveURL(/\/gyms\/gym-1$/); - // grupa „Zarządzaj” na lg+ zwinięta do kontrolki → dropdown + // akcja „Kod QR” w rozwijanym „Zarządzaj” (desktop: kontrolka zbiera akcje) await page.getByRole('button', { name: 'Zarządzaj' }).click(); await page.getByRole('button', { name: 'Kod QR' }).click(); const dialog = page.getByRole('dialog'); diff --git a/api/src/routes/gyms.ts b/api/src/routes/gyms.ts index e8c09ad..32bb177 100644 --- a/api/src/routes/gyms.ts +++ b/api/src/routes/gyms.ts @@ -16,7 +16,12 @@ import { } from '../services/gyms.js'; import { logActivity } from '../services/audit.js'; import { asyncHandler } from '../lib/asyncHandler.js'; -import { checkIn, getEquipmentUsage, getGymStatsOverview } from '../services/presence.js'; +import { + checkIn, + getEquipmentUsage, + getGymPresenceTelemetry, + getGymStatsOverview, +} from '../services/presence.js'; import { rangeQuerySchema, resolveRange } from './presence.js'; import { checkInSchema, createGymSchema, rateGymSchema, updateGymSchema } from './gyms/schemas.js'; import { createGymClaimRoutes } from './gyms/claims.js'; @@ -170,6 +175,33 @@ export function createGymRoutes(deps: AppDeps) { }), ); + /** + * @openapi + * /gyms/{gymId}/presence-stats: + * get: + * summary: Presence telemetry of a gym (general view) — day×hour heatmap, avg stay, visits/day, peak, live, top equipment (default range: last 30 days). REAL visible to all logged-in users, VIRTUAL to managers (empty — presence is REAL only) + * tags: [Gyms] + * parameters: + * - { in: query, name: from, schema: { type: string, format: date-time } } + * - { in: query, name: to, schema: { type: string, format: date-time } } + * responses: + * 200: { description: "OK, returns { gym, stats: { visits, avgStayMinutes, heatmap, topGyms, peak, topEquipment, live, visitsPerDay } }" } + * 403: { description: VIRTUAL gym and the caller is not a manager } + * 404: { description: Gym not found } + */ + router.get( + '/:gymId/presence-stats', + validate(rangeQuerySchema, 'query'), + asyncHandler(async (req, res) => { + const query = req.query as z.infer; + const result = await getGymPresenceTelemetry(prisma, req.params.gymId, resolveRange(query), { + userId: req.user!.id, + isAdmin: req.user!.isAdmin, + }); + res.json(result); + }), + ); + /** * @openapi * /gyms/{gymId}/stats/overview: diff --git a/api/src/services/presence.ts b/api/src/services/presence.ts index ec4d88d..c41cb92 100644 --- a/api/src/services/presence.ts +++ b/api/src/services/presence.ts @@ -439,6 +439,30 @@ export async function getGymStats( }; } +/** + * Telemetria bytności dla widoku ogólnego siłowni (aplikacja): dostęp jak + * mapa urządzeń — REAL: każdy zalogowany; VIRTUAL: tylko menedżer (OWNER) lub + * admin (puste statystyki — bytność istnieje tylko dla REAL). 404 gdy brak siłowni. + */ +export async function getGymPresenceTelemetry( + prisma: PrismaClient, + gymId: string, + range: Required, + caller: { userId: string; isAdmin: boolean }, +) { + const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } }); + if (!gym) throw notFound('Gym not found'); + if (gym.kind !== 'REAL' && !caller.isAdmin) { + const membership = await prisma.gymMembership.findUnique({ + where: { userId_gymId: { userId: caller.userId, gymId } }, + select: { roles: true }, + }); + if (!membership?.roles.includes('OWNER')) + throw forbidden('You do not have access to this gym'); + } + return getGymStats(prisma, gymId, range); +} + /** * Przegląd statystyk właściciela siłowni (tylko REAL): telemetria bytności * (bez top urządzeń — jest na podstronie urządzeń) + członkowie i napływ + diff --git a/api/src/swagger.ts b/api/src/swagger.ts index 8044448..4b7c079 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -588,6 +588,27 @@ export const openapi: Record = { }, }, }, + '/gyms/{gymId}/presence-stats': { + get: { + tags: ['Gyms'], + summary: + 'Presence telemetry of a gym (general view): day×hour heatmap, avg stay, visits/day, peak, live, top equipment. REAL visible to all logged-in users; VIRTUAL to managers only (empty — presence is REAL only). Default range: last 30 days', + security: [{ bearerAuth: [] }], + parameters: [ + { name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }, + { name: 'from', in: 'query', schema: { type: 'string', format: 'date-time' } }, + { name: 'to', in: 'query', schema: { type: 'string', format: 'date-time' } }, + ], + responses: { + 200: { + description: + 'OK, returns { gym, stats: { visits, avgStayMinutes, heatmap: [{ day, hour, count }], topGyms, peak, topEquipment, live, visitsPerDay } }', + }, + 403: { description: 'VIRTUAL gym and the caller is not a manager' }, + 404: { description: 'Gym not found' }, + }, + }, + }, '/gyms/{gymId}/stats/overview': { get: { tags: ['Gyms'], diff --git a/api/test/integration/gym-presence-stats.test.ts b/api/test/integration/gym-presence-stats.test.ts new file mode 100644 index 0000000..fa616da --- /dev/null +++ b/api/test/integration/gym-presence-stats.test.ts @@ -0,0 +1,176 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { prisma } from '../../src/lib/prisma.js'; +import { buildApp, createUserWithToken, rand } from '../helpers.js'; + +interface PresenceStatsBody { + gym: { id: string; name: string; kind: string; capacity: number | null }; + stats: { + visits: number; + avgStayMinutes: number | null; + heatmap: { day: number; hour: number; count: number }[]; + topGyms: unknown[]; + peak: number; + topEquipment: unknown[]; + live: number; + visitsPerDay: number; + }; +} + +describe('gym presence-stats — telemetria bytności (widok ogólny)', () => { + let ownerId: string; + let ownerToken: string; + let strangerToken: string; + let adminToken: string; + + const gymIds: string[] = []; + const presenceIds: string[] = []; + + beforeAll(async () => { + const owner = await createUserWithToken(); + ownerId = owner.user.id; + ownerToken = owner.token; + const stranger = await createUserWithToken(); + strangerToken = stranger.token; + const admin = await createUserWithToken({ isAdmin: true }); + adminToken = admin.token; + }); + + afterAll(async () => { + await prisma.gymPresence + .deleteMany({ where: { gymId: { in: gymIds } } }) + .catch(() => undefined); + await prisma.gymMembership + .deleteMany({ where: { gymId: { in: gymIds } } }) + .catch(() => undefined); + await prisma.gym.deleteMany({ where: { id: { in: gymIds } } }).catch(() => undefined); + }); + + async function createRealGym() { + const gym = await prisma.gym.create({ + data: { name: `Presence Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' }, + }); + gymIds.push(gym.id); + await prisma.gymMembership.create({ + data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] }, + }); + return gym; + } + + async function createVirtualGym() { + const gym = await prisma.gym.create({ + data: { name: `Presence Virtual ${rand()}`, kind: 'VIRTUAL' }, + }); + gymIds.push(gym.id); + await prisma.gymMembership.create({ + data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] }, + }); + return gym; + } + + /** Bytność CLOSED [checkedInAt, +2h] — deterministyczne kafle godzinowe. */ + async function seedPresence(userId: string, gymId: string, checkedInAt: Date) { + const closedAt = new Date(checkedInAt.getTime() + 2 * 60 * 60 * 1000); + const row = await prisma.gymPresence.create({ + data: { + userId, + gymId, + status: 'CLOSED', + checkedInAt, + lastActivityAt: closedAt, + closedAt, + }, + }); + presenceIds.push(row.id); + } + + function baseAt(daysAgo: number): Date { + const base = new Date(Date.now() - daysAgo * 86_400_000); + base.setHours(13, 5, 0, 0); + return base; + } + + it('REAL: statystyki dostępne dla każdego zalogowanego (heatmapa + KPI)', async () => { + const app = buildApp(); + const gym = await createRealGym(); + const visitor = await createUserWithToken(); + + const dayA = baseAt(5); + const dayB = new Date(dayA.getTime() + 86_400_000); + await seedPresence(visitor.user.id, gym.id, dayA); + await seedPresence(ownerId, gym.id, dayB); + // bytność poza domyślnym zakresem 30 dni nie liczy się + await seedPresence(visitor.user.id, gym.id, baseAt(40)); + + const res = await app + .get(`/api/v1/gyms/${gym.id}/presence-stats`) + .set('Authorization', `Bearer ${strangerToken}`); + expect(res.status).toBe(200); + const body = res.body as PresenceStatsBody; + expect(body.gym).toMatchObject({ id: gym.id, kind: 'REAL' }); + expect(body.stats.visits).toBe(2); + expect(body.stats.peak).toBe(1); + expect(body.stats.live).toBe(0); + // heatmapa: dokładnie dwie wizyty w godzinie 13, dni zgodne z datami (0=pon) + expect(body.stats.heatmap).toHaveLength(2); + for (const cell of body.stats.heatmap) { + expect(cell.hour).toBe(13); + expect(cell.count).toBe(1); + } + expect(body.stats.heatmap.map((c) => c.day).sort()).toEqual( + [dayA, dayB].map((d) => (d.getDay() + 6) % 7).sort(), + ); + // śr. pobyt = 120 min; wizyt/dzień za 30 dni ≈ 0.1 + expect(body.stats.avgStayMinutes).toBe(120); + expect(body.stats.visitsPerDay).toBe(0.1); + }); + + it('REAL: filtr from zawęża zakres', async () => { + const app = buildApp(); + const gym = await createRealGym(); + await seedPresence(ownerId, gym.id, baseAt(10)); + + const from = new Date(Date.now() - 2 * 86_400_000).toISOString(); + const narrowed = await app + .get(`/api/v1/gyms/${gym.id}/presence-stats?from=${encodeURIComponent(from)}`) + .set('Authorization', `Bearer ${strangerToken}`); + expect(narrowed.status).toBe(200); + expect((narrowed.body as PresenceStatsBody).stats.visits).toBe(0); + expect((narrowed.body as PresenceStatsBody).stats.heatmap).toEqual([]); + }); + + it('404 dla nieistniejącej siłowni', async () => { + const app = buildApp(); + const missing = await app + .get('/api/v1/gyms/does-not-exist/presence-stats') + .set('Authorization', `Bearer ${strangerToken}`); + expect(missing.status).toBe(404); + }); + + it('VIRTUAL: stranger 403, właściciel i admin dostają puste statystyki', async () => { + const app = buildApp(); + const virtual = await createVirtualGym(); + + const denied = await app + .get(`/api/v1/gyms/${virtual.id}/presence-stats`) + .set('Authorization', `Bearer ${strangerToken}`); + expect(denied.status).toBe(403); + + const byOwner = await app + .get(`/api/v1/gyms/${virtual.id}/presence-stats`) + .set('Authorization', `Bearer ${ownerToken}`); + expect(byOwner.status).toBe(200); + expect((byOwner.body as PresenceStatsBody).stats.visits).toBe(0); + + const byAdmin = await app + .get(`/api/v1/gyms/${virtual.id}/presence-stats`) + .set('Authorization', `Bearer ${adminToken}`); + expect(byAdmin.status).toBe(200); + expect((byAdmin.body as PresenceStatsBody).stats.visits).toBe(0); + }); + + it('wymaga autoryzacji (401 bez tokenu)', async () => { + const app = buildApp(); + const anon = await app.get('/api/v1/gyms/any/presence-stats'); + expect(anon.status).toBe(401); + }); +}); diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index 6c5e100..2e78166 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -41,6 +41,7 @@ import type { GymContactView, GymInvitation, GymKind, + GymPresenceStatsResponse, GymStatsOverview, VirtualGym, Trainee, @@ -221,6 +222,23 @@ export function deleteGymContactMessage(messageId: string) { return api(`/gym-contact/messages/${encodeURIComponent(messageId)}`, { method: 'DELETE' }); } +/** + * Telemetria bytności (widok ogólny siłowni REAL): heatmapa dzień×godzina + KPI. + * Stały okres 30 dni — bez filtra na widoku ogólnym (rozwinięcie: statystyki właściciela). + */ +export function useGymPresenceStats(gymId: string | undefined, rangeDays = 30) { + return useQuery({ + queryKey: ['gym-presence-stats', gymId, rangeDays], + queryFn: () => { + const from = new Date(Date.now() - rangeDays * 86_400_000).toISOString(); + return api( + `/gyms/${gymId}/presence-stats?from=${encodeURIComponent(from)}`, + ); + }, + enabled: !!gymId, + }); +} + /** * Statystyki właściciela (REAL): presence + członkowie + aktywność treningowa. * `rangeDays`: 7/30/90, from liczony od teraz (jak mapa ciepła urządzeń). diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 267d35d..32e3b65 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -353,6 +353,23 @@ export interface GymContactThread { canReply: boolean; } +// ---------- bytność (GET /gyms/:id/presence-stats, REAL — widok ogólny) ---------- +export interface GymPresenceStatsData { + visits: number; + avgStayMinutes: number | null; + heatmap: { day: number; hour: number; count: number }[]; + topGyms: { gymId: string; gymName: string; visits: number }[]; + peak: number; + topEquipment: { equipmentId: string; name: string; nameEn: string | null; count: number }[]; + live: number; + visitsPerDay: number; +} + +export interface GymPresenceStatsResponse { + gym: { id: string; name: string; kind: GymKind; capacity: number | null }; + stats: GymPresenceStatsData; +} + // ---------- statystyki właściciela (GET /gyms/:id/stats/overview, REAL) ---------- export interface GymStatsOverview { gym: { id: string; name: string; kind: GymKind; capacity: number | null }; diff --git a/app/src/components/gyms/PresenceHeatmap.tsx b/app/src/components/gyms/PresenceHeatmap.tsx new file mode 100644 index 0000000..524865f --- /dev/null +++ b/app/src/components/gyms/PresenceHeatmap.tsx @@ -0,0 +1,74 @@ +import { useTranslation } from 'react-i18next'; +import { dayName } from '../../lib/format'; +import { dayShort } from '../../lib/availability'; + +export interface PresenceHeatCell { + day: number; + hour: number; + count: number; +} + +/* Mapa ciepła bytności 7 (dzień 0=pon) × 24 (godzina) — natężenie ~ udział w szczycie, + styl kafli jak mapa urządzeń. Współdzielona: widok ogólny siłowni + statystyki właściciela. + Etykiety dni skrócone (pełna nazwa w tytulu wiersza), siatka skaluje się do szerokosci + kolumny — bez minimalnej szerokosci i przewijania (zero overflow w sąsiedztwie karty). */ +export function PresenceHeatmapGrid({ cells }: { cells: PresenceHeatCell[] }) { + const max = cells.reduce((m, c) => Math.max(m, c.count), 0); + return ( +
+
+ + {Array.from({ length: 24 }, (_, hour) => ( + + {hour % 3 === 0 ? String(hour).padStart(2, '0') : ''} + + ))} + {Array.from({ length: 7 }, (_, day) => ( + + ))} +
+
+ ); +} + +function HeatmapRow({ day, cells, max }: { day: number; cells: PresenceHeatCell[]; max: number }) { + const { t } = useTranslation('gyms'); + return ( + <> + + {dayShort(day)} + + {Array.from({ length: 24 }, (_, hour) => { + const cell = cells.find((c) => c.day === day && c.hour === hour); + const count = cell?.count ?? 0; + const intensity = max > 0 ? count / max : 0; + return ( + 0 + ? `color-mix(in srgb, var(--accent) ${Math.round(18 + intensity * 82)}%, var(--bg-input))` + : 'var(--bg-input)', + }} + /> + ); + })} + + ); +} diff --git a/app/src/i18n/locales/en/gyms.json b/app/src/i18n/locales/en/gyms.json index 348800e..701bf7f 100644 --- a/app/src/i18n/locales/en/gyms.json +++ b/app/src/i18n/locales/en/gyms.json @@ -81,16 +81,7 @@ "galleryTitle": "Photo gallery", "equipmentTitle": "Equipment", "equipmentDesc": "Machines and devices available at this gym.", - "hoursTitle": "Opening hours", "exceptionsLabel": "Exceptions", - "dataTitle": "Details", - "dataKind": "Type", - "dataPrivate": "Private", - "dataCapacity": "Capacity", - "dataStreet": "Street", - "dataPostalCity": "Postal code and city", - "dataCountry": "Country", - "dataLocation": "Location", "groupEdit": "Editing", "groupManage": "Manage", "groupGallery": "Gallery", @@ -314,6 +305,18 @@ "rangeDays_one": "{{count}} day", "rangeDays_other": "{{count}} days" }, + "presence": { + "title": "Attendance", + "empty": "No check-ins in the last 30 days.", + "live": "inside now", + "visits": "visits (30 days)", + "avgStay": "avg stay", + "minutesShort": "min", + "peak": "hourly peak", + "visitsPerDay": "visits/day", + "heatmap": "When they train (day × hour)", + "topEquipment": "Most used equipment" + }, "address": { "street": "Street and number", "streetPh": "e.g. Mokotowska 12A", diff --git a/app/src/i18n/locales/pl/gyms.json b/app/src/i18n/locales/pl/gyms.json index 2816ad3..ad15f75 100644 --- a/app/src/i18n/locales/pl/gyms.json +++ b/app/src/i18n/locales/pl/gyms.json @@ -85,16 +85,7 @@ "galleryTitle": "Galeria zdjęć", "equipmentTitle": "Urządzenia", "equipmentDesc": "Maszyny i urządzenia dostępne w tej siłowni.", - "hoursTitle": "Godziny otwarcia", "exceptionsLabel": "Wyjątki", - "dataTitle": "Dane", - "dataKind": "Rodzaj", - "dataPrivate": "Prywatna", - "dataCapacity": "Pojemność", - "dataStreet": "Ulica", - "dataPostalCity": "Kod i miasto", - "dataCountry": "Kraj", - "dataLocation": "Lokalizacja", "groupEdit": "Edycja", "groupManage": "Zarządzaj", "groupGallery": "Galeria", @@ -328,6 +319,18 @@ "rangeDays_many": "{{count}} dni", "rangeDays_other": "{{count}} dni" }, + "presence": { + "title": "Bytność", + "empty": "Brak meldunków w ostatnich 30 dniach.", + "live": "teraz w środku", + "visits": "wizyty (30 dni)", + "avgStay": "śr. pobyt", + "minutesShort": "min", + "peak": "rekord godzinowy", + "visitsPerDay": "wizyt/dzień", + "heatmap": "Kiedy bywają (dzień × godzina)", + "topEquipment": "Najczęściej używane urządzenia" + }, "address": { "street": "Ulica i numer", "streetPh": "np. Mokotowska 12A", diff --git a/app/src/lib/availability.ts b/app/src/lib/availability.ts index 4177c51..8706c4c 100644 --- a/app/src/lib/availability.ts +++ b/app/src/lib/availability.ts @@ -75,3 +75,13 @@ export function shortTime(t: string): string { export function formatDayRange(day: DayAvailability): string { return `${shortTime(day.start)}–${shortTime(day.end)}`; } + +/** "06:00" -> "6:00" — minutes always kept, only the leading zero is dropped. */ +export function clockTime(t: string): string { + return t.replace(/^0/, ''); +} + +/** Day range with minutes for the hours band, e.g. "6:00–22:00". */ +export function formatDayRangeClock(day: DayAvailability): string { + return `${clockTime(day.start)}–${clockTime(day.end)}`; +} diff --git a/app/src/pages/gyms/GymDetail.tsx b/app/src/pages/gyms/GymDetail.tsx index 8479fef..513e237 100644 --- a/app/src/pages/gyms/GymDetail.tsx +++ b/app/src/pages/gyms/GymDetail.tsx @@ -4,11 +4,9 @@ import { useTranslation } from 'react-i18next'; import { useQueryClient } from '@tanstack/react-query'; import { ArrowLeft, - BarChart3, CalendarX, Dumbbell, Image as ImageIcon, - MapPin, MessageSquare, Settings, ThumbsDown, @@ -28,13 +26,14 @@ import { useGymAnnouncements, useGymDetail, useGymExceptions, - useGymStatsOverview, + useGymPresenceStats, useMyGymClaims, withdrawGymClaim, } from '../../api/queries'; import type { Gym, GymException } from '../../api/types'; import { fmtDate, fmtDateTime } from '../../lib/format'; import { formatGymEquipment } from '../../lib/equipment'; +import { localizedName } from '../../lib/localizedName'; import { BackButton, Button, @@ -55,11 +54,12 @@ import { TIME_SLOTS, dayFull, dayShort, - formatDayRange, + formatDayRangeClock, } from '../../lib/availability'; import ClaimModal from '../../components/gyms/ClaimModal'; import InviteGymModal from '../../components/gyms/InviteGymModal'; import GymQrModal from '../../components/gyms/GymQrModal'; +import { PresenceHeatmapGrid } from '../../components/gyms/PresenceHeatmap'; import { GymEditForm } from './GymSections'; /* Godziny otwarcia w całym wierszu pod hero (informacja kluczowa — nie w bocznej kolumnie). @@ -75,10 +75,9 @@ function HoursBand({ gym }: { gym: Gym }) { const hasHours = availability.some(Boolean); if (!hasHours && exceptions.length === 0) return null; return ( - + {hasHours && ( <> -
{availability.map((day, i) => (
- {/* telefon: skrót dnia + zwarty zakres; desktop: pełna nazwa + pełne godziny */} - {dayShort(i)} - - {dayFull(i)} - {i === todayIdx && ( - - {t('common:fmt.today')} - - )} + {/* pelna nazwa dnia tylko gdy miesci sie w kolumnie (container query karty), + ponizej skrot; minuty godzin sa zawsze widoczne — ponizej @3xl zakres + lamie sie do dwoch linii zamiast byc przycinany lub gubic minuty; + badge „dziś" rownolegle obok nazwy (od @2xl), nie osobna linia */} + + {dayShort(i)} + {dayFull(i)} + {i === todayIdx && ( + + {t('common:fmt.today')} + + )}
- {day ? formatDayRange(day) : '—'} - - {day ? `${day.start}–${day.end}` : t('hours.closed')} + + {day ? formatDayRangeClock(day) : '—'} + + + {day ? formatDayRangeClock(day) : t('hours.closed')}
@@ -156,9 +160,9 @@ function GalleryTile({ gym }: { gym: Gym & { photos: { id: string; url: string } to={`/gyms/${gym.id}/gallery`} className="flex flex-col rounded-2xl border border-line bg-card p-3 transition-colors hover:border-accent/55" > -
+
{preview.length === 0 ? ( -
+
) : ( @@ -190,31 +194,32 @@ function EquipmentTile({ gym }: { gym: Gym }) { to={`/gyms/${gym.id}/equipment`} className="flex flex-col rounded-2xl border border-line bg-card p-3 transition-colors hover:border-accent/55" > -
+
{preview.length === 0 ? ( -
+
) : ( preview.map((e) => { const photo = e.photos?.[0]; - return photo ? ( -
- -
- ) : ( -
-