diff --git a/app/src/App.tsx b/app/src/App.tsx index e13f54d..ee69dc3 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -20,6 +20,8 @@ import ProfileProgress from './pages/profile/ProfileProgress'; import ProfileClaims from './pages/profile/ProfileClaims'; import Gyms from './pages/gyms/Gyms'; import GymDetail from './pages/gyms/GymDetail'; +import GymContactPage from './pages/gyms/GymContactPage'; +import GymStatsPage from './pages/gyms/GymStatsPage'; import GymGalleryPage from './pages/gyms/GymGalleryPage'; import GymEquipmentPage from './pages/gyms/GymEquipmentPage'; import GymAnnouncementsPage from './pages/gyms/GymAnnouncementsPage'; @@ -75,6 +77,8 @@ export default function App() { } /> } /> } /> + } /> + } /> api(`/gyms/${gymId}/contact`), + enabled: !!gymId, + refetchInterval: 30_000, + }); +} + +/** Członek inicjuje/odpowiada we własnym wątku (upsert per [gymId,userId]). */ +export function sendGymContactMessage(gymId: string, body: string) { + return api<{ + conversation: { + id: string; + gymId: string; + userId: string; + createdAt: string; + updatedAt: string; + }; + }>(`/gyms/${encodeURIComponent(gymId)}/contact/messages`, { method: 'POST', body: { body } }); +} + +/** Skrzynka właściciela: wątki we wszystkich gymach, gdzie caller ma rolę OWNER. */ +export function useGymContactInbox() { + return useQuery({ + queryKey: ['gym-contact', 'inbox'], + queryFn: () => api<{ conversations: GymContactThreadListItem[] }>('/gym-contact/conversations'), + refetchInterval: 30_000, + }); +} + +/** Pojedynczy wątek (read-mark po stronie API). */ +export function useGymContactThread(conversationId: string) { + return useQuery({ + queryKey: ['gym-contact', 'thread', conversationId], + queryFn: () => + api(`/gym-contact/conversations/${encodeURIComponent(conversationId)}`), + enabled: !!conversationId, + refetchInterval: 30_000, + }); +} + +/** Odpowiedź uczestnika w wątku (właściciel/admin lub członek). */ +export function sendGymContactReply(conversationId: string, body: string) { + return api<{ message: GymContactMessage }>( + `/gym-contact/conversations/${encodeURIComponent(conversationId)}/messages`, + { method: 'POST', body: { body } }, + ); +} + +/** Usunięcie własnej wiadomości (twardy delete, tylko autor). */ +export function deleteGymContactMessage(messageId: string) { + return api(`/gym-contact/messages/${encodeURIComponent(messageId)}`, { method: 'DELETE' }); +} + +/** + * Statystyki właściciela (REAL): presence + członkowie + aktywność treningowa. + * `rangeDays`: 7/30/90, from liczony od teraz (jak mapa ciepła urządzeń). + */ +export function useGymStatsOverview(gymId: string | undefined, rangeDays: number) { + return useQuery({ + queryKey: ['gym-stats-overview', gymId, rangeDays], + queryFn: () => { + const from = new Date(Date.now() - rangeDays * 86_400_000).toISOString(); + return api( + `/gyms/${gymId}/stats/overview?from=${encodeURIComponent(from)}`, + ); + }, + enabled: !!gymId, + }); +} + // ---------- bytność (check-in, live occupancy) ---------- /** Aktywna bytność zalogowanego — podstawa przycisków „Idę ćwiczyć / Wychodzę / Wciąż tu jestem". */ export function useActivePresence(refetchIntervalMs?: number) { diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 951835b..267d35d 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -158,6 +158,8 @@ export interface Gym { coverPhoto: string | null; /** Live „teraz: N" (aktywne bytności); null dla VIRTUAL (brak meldunków). */ currentOccupancy?: number | null; + /** Głos zalogowanego (publiczna VIRTUAL); null = nie głosował; brak dla REAL/prywatnych. */ + myVote?: 'UP' | 'DOWN' | null; } /** Odpowiedź detalu siłowni (GET /gyms/:id): siłownia + galeria + role zalogowanego. */ @@ -294,6 +296,87 @@ export interface GymException { availability: DayAvailability | null; } +// ---------- kontakt członek ↔ właściciele siłowni ---------- +export type GymContactRole = 'member' | 'owner' | 'admin'; + +export interface GymContactMessage { + id: string; + senderId: string; + senderName: string; + body: string; + createdAt: string; +} + +export interface GymContactConversationInfo { + id: string; + gymId: string; + gymName: string; + /** Autor wątku (członek, który go zainicjował). */ + userId: string; + memberName: string; + createdAt: string; + updatedAt: string; +} + +/** Widok członka: własny wątek (lazily null) + strumień + canReply. */ +export interface GymContactMemberView { + role: 'member'; + conversation: GymContactConversationInfo | null; + messages: GymContactMessage[]; + canReply: boolean; +} + +export interface GymContactThreadListItem { + id: string; + gymId: string; + gymName: string; + userId: string; + counterpartName: string; + lastMessageBody: string | null; + lastMessageAt: string | null; + unreadCount: number; +} + +/** Widok właściciela/admina siłowni: lista wątków tego gyma. */ +export interface GymContactManagerView { + role: 'owner' | 'admin'; + threads: GymContactThreadListItem[]; +} + +export type GymContactView = GymContactMemberView | GymContactManagerView; + +/** Pojedynczy wątek (GET /gym-contact/conversations/:id) — read-mark po stronie API. */ +export interface GymContactThread { + role: GymContactRole; + conversation: GymContactConversationInfo; + messages: GymContactMessage[]; + canReply: boolean; +} + +// ---------- statystyki właściciela (GET /gyms/:id/stats/overview, REAL) ---------- +export interface GymStatsOverview { + gym: { id: string; name: string; kind: GymKind; capacity: number | null }; + presence: { + visits: number; + visitsPerDay: number; + avgStayMinutes: number | null; + peak: number; + live: number; + heatmap: { day: number; hour: number; count: number }[]; + }; + members: { + total: number; + byRole: { OWNER: number; TRAINER: number; MEMBER: number }; + newInRange: number; + }; + activity: { + sessionsStarted: number; + sessionsCompleted: number; + sessionsAbandoned: number; + uniqueExercisers: number; + }; +} + export interface Exercise { id: string; slug: string; diff --git a/app/src/components/Layout.tsx b/app/src/components/Layout.tsx index 6546008..c549bf2 100644 --- a/app/src/components/Layout.tsx +++ b/app/src/components/Layout.tsx @@ -24,6 +24,7 @@ import { useActiveSession, useConversations, useFeedUnreadCount, + useGymContactInbox, useGymInvitations, useInvitations, useIsTrainer, @@ -200,14 +201,14 @@ export default function Layout() { const { data: invitations } = useInvitations(); const { data: gymInvitations } = useGymInvitations(); const { data: conversations } = useConversations(); + const { data: gymContactData } = useGymContactInbox(); // Liczba oczekujących zaproszeń: coaching (trener) + do prywatnych siłowni. const pendingInvitations = (invitations?.invitations ?? []).length + (gymInvitations?.invitations ?? []).length; - // Nieprzeczytane wiadomości w komunikatorze (suma per rozmowa). - const unreadMessages = (conversations?.conversations ?? []).reduce( - (n, c) => n + c.unreadCount, - 0, - ); + // Nieprzeczytane: komunikator coachingowy + wątki kontaktu z właścicielami siłowni. + const unreadMessages = + (conversations?.conversations ?? []).reduce((n, c) => n + c.unreadCount, 0) + + (gymContactData?.conversations ?? []).reduce((n, c) => n + c.unreadCount, 0); // Nieprzeczytane aktualności (powiadomienia osobiste + ogłoszenia siłowni). const { data: feedUnread } = useFeedUnreadCount(); const unreadFeed = feedUnread?.unreadCount ?? 0; diff --git a/app/src/components/gyms/InviteGymModal.tsx b/app/src/components/gyms/InviteGymModal.tsx index b52b5fb..85d44f9 100644 --- a/app/src/components/gyms/InviteGymModal.tsx +++ b/app/src/components/gyms/InviteGymModal.tsx @@ -1,8 +1,15 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useQueryClient } from '@tanstack/react-query'; -import { sendGymInvitation, useGymInviteeSearch } from '../../api/queries'; -import { Button, ErrorText, Field, Input, Loading, Modal } from '../ui'; +import { + sendGymInvitation, + useGymInvitations, + useGymInviteeSearch, + withdrawGymInvitation, +} from '../../api/queries'; +import type { GymInvitation } from '../../api/types'; +import { Avatar } from '../Avatar'; +import { Button, ConfirmDialog, ErrorText, Field, Input, ListRow, Loading, Modal } from '../ui'; import { useToast } from '../toast'; /** Wyszukajka imię + nazwisko → „Zaproś” per user (właściciel prywatnej VIRTUAL). */ @@ -94,6 +101,86 @@ export default function InviteGymModal({ ); })} + + ); } + +/* Wysłane zaproszenia (dawna karta w treści detailu — przeniesiona do modala, + 1 kontrolka = 1 miejsce): lista + „Wycofaj” z potwierdzeniem. */ +function SentInvitationsList({ gymId }: { gymId: string }) { + const queryClient = useQueryClient(); + const { push } = useToast(); + const { t } = useTranslation('gyms'); + const { data } = useGymInvitations(); + const sent = (data?.invitations ?? []).filter( + (i) => i.direction === 'sent' && i.gym.id === gymId, + ); + const [toWithdraw, setToWithdraw] = useState(null); + const [busy, setBusy] = useState(false); + + const withdraw = async () => { + if (!toWithdraw) return; + setBusy(true); + try { + await withdrawGymInvitation(toWithdraw.id); + await queryClient.invalidateQueries({ queryKey: ['gym-invitations'] }); + push(t('invites.toastWithdrawn'), 'success'); + setToWithdraw(null); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setBusy(false); + } + }; + + if (sent.length === 0) return null; + const name = toWithdraw + ? [toWithdraw.user?.firstName, toWithdraw.user?.lastName].filter(Boolean).join(' ') || + toWithdraw.user?.email || + '—' + : ''; + + return ( + + + {t('invite.sentTitle')} + + + {sent.map((inv) => { + const invName = + [inv.user?.firstName, inv.user?.lastName].filter(Boolean).join(' ') || + inv.user?.email || + '—'; + return ( + + + {invName} + + } + actions={ + setToWithdraw(inv)}> + {t('invites.withdraw')} + + } + /> + ); + })} + + setToWithdraw(null)} + onConfirm={() => void withdraw()} + title={t('invites.withdraw')} + description={t('invites.confirmWithdraw', { name })} + confirmLabel={t('invites.withdraw')} + danger + busy={busy} + /> + + ); +} diff --git a/app/src/i18n/locales/en/common.json b/app/src/i18n/locales/en/common.json index 50b2df2..01b18a9 100644 --- a/app/src/i18n/locales/en/common.json +++ b/app/src/i18n/locales/en/common.json @@ -95,7 +95,9 @@ "measurements_one": "{{count}} measurement", "measurements_other": "{{count}} measurements", "devices_one": "{{count}} device", - "devices_other": "{{count}} devices" + "devices_other": "{{count}} devices", + "members_one": "{{count}} member", + "members_other": "{{count}} members" }, "muscles": { "chest": "Chest", diff --git a/app/src/i18n/locales/en/gyms.json b/app/src/i18n/locales/en/gyms.json index d538cde..348800e 100644 --- a/app/src/i18n/locales/en/gyms.json +++ b/app/src/i18n/locales/en/gyms.json @@ -97,6 +97,7 @@ "groupEquipment": "Equipment", "groupAnnouncements": "Announcements", "groupInvites": "Invitations", + "groupStats": "Statistics", "actionInfo": "Information", "actionInvite": "Invite user", "actionWithdrawClaim": "Withdraw request", @@ -139,6 +140,7 @@ "desc": "A private gym is hidden — invite specific users.", "empty": "No invitations sent.", "withdraw": "Withdraw", + "confirmWithdraw": "Withdraw the invitation for {{name}}?", "toastWithdrawn": "Invitation withdrawn" }, "page": { @@ -253,9 +255,10 @@ "firstNamePh": "e.g. John", "lastNameLabel": "Last name", "lastNamePh": "e.g. Smith", - "empty": "No users with these details.", + "empty": "No users with the given details.", "submit": "Invite", - "busy": "Inviting…" + "busy": "Inviting…", + "sentTitle": "Sent invitations" }, "join": { "toastOk": "Joined gym: {{name}}", @@ -267,6 +270,50 @@ "submit": "Join", "busy": "Joining…" }, + "rating": { + "group": "Rating", + "recommend": "Recommend", + "notRecommend": "Do not recommend" + }, + "contact": { + "action": "Write to owners", + "pageTitle": "Contact", + "ownersTitle": "Owners — {{name}}", + "ownersAvatar": "Owners", + "threadsTitle": "Conversations — {{name}}", + "composerPlaceholder": "Write a message to the owners…", + "composerAria": "Message body", + "send": "Send", + "sending": "Sending…", + "counter": "{{n}}/{{max}}", + "emptyThread": "No messages yet — write the first one.", + "emptyThreadsTitle": "No conversations", + "emptyThreadsDesc": "Members of this gym have not written yet.", + "deleteAria": "Delete message", + "deleteTitle": "Delete message", + "deleteDesc": "This action cannot be undone." + }, + "stats": { + "title": "Statistics", + "visits": "Visits", + "visitsPerDay": "Visits / day", + "avgStay": "Avg. stay", + "minutes": "{{n}} min", + "peak": "Peak", + "live": "Now", + "members": "Members", + "newInRange": "New in range", + "sessionsCompleted": "Sessions completed", + "sessionsAbandoned": "Sessions abandoned", + "uniqueExercisers": "Exercising people", + "heatmapTitle": "Presence (day × hour)", + "heatmapEmpty": "No visits in this period.", + "cellTitle_one": "{{day}}, {{hour}}:00 — {{count}} visit", + "cellTitle_other": "{{day}}, {{hour}}:00 — {{count}} visits", + "rangeAria": "Statistics range", + "rangeDays_one": "{{count}} day", + "rangeDays_other": "{{count}} days" + }, "address": { "street": "Street and number", "streetPh": "e.g. Mokotowska 12A", diff --git a/app/src/i18n/locales/en/messages.json b/app/src/i18n/locales/en/messages.json index 3c8368f..dd85946 100644 --- a/app/src/i18n/locales/en/messages.json +++ b/app/src/i18n/locales/en/messages.json @@ -10,6 +10,7 @@ "roleTrainers": "Trainers", "youPrefix": "You: ", "noMessageRow": "No messages", + "gymOwnersSection": "Gym owners", "emptyTitle": "No conversations", "emptyDesc": "A conversation appears once you have an active relationship with a trainer.", "searchNoResults": "No results for the given query.", diff --git a/app/src/i18n/locales/pl/common.json b/app/src/i18n/locales/pl/common.json index f1bf639..a453c12 100644 --- a/app/src/i18n/locales/pl/common.json +++ b/app/src/i18n/locales/pl/common.json @@ -117,7 +117,11 @@ "devices_one": "{{count}} urządzenie", "devices_few": "{{count}} urządzenia", "devices_many": "{{count}} urządzeń", - "devices_other": "{{count}} urządzeń" + "devices_other": "{{count}} urządzeń", + "members_one": "{{count}} członek", + "members_few": "{{count}} członków", + "members_many": "{{count}} członków", + "members_other": "{{count}} członków" }, "muscles": { "chest": "Klatka", diff --git a/app/src/i18n/locales/pl/gyms.json b/app/src/i18n/locales/pl/gyms.json index c0c647c..2816ad3 100644 --- a/app/src/i18n/locales/pl/gyms.json +++ b/app/src/i18n/locales/pl/gyms.json @@ -101,6 +101,7 @@ "groupEquipment": "Urządzenia", "groupAnnouncements": "Ogłoszenia", "groupInvites": "Zaproszenia", + "groupStats": "Statystyki", "actionInfo": "Informacje", "actionInvite": "Zaproś usera", "actionWithdrawClaim": "Wycofaj wniosek", @@ -143,6 +144,7 @@ "desc": "Prywatna siłownia jest ukryta — zapraszaj określonych userów.", "empty": "Brak wysłanych zaproszeń.", "withdraw": "Wycofaj", + "confirmWithdraw": "Wycofać zaproszenie dla {{name}}?", "toastWithdrawn": "Zaproszenie wycofane" }, "page": { @@ -265,7 +267,8 @@ "lastNamePh": "np. Kowalski", "empty": "Brak użytkowników o podanych danych.", "submit": "Zaproś", - "busy": "Zapraszanie…" + "busy": "Zapraszanie…", + "sentTitle": "Wysłane zaproszenia" }, "join": { "toastOk": "Dołączono do siłowni: {{name}}", @@ -277,6 +280,54 @@ "submit": "Dołącz", "busy": "Dołączanie…" }, + "rating": { + "group": "Ocena", + "recommend": "Polecam", + "notRecommend": "Nie polecam" + }, + "contact": { + "action": "Napisz do właścicieli", + "pageTitle": "Kontakt", + "ownersTitle": "Właściciele — {{name}}", + "ownersAvatar": "Właściciele", + "threadsTitle": "Rozmowy — {{name}}", + "composerPlaceholder": "Napisz wiadomość do właścicieli…", + "composerAria": "Treść wiadomości", + "send": "Wyślij", + "sending": "Wysyłanie…", + "counter": "{{n}}/{{max}}", + "emptyThread": "Brak wiadomości — napisz pierwszą.", + "emptyThreadsTitle": "Brak rozmów", + "emptyThreadsDesc": "Członkowie tej siłowni jeszcze nie napisali.", + "deleteAria": "Usuń wiadomość", + "deleteTitle": "Usuń wiadomość", + "deleteDesc": "Tej operacji nie można cofnąć." + }, + "stats": { + "title": "Statystyki", + "visits": "Wizyty", + "visitsPerDay": "Wizyty / dzień", + "avgStay": "Śr. pobyt", + "minutes": "{{n}} min", + "peak": "Szczyt", + "live": "Teraz", + "members": "Członkowie", + "newInRange": "Nowi w okresie", + "sessionsCompleted": "Sesje ukończone", + "sessionsAbandoned": "Sesje porzucone", + "uniqueExercisers": "Ćwiczący", + "heatmapTitle": "Bytność (dzień × godzina)", + "heatmapEmpty": "Brak wizyt w tym okresie.", + "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", + "rangeAria": "Zakres statystyk", + "rangeDays_one": "{{count}} dzień", + "rangeDays_few": "{{count}} dni", + "rangeDays_many": "{{count}} dni", + "rangeDays_other": "{{count}} dni" + }, "address": { "street": "Ulica i numer", "streetPh": "np. Mokotowska 12A", diff --git a/app/src/i18n/locales/pl/messages.json b/app/src/i18n/locales/pl/messages.json index b5f6156..434259b 100644 --- a/app/src/i18n/locales/pl/messages.json +++ b/app/src/i18n/locales/pl/messages.json @@ -10,6 +10,7 @@ "roleTrainers": "Trenerzy", "youPrefix": "Ty: ", "noMessageRow": "Brak wiadomości", + "gymOwnersSection": "Właściciele siłowni", "emptyTitle": "Brak rozmów", "emptyDesc": "Rozmowa pojawi się po nawiązaniu aktywnej relacji z trenerem.", "searchNoResults": "Brak wyników dla podanego zapytania.", diff --git a/app/src/pages/gyms/GymContactPage.tsx b/app/src/pages/gyms/GymContactPage.tsx new file mode 100644 index 0000000..69004e1 --- /dev/null +++ b/app/src/pages/gyms/GymContactPage.tsx @@ -0,0 +1,358 @@ +import { Fragment, useRef, useState } from 'react'; +import { useParams, useSearchParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { useQueryClient } from '@tanstack/react-query'; +import { MessageSquare, Send } from 'lucide-react'; +import { + deleteGymContactMessage, + sendGymContactMessage, + sendGymContactReply, + useGymContactThread, + useGymContactView, + useGymDetail, + useMe, +} from '../../api/queries'; +import type { GymContactMessage } from '../../api/types'; +import { fmtDate, fmtDateTime, timeAgo } from '../../lib/format'; +import { + BackButton, + Button, + Card, + ConfirmDialog, + EmptyState, + ErrorText, + PageHeader, + Skeleton, + Textarea, +} from '../../components/ui'; +import { Avatar } from '../../components/Avatar'; +import { useToast } from '../../components/toast'; +import { useTopbar } from '../../topbar'; + +const MAX_BODY = 1000; + +/* Bąbelek wiadomości kontaktowej (mine = prawo, other = lewo + etykieta nadawcy). */ +function Bubble({ + message, + mine, + onDelete, +}: { + message: GymContactMessage; + mine: boolean; + onDelete: (id: string) => void; +}) { + const { t } = useTranslation('gyms'); + return ( + + {!mine && } + + {!mine && ( + + {message.senderName} + + )} + {message.body} + + {mine && ( + onDelete(message.id)} + className="cursor-pointer rounded-md p-0.5 text-dim/70 transition-colors hover:text-danger" + > + + + + + )} + {fmtDateTime(message.createdAt)} + + + + ); +} + +/* Komposer: textarea + licznik znaków + Wyślij (limit po stronie API: 1–1000). */ +function Composer({ onSend, busy }: { onSend: (body: string) => void; busy: boolean }) { + const { t } = useTranslation('gyms'); + const [body, setBody] = useState(''); + const send = () => { + const text = body.trim(); + if (!text) return; + onSend(text); + setBody(''); + }; + return ( + + setBody(e.target.value)} + aria-label={t('contact.composerAria')} + /> + + + {t('contact.counter', { n: body.length, max: MAX_BODY })} + + + + {busy ? t('contact.sending') : t('contact.send')} + + + + ); +} + +/** + * Kontakt członek ↔ właściciele siłowni (jeden komponent dla obu ról): + * member → własny wątek (lazily) + komposer; owner/admin → lista wątków gyma, + * klik wiersza (?thread=) → strumień + odpowiedź. + */ +export default function GymContactPage() { + const { id } = useParams(); + const { t } = useTranslation('gyms'); + const queryClient = useQueryClient(); + const { push } = useToast(); + const { data: meData } = useMe(); + const myId = meData?.user.id; + + const { data: view, isLoading, error } = useGymContactView(id); + const memberView = view?.role === 'member' ? view : null; + const managerView = view && (view.role === 'owner' || view.role === 'admin') ? view : null; + const isManager = managerView != null; + const [searchParams, setSearchParams] = useSearchParams(); + const selectedId = searchParams.get('thread'); + + const { data: gymData } = useGymDetail(id); + const { data: thread, isLoading: threadLoading } = useGymContactThread( + isManager && selectedId ? selectedId : '', + ); + + const listRef = useRef(null); + if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight; + + useTopbar({ + title: t('contact.pageTitle'), + back: `/gyms/${id}`, + }); + + const [busy, setBusy] = useState(false); + const [pendingDelete, setPendingDelete] = useState(null); + const [deleteBusy, setDeleteBusy] = useState(false); + + const invalidateContact = () => queryClient.invalidateQueries({ queryKey: ['gym-contact'] }); + + const doSend = async (text: string) => { + if (!id) return; + setBusy(true); + try { + if (isManager && selectedId) { + await sendGymContactReply(selectedId, text); + } else { + await sendGymContactMessage(id, text); + } + await invalidateContact(); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setBusy(false); + } + }; + + const doDelete = async () => { + if (!pendingDelete) return; + setDeleteBusy(true); + try { + await deleteGymContactMessage(pendingDelete); + await invalidateContact(); + setPendingDelete(null); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setDeleteBusy(false); + } + }; + + if (isLoading) { + return ( + + + + + ); + } + + if (error) { + return ( + <> + + + {t('common:errorPrefix')} + {(error as Error).message} + + > + ); + } + + /* Widok właściciela/admina bez wybranego wątku: lista rozmów tego gyma. */ + if (managerView && !selectedId) { + const threads = managerView.threads; + return ( + <> + } + /> + + {threads.length === 0 ? ( + + ) : ( + + {threads.map((thr) => { + const unread = thr.unreadCount > 0; + return ( + setSearchParams({ thread: thr.id })} + className="flex w-full cursor-pointer items-center gap-3 rounded-[10px] px-2 py-3.5 text-left transition-colors hover:bg-line/20" + > + + + {unread && ( + + )} + + + + + {thr.counterpartName} + + {thr.lastMessageAt && ( + + {timeAgo(thr.lastMessageAt)} + + )} + + + + {thr.lastMessageBody ?? '—'} + + {unread && ( + + {thr.unreadCount} + + )} + + + + ); + })} + + )} + + > + ); + } + + /* Strumień wiadomości: member → własny wątek z widoku; owner → wybrany wątek. */ + const managerThreadLoading = isManager && threadLoading && !thread; + const messages = isManager ? (thread?.messages ?? []) : (memberView?.messages ?? []); + const memberName = isManager ? (thread?.conversation.memberName ?? '') : ''; + const gymName = isManager + ? (thread?.conversation.gymName ?? '') + : (memberView?.conversation?.gymName ?? gymData?.gym.name ?? ''); + + if (managerThreadLoading) { + return ( + + + + + ); + } + + return ( + + } + actions={ + isManager ? ( + setSearchParams({})} /> + ) : ( + + ) + } + /> + + + {messages.length === 0 ? ( + {t('contact.emptyThread')} + ) : ( + + {messages.map((m, i, arr) => { + const prev = i > 0 ? arr[i - 1] : null; + const newDay = !prev || fmtDate(prev.createdAt) !== fmtDate(m.createdAt); + return ( + + {newDay && ( + + + {fmtDate(m.createdAt)} + + + )} + setPendingDelete(mid)} + /> + + ); + })} + + )} + + + void doSend(text)} busy={busy} /> + + setPendingDelete(null)} + onConfirm={() => void doDelete()} + title={t('contact.deleteTitle')} + description={t('contact.deleteDesc')} + confirmLabel={t('common:remove')} + danger + busy={deleteBusy} + /> + + ); +} diff --git a/app/src/pages/gyms/GymDetail.tsx b/app/src/pages/gyms/GymDetail.tsx index 3f2c04d..8479fef 100644 --- a/app/src/pages/gyms/GymDetail.tsx +++ b/app/src/pages/gyms/GymDetail.tsx @@ -4,11 +4,16 @@ import { useTranslation } from 'react-i18next'; import { useQueryClient } from '@tanstack/react-query'; import { ArrowLeft, + BarChart3, CalendarX, Dumbbell, Image as ImageIcon, MapPin, + MessageSquare, Settings, + ThumbsDown, + ThumbsUp, + UserPlus, Users, } from 'lucide-react'; import { @@ -17,14 +22,15 @@ import { createGymException, deleteGym, deleteGymException, + joinGym, + rateGym, useActivePresence, useGymAnnouncements, useGymDetail, useGymExceptions, - useGymInvitations, + useGymStatsOverview, useMyGymClaims, withdrawGymClaim, - withdrawGymInvitation, } from '../../api/queries'; import type { Gym, GymException } from '../../api/types'; import { fmtDate, fmtDateTime } from '../../lib/format'; @@ -36,14 +42,12 @@ import { ConfirmDialog, ErrorText, Input, - ListRow, Loading, Modal, SectionHeader, Select, } from '../../components/ui'; import { useToast } from '../../components/toast'; -import { Avatar } from '../../components/Avatar'; import { AuthImage } from '../../components/AuthImage'; import { useTopbar, type TopbarAction, type TopbarCustomGroup } from '../../topbar'; import { @@ -263,6 +267,31 @@ function AnnouncementsTile({ gymId }: { gymId: string }) { ); } +/* Kafelek Statystyk właściciela (tylko REAL + OWNER): telemetria bytności, + członkowie i aktywność treningowa; klik → podstrona /stats. */ +function StatsTile({ gym }: { gym: Gym }) { + const { t } = useTranslation('gyms'); + const { data } = useGymStatsOverview(gym.id, 30); + return ( + + + + + + + {t('detail.groupStats')} + + + {data ? t('common:counters.members', { count: data.members.total }) : '—'} + + + + ); +} + /* Lista wyjątków harmonogramu (read + usuwanie przez właściciela). */ function ExceptionsList({ gymId, canManage }: { gymId: string; canManage: boolean }) { const queryClient = useQueryClient(); @@ -459,6 +488,7 @@ export default function GymDetail() { const gym = data?.gym; const presence = presenceData?.presence ?? null; const isOwner = (data?.roles ?? []).includes('OWNER'); + const isMember = (data?.roles ?? []).length > 0; const claim = (claimsData?.claims ?? []).find((c) => c.gymId === id) ?? null; const [confirmOpen, setConfirmOpen] = useState(false); @@ -470,6 +500,8 @@ export default function GymDetail() { const [editOpen, setEditOpen] = useState(false); const [qrOpen, setQrOpen] = useState(false); const [presenceBusy, setPresenceBusy] = useState(false); + const [joinBusy, setJoinBusy] = useState(false); + const [rateBusy, setRateBusy] = useState(false); const invalidatePresence = async () => { await Promise.all([ @@ -538,41 +570,102 @@ export default function GymDetail() { } }; - // Operacje właściciela: JEDNA grupa „Zarządzaj” (topbar). Pozycje Galeria/Urządzenia/ - // Ogłoszenia nawigują na podstrony (świadome dublowanie z kafelkami — decyzja product); + // Dołączenie do publicznej VIRTUAL (akcja przeniesiona z kart listy). + const doJoin = async () => { + if (!gym) return; + setJoinBusy(true); + try { + await joinGym(gym.id); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['gym', id] }), + queryClient.invalidateQueries({ queryKey: ['gyms'] }), + queryClient.invalidateQueries({ queryKey: ['gyms', 'virtual'] }), + ]); + push(t('join.toastOk', { name: gym.name }), 'success'); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setJoinBusy(false); + } + }; + + // Głos „Polecam / Nie polecam" (publiczna VIRTUAL) — dawne przyciski z kart listy. + const rate = async (vote: 'UP' | 'DOWN') => { + if (!gym) return; + setRateBusy(true); + try { + await rateGym(gym.id, vote); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['gym', id] }), + queryClient.invalidateQueries({ queryKey: ['gyms', 'virtual'] }), + ]); + } catch (e) { + push((e as Error).message, 'error'); + } finally { + setRateBusy(false); + } + }; + + // Operacje właściciela: JEDNA grupa „Zarządzaj” (topbar). Pozycje Galeria/Statystyki/ + // Urządzenia/Ogłoszenia nawigują na podstrony (świadome dublowanie z kafelkami — decyzja product); // Informacje/QR/Zaproszenia/Usuń otwierają modale na tej stronie. - const groups: TopbarCustomGroup[] | undefined = - gym && isOwner - ? [ - { - id: 'manage', - label: t('detail.groupManage'), - icon: Settings, - actions: [ - { label: t('detail.actionInfo'), onClick: () => setEditOpen(true) }, - ...(gym.kind === 'REAL' - ? [ - { - label: t('detail.groupGallery'), - to: `/gyms/${gym.id}/gallery`, - }, - { label: tp('qr.action'), onClick: () => setQrOpen(true) }, - ] - : []), - { label: t('detail.groupEquipment'), to: `/gyms/${gym.id}/equipment` }, - { label: t('detail.groupAnnouncements'), to: `/gyms/${gym.id}/announcements` }, - ...(gym.kind === 'VIRTUAL' && gym.isPrivate - ? [{ label: t('detail.actionInvite'), onClick: () => setInviteOpen(true) }] - : []), + const groups: TopbarCustomGroup[] = []; + if (gym && isOwner) { + groups.push({ + id: 'manage', + label: t('detail.groupManage'), + icon: Settings, + // na lg+ zwinięta do jednej kontrolki „Zarządzaj” (dropdown) — nie inline + collapsed: true, + actions: [ + { label: t('detail.actionInfo'), onClick: () => setEditOpen(true) }, + ...(gym.kind === 'REAL' + ? [ { - label: t('detail.actionDelete'), - variant: 'danger', - onClick: () => setConfirmOpen(true), + label: t('detail.groupGallery'), + to: `/gyms/${gym.id}/gallery`, }, - ], - }, - ] - : undefined; + { label: t('detail.groupStats'), to: `/gyms/${gym.id}/stats` }, + { label: tp('qr.action'), onClick: () => setQrOpen(true) }, + ] + : []), + { label: t('detail.groupEquipment'), to: `/gyms/${gym.id}/equipment` }, + { label: t('detail.groupAnnouncements'), to: `/gyms/${gym.id}/announcements` }, + ...(gym.kind === 'VIRTUAL' && gym.isPrivate + ? [{ label: t('detail.groupInvites'), onClick: () => setInviteOpen(true) }] + : []), + { + label: t('detail.actionDelete'), + variant: 'danger', + onClick: () => setConfirmOpen(true), + }, + ], + }); + } + // Publiczna VIRTUAL, nie-OWNER: ocena odwzorowania (grupa „Ocena” — 2 akcje togglowe, + // oddany głos = zablokowana kontrolka + kropka aktywności przy ikonie grupy). + if (gym && gym.kind === 'VIRTUAL' && !gym.isPrivate && !isOwner) { + groups.push({ + id: 'rating', + label: t('rating.group'), + icon: ThumbsUp, + active: (gym.myVote ?? null) != null, + actions: [ + { + label: t('rating.recommend'), + icon: ThumbsUp, + disabled: rateBusy || gym.myVote === 'UP', + onClick: () => void rate('UP'), + }, + { + label: t('rating.notRecommend'), + icon: ThumbsDown, + disabled: rateBusy || gym.myVote === 'DOWN', + onClick: () => void rate('DOWN'), + }, + ], + }); + } // Spoza grupy: claim/wycofanie wniosku (VIRTUAL) — reszta operacji właściciela w „Zarządzaj”. const ownerActions: TopbarAction[] | undefined = @@ -619,11 +712,31 @@ export default function GymDetail() { ] : undefined; - const topActions = [...(presenceActions ?? []), ...(ownerActions ?? [])]; + // Kontakt z właścicielami (członek, nie-OWNER — właściciele wchodzą przez skrzynkę) + // albo dołączenie do publicznej VIRTUAL (nie-członek) — akcje przeniesione z kart listy. + const memberActions: TopbarAction[] | undefined = + gym && isMember && !isOwner + ? [{ label: t('contact.action'), icon: MessageSquare, to: `/gyms/${gym.id}/contact` }] + : gym && gym.kind === 'VIRTUAL' && !gym.isPrivate && !isMember + ? [ + { + label: t('join.submit'), + icon: UserPlus, + disabled: joinBusy, + onClick: () => void doJoin(), + }, + ] + : undefined; + + const topActions = [ + ...(presenceActions ?? []), + ...(memberActions ?? []), + ...(ownerActions ?? []), + ]; useTopbar({ title: t('nav:gyms'), back: '/gyms', - groups, + groups: groups.length > 0 ? groups : undefined, actions: topActions.length > 0 ? topActions : undefined, }); @@ -750,6 +863,7 @@ export default function GymDetail() { {gym.kind === 'REAL' && } + {gym.kind === 'REAL' && isOwner && } @@ -784,9 +898,6 @@ export default function GymDetail() { )} - {isOwner && gym.kind === 'VIRTUAL' && gym.isPrivate && ( - - )} @@ -853,62 +964,3 @@ export default function GymDetail() { > ); } - -/* Zaproszenia do prywatnej siłowni (lista + wycofywanie). */ -function GymInvitationsSection({ gym }: { gym: Gym }) { - const queryClient = useQueryClient(); - const { push } = useToast(); - const { t } = useTranslation('gyms'); - const { data } = useGymInvitations(); - const sent = (data?.invitations ?? []).filter( - (i) => i.direction === 'sent' && i.gym.id === gym.id, - ); - - const withdraw = async (id: string) => { - try { - await withdrawGymInvitation(id); - await queryClient.invalidateQueries({ queryKey: ['gym-invitations'] }); - push(t('invites.toastWithdrawn'), 'success'); - } catch (e) { - push((e as Error).message, 'error'); - } - }; - - return ( - - - - {sent.length === 0 && ( - {t('invites.empty')} - )} - {sent.map((inv) => { - const name = - [inv.user?.firstName, inv.user?.lastName].filter(Boolean).join(' ') || - inv.user?.email || - '—'; - return ( - - - {name} - - } - actions={ - void withdraw(inv.id)} - > - {t('invites.withdraw')} - - } - /> - ); - })} - - - ); -} diff --git a/app/src/pages/gyms/GymStatsPage.tsx b/app/src/pages/gyms/GymStatsPage.tsx new file mode 100644 index 0000000..4744ad9 --- /dev/null +++ b/app/src/pages/gyms/GymStatsPage.tsx @@ -0,0 +1,178 @@ +import { useState } from 'react'; +import { useParams } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { useGymDetail, useGymStatsOverview } from '../../api/queries'; +import type { GymStatsOverview } from '../../api/types'; +import { dayName } from '../../lib/format'; +import { BackButton, Card, ErrorText, Loading, SectionHeader, Select } from '../../components/ui'; +import { useTopbar } from '../../topbar'; + +const RANGE_OPTIONS = [7, 30, 90]; + +/* KPI: etykieta + duża wartość tabelaryczna. */ +function Kpi({ label, value }: { label: string; value: string | number }) { + return ( + + {label} + {value} + + ); +} + +/* Mapa ciepła bytności 7 (dzień 0=pon) × 24 (godzina) — natężenie ~ udział w szczycie, + styl kafli jak mapa urządzeń. */ +function PresenceHeatmap({ stats }: { stats: GymStatsOverview }) { + const { t } = useTranslation('gyms'); + const cells = stats.presence.heatmap; + const max = cells.reduce((m, c) => Math.max(m, c.count), 0); + return ( + + + {cells.length === 0 ? ( + {t('stats.heatmapEmpty')} + ) : ( + + + + {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: GymStatsOverview['presence']['heatmap']; + max: number; +}) { + const { t } = useTranslation('gyms'); + return ( + <> + + {dayName(day + 1)} + + {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)', + }} + /> + ); + })} + > + ); +} + +/** + * Statystyki właściciela (tylko REAL): telemetria bytności + członkowie i napływ + * + aktywność treningowa. Filtr okresu 7/30/90 w grupie filtrów topbaru. + */ +export default function GymStatsPage() { + const { id } = useParams(); + const { t } = useTranslation('gyms'); + const { data: gymData } = useGymDetail(id); + const [rangeDays, setRangeDays] = useState(30); + const { data, isLoading, error } = useGymStatsOverview(id, rangeDays); + + const rangeFilter = ( + setRangeDays(Number(e.target.value))} + aria-label={t('stats.rangeAria')} + > + {RANGE_OPTIONS.map((d) => ( + + {t('stats.rangeDays', { count: d })} + + ))} + + ); + useTopbar({ + title: t('stats.title'), + back: `/gyms/${id}`, + filters: [rangeFilter], + filterActive: rangeDays !== 30, + }); + + if (isLoading) return ; + if (error || !data) { + return ( + <> + + + {t('common:errorPrefix')} + {(error as Error).message} + + > + ); + } + + const { presence, members, activity } = data; + return ( + <> + {/* HERO-LITE: nazwa siłowni (tytuł h1 należy do topbaru) */} + + + {gymData?.gym.name ?? ''} + + + + + + + + + + + + + + + + + + + > + ); +} diff --git a/app/src/pages/gyms/Gyms.tsx b/app/src/pages/gyms/Gyms.tsx index d6c665f..201669b 100644 --- a/app/src/pages/gyms/Gyms.tsx +++ b/app/src/pages/gyms/Gyms.tsx @@ -1,29 +1,10 @@ import { useEffect, useState, type ReactNode } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { useQueryClient } from '@tanstack/react-query'; -import { - Building2, - Dumbbell, - MapPin, - Plus, - ThumbsDown, - ThumbsUp, - UserPlus, - Users, -} from 'lucide-react'; -import { - joinGym, - rateGym, - useGyms, - useGymInvitations, - useMyGymClaims, - useVirtualGyms, - withdrawGymClaim, - withdrawGymInvitation, -} from '../../api/queries'; +import { Building2, Dumbbell, MapPin, Plus, UserPlus, Users } from 'lucide-react'; +import { useGyms, useVirtualGyms } from '../../api/queries'; import { AuthImage } from '../../components/AuthImage'; -import type { Gym, GymClaim, GymInvitation, VirtualGym } from '../../api/types'; +import type { Gym, VirtualGym } from '../../api/types'; import { Badge, Button, @@ -31,19 +12,15 @@ import { EmptyState, ErrorText, H3, - ListRow, Loading, MetaItem, Tabs, } from '../../components/ui'; -import { useToast } from '../../components/toast'; import { useListSearch } from '../../store/list-search'; import { useTopbar } from '../../topbar'; import { dayShort, formatDayRange, normalizeAvailability } from '../../lib/availability'; import { GYM_ROLE } from '../../lib/labels'; import GymCreateModal from '../../components/gyms/GymCreateModal'; -import ClaimModal from '../../components/gyms/ClaimModal'; -import InviteGymModal from '../../components/gyms/InviteGymModal'; import JoinGymModal from '../../components/gyms/JoinGymModal'; type Tab = 'mine' | 'virtual'; @@ -203,264 +180,40 @@ function GymCard({ ); } -/* Głosy „Polecam/Nie polecam” z licznikami (aria-pressed). */ -function VoteButtons({ gym, onRate }: { gym: VirtualGym; onRate: (vote: 'UP' | 'DOWN') => void }) { - const { t } = useTranslation('gyms'); - return ( - - onRate('UP')} - className={`inline-flex cursor-pointer items-center gap-1.5 rounded-full border px-2.5 py-1.5 text-[0.875rem] font-semibold transition-colors ${ - gym.myVote === 'UP' - ? 'border-accent bg-accent/15 text-accent-text' - : 'border-line text-dim hover:text-ink hover:border-accent' - }`} - > - - {gym.up} - - onRate('DOWN')} - className={`inline-flex cursor-pointer items-center gap-1.5 rounded-full border px-2.5 py-1.5 text-[0.875rem] font-semibold transition-colors ${ - gym.myVote === 'DOWN' - ? 'border-danger bg-danger/15 text-danger' - : 'border-line text-dim hover:text-ink hover:border-accent' - }`} - > - - {gym.down} - - - ); -} - +/* Karta wirtualnej siłowni — CZYŚTA NAWIGACJA (1 kontrolka = 1 miejsce): + akcje (dołącz, głosy, zaproszenia, wniosek o weryfikację) żyją w menu + kontekstowym detailu. Tu zostają tylko dane: badge'e, członkowie, % poleceń + i status własnego wniosku jako tekst bez przycisków. */ function VirtualGymCard({ gym, - isOwner, isMember, - claim, - sentInvitations, - onInvite, + onClick, }: { gym: VirtualGym; - isOwner: boolean; isMember: boolean; - /** Oczekujący/odrzucony wniosek zalogowanego o weryfikację tej siłowni (z /gyms/claims). */ - claim: GymClaim | null; - sentInvitations: GymInvitation[]; - onInvite: () => void; + onClick: () => void; }) { - const queryClient = useQueryClient(); - const { push } = useToast(); const { t } = useTranslation('gyms'); - const [claimOpen, setClaimOpen] = useState(false); - const [busy, setBusy] = useState(false); - - const invalidate = () => - Promise.all([ - queryClient.invalidateQueries({ queryKey: ['gyms', 'virtual'] }), - queryClient.invalidateQueries({ queryKey: ['gyms'] }), - queryClient.invalidateQueries({ queryKey: ['gym-invitations'] }), - ]); - - const rate = async (vote: 'UP' | 'DOWN') => { - try { - await rateGym(gym.id, vote); - await invalidate(); - } catch (e) { - push((e as Error).message, 'error'); - } - }; - - const join = async () => { - setBusy(true); - try { - await joinGym(gym.id); - await invalidate(); - push(t('join.toastOk', { name: gym.name }), 'success'); - } catch (e) { - push((e as Error).message, 'error'); - } finally { - setBusy(false); - } - }; - - const withdrawClaim = async () => { - if (!claim) return; - setBusy(true); - try { - await withdrawGymClaim(claim.id); - await invalidate(); - push(t('detail.claimWithdrawnToast'), 'success'); - } catch (e) { - push((e as Error).message, 'error'); - } finally { - setBusy(false); - } - }; - - const withdrawInvitation = async (id: string) => { - try { - await withdrawGymInvitation(id); - await invalidate(); - push(t('invites.toastWithdrawn'), 'success'); - } catch (e) { - push((e as Error).message, 'error'); - } - }; - return ( 0 ? Math.round((gym.up / (gym.up + gym.down)) * 100) : null} extraBadges={ isMember ? {t('common:statuses.gymRole.MEMBER')} : null } > - {!gym.isPrivate && ( - - void rate(v)} /> - - )} - - - {!isMember && !gym.isPrivate && ( - void join()} disabled={busy}> - {t('join.submit')} - - )} - {gym.isPrivate && isOwner && ( - - {t('detail.actionInvite')} - - )} - {isOwner && !gym.isPrivate && gym.claimStatus === 'PENDING' && ( - <> - {t('page.claimPending')} - void withdrawClaim()} - disabled={busy} - > - {t('invites.withdraw')} - - > - )} - {isOwner && !gym.isPrivate && gym.claimStatus === 'REJECTED' && ( - <> - - {t('page.rejected')} - {gym.rejectReason ? `: ${gym.rejectReason}` : ''} - - setClaimOpen(true)}> - {t('page.resubmit')} - - > - )} - {isOwner && !gym.isPrivate && !gym.claimStatus && ( - setClaimOpen(true)}> - {t('detail.actionClaimVerify')} - - )} - {gym.isPrivate && isOwner && ( - setClaimOpen(true)} - onWithdraw={() => void withdrawClaim()} - busy={busy} - /> - )} - - - {gym.isPrivate && isOwner && sentInvitations.length > 0 && ( - - - {t('page.sentInvites')} - - - {sentInvitations.map((inv) => { - const name = - [inv.user?.firstName, inv.user?.lastName].filter(Boolean).join(' ') || - inv.user?.email || - '—'; - return ( - void withdrawInvitation(inv.id)} - > - {t('invites.withdraw')} - - } - /> - ); - })} - - - )} - - setClaimOpen(false)} - gym={{ id: gym.id, name: gym.name }} - initial={claim ?? null} - /> - - ); -} - -/** Status wniosku właściciela przy prywatnej VIRTUAL (po weryfikacji siłownia znika z listy). */ -function ClaimStatusInline({ - gym, - onResubmit, - onWithdraw, - busy, -}: { - gym: VirtualGym; - onResubmit: () => void; - onWithdraw: () => void; - busy: boolean; -}) { - const { t } = useTranslation('gyms'); - if (gym.claimStatus === 'PENDING') { - return ( - <> + {gym.claimStatus === 'PENDING' && ( {t('page.claimPending')} - - {t('invites.withdraw')} - - > - ); - } - if (gym.claimStatus === 'REJECTED') { - return ( - <> + )} + {gym.claimStatus === 'REJECTED' && ( {t('page.rejected')} {gym.rejectReason ? `: ${gym.rejectReason}` : ''} - - {t('page.resubmit')} - - > - ); - } - return ( - - {t('detail.actionClaimVerify')} - + )} + ); } @@ -470,19 +223,13 @@ export default function Gyms() { // „Moje siłownie” = WSZYSTKIE członkostwa (OWNER/TRAINER/MEMBER) z rolami. const { data: gymsData, isLoading: gymsLoading, error: gymsError } = useGyms(); const { data: virtualData, isLoading: virtualLoading, error: virtualError } = useVirtualGyms(); - const { data: invData } = useGymInvitations(); - const { data: claimsData } = useMyGymClaims(); const myGyms = gymsData?.gyms ?? []; const memberIds = new Set(myGyms.map((g) => g.id)); - const ownerIds = new Set(myGyms.filter((g) => g.roles.includes('OWNER')).map((g) => g.id)); const virtualGyms = virtualData?.gyms ?? []; - const sentGymInvitations = (invData?.invitations ?? []).filter((i) => i.direction === 'sent'); - const claimsByGym = new Map((claimsData?.claims ?? []).map((c) => [c.gymId, c])); const [createOpen, setCreateOpen] = useState(false); const [joinOpen, setJoinOpen] = useState(false); - const [inviteGym, setInviteGym] = useState<{ id: string; name: string } | null>(null); const [tab, setTab] = useState(null); useEffect(() => { @@ -605,11 +352,8 @@ export default function Gyms() { i.gym.id === g.id)} - onInvite={() => setInviteGym({ id: g.id, name: g.name })} + onClick={() => navigate(`/gyms/${g.id}`)} /> ))} @@ -620,7 +364,6 @@ export default function Gyms() { setCreateOpen(false)} /> setJoinOpen(false)} /> - {inviteGym && setInviteGym(null)} gym={inviteGym} />} > ); } diff --git a/app/src/pages/messages/Messages.tsx b/app/src/pages/messages/Messages.tsx index 559182d..c5571b0 100644 --- a/app/src/pages/messages/Messages.tsx +++ b/app/src/pages/messages/Messages.tsx @@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { ArrowUpDown, ChevronDown, MessageSquare, Users } from 'lucide-react'; -import { useConversations, useMe } from '../../api/queries'; +import { useConversations, useGymContactInbox, useMe } from '../../api/queries'; import { displayName, timeAgo } from '../../lib/format'; import { cn } from '../../lib/utils'; import { @@ -37,6 +37,8 @@ export default function Messages() { const navigate = useNavigate(); const { t } = useTranslation('messages'); const { data, isLoading, error } = useConversations(); + // Wątki kontaktu z właścicielami (tylko dla OWNER-ów siłowni; puste dla reszty). + const { data: ownerInboxData } = useGymContactInbox(); const { data: meData } = useMe(); const myId = meData?.user.id; const query = useListSearch((s) => s.queries.messages); @@ -260,6 +262,80 @@ export default function Messages() { ) : ( {renderRows(filtered)} ))} + + {/* trzecia sekcja: wątki kontaktu członek ↔ właściciele (widoczna tylko gdy są) */} + {(ownerInboxData?.conversations.length ?? 0) > 0 && + (() => { + const items = (ownerInboxData?.conversations ?? []).filter( + (c) => + !q || + c.counterpartName.toLowerCase().includes(q) || + c.gymName.toLowerCase().includes(q), + ); + if (items.length === 0) return null; + return ( + + + {t('gymOwnersSection')} + {items.length} + + + + {items.map((c) => { + const unread = c.unreadCount > 0; + return ( + navigate(`/gyms/${c.gymId}/contact?thread=${c.id}`)} + className="flex w-full cursor-pointer items-center gap-3 rounded-[10px] px-2 py-3.5 text-left transition-colors hover:bg-line/20" + > + + + {unread && ( + + )} + + + + + {c.counterpartName} + + {c.gymName} + + + {c.lastMessageAt && ( + + {timeAgo(c.lastMessageAt)} + + )} + + + + {c.lastMessageBody ?? '—'} + + {unread && ( + + {c.unreadCount} + + )} + + + + ); + })} + + + + ); + })()} > ); } diff --git a/app/src/topbar/GroupButton.tsx b/app/src/topbar/GroupButton.tsx index 522017b..493e569 100644 --- a/app/src/topbar/GroupButton.tsx +++ b/app/src/topbar/GroupButton.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from 'react'; import type { ReactNode } from 'react'; -import type { LucideIcon } from 'lucide-react'; +import { ChevronDown, type LucideIcon } from 'lucide-react'; import { cn } from '../lib/utils'; /** Telefon ((null); @@ -92,6 +99,7 @@ export function GroupButton({ return ( {/* lg+ (lub md+ przy alwaysInlineFromMd) treść grupy zawsze inline; + collapsed: na lg+ tylko po otwarciu, jako dropdown pod kontrolką; md–lg akordeon od ikonki; telefon: domyślnie panel nad dolnym paskiem (w górę), flatOnMobile: płaski rząd bezpośrednio w pasku */} @@ -99,7 +107,10 @@ export function GroupButton({ className={cn( 'topbar-expand items-center gap-2', flat || open ? 'flex' : 'hidden', - alwaysInlineFromMd ? 'md:flex' : 'lg:flex', + collapsed ? undefined : alwaysInlineFromMd ? 'md:flex' : 'lg:flex', + collapsed && + open && + 'lg:absolute lg:right-0 lg:top-full lg:z-50 lg:mt-2 lg:flex-col lg:w-max lg:min-w-[13rem] lg:rounded-2xl lg:border lg:border-line lg:bg-card lg:p-2 lg:shadow-[var(--shadow)]', flat ? 'max-md:static max-md:flex-row max-md:items-center max-md:gap-2' : // telefon: panel grupy renderuje Topbar (w pigułce na dole) — ten nie żyje + {collapsed && ( + + {label} + + )} + {collapsed && } {active && ( )} diff --git a/app/src/topbar/Topbar.tsx b/app/src/topbar/Topbar.tsx index 5b28d65..5aa2a1d 100644 --- a/app/src/topbar/Topbar.tsx +++ b/app/src/topbar/Topbar.tsx @@ -261,8 +261,10 @@ export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) { key={g.id} icon={g.icon} label={g.label} + active={g.active} open={openGroup === `grp:${g.id}`} onToggle={() => toggle(`grp:${g.id}`)} + collapsed={g.collapsed} > {g.actions.map((action) => ( diff --git a/app/src/topbar/types.ts b/app/src/topbar/types.ts index 57a9544..63fe417 100644 --- a/app/src/topbar/types.ts +++ b/app/src/topbar/types.ts @@ -25,6 +25,13 @@ export interface TopbarCustomGroup { label: string; icon: LucideIcon; actions: TopbarAction[]; + /** + * lg+: grupa zwinięta do jednej kontrolki (ikona + etykieta + strzałka), + * otwarty panel jako dropdown. Poniżej lg bez zmian (akordeon/pigułka). + */ + collapsed?: boolean; + /** Kropka aktywności przy ikonie grupy (np. oddany głos w ocenie). */ + active?: boolean; } /** diff --git a/app/test/e2e/gym-contact.spec.ts b/app/test/e2e/gym-contact.spec.ts new file mode 100644 index 0000000..a7d05a4 --- /dev/null +++ b/app/test/e2e/gym-contact.spec.ts @@ -0,0 +1,100 @@ +import { test, expect } from './fixtures'; +import { mockApi } from './mock-api'; + +async function login(page: import('@playwright/test').Page) { + await page.goto('/login'); + await page.locator('input[type="email"]').fill('test@fitos.pl'); + await page.locator('input[type="password"]').fill('haslo123'); + await page.getByRole('button', { name: 'Zaloguj' }).click(); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); +} + +const THREAD_ROW = { + id: 'gconv-1', + gymId: 'gym-1', + gymName: 'Żelazna Świątynia', + userId: 'trainee-1', + counterpartName: 'Anna Nowak', + lastMessageBody: 'Kiedy otwarte?', + lastMessageAt: '2026-10-20T12:00:00.000Z', + unreadCount: 1, +}; + +const INBOX = { + conversations: [THREAD_ROW], +}; + +const OWNER_THREADS = { + role: 'owner', + threads: [THREAD_ROW], +}; + +const MEMBER_THREAD = { + role: 'owner', + conversation: { + id: 'gconv-1', + gymId: 'gym-1', + gymName: 'Żelazna Świątynia', + userId: 'trainee-1', + memberName: 'Anna Nowak', + createdAt: '2026-10-20T10:00:00.000Z', + updatedAt: '2026-10-20T12:00:00.000Z', + }, + messages: [ + { + id: 'gm1', + senderId: 'trainee-1', + senderName: 'Anna Nowak', + body: 'Kiedy otwarte?', + createdAt: '2026-10-20T12:00:00.000Z', + }, + ], + canReply: true, +}; + +test('kontakt: członek dołącza do VIRTUAL i pisze pierwszy wątek', async ({ page }) => { + mockApi(page); + await login(page); + await page.getByRole('link', { name: 'Siłownie' }).click(); + await page.getByRole('button', { name: /Wirtualne/ }).click(); + await page.getByRole('link', { name: 'Wirtualna Alfa' }).click(); + + // dołączenie z menu detalu → akcja kontaktu dostępna + await page.getByRole('button', { name: 'Dołącz', exact: true }).click(); + await expect(page.getByText('Dołączono do siłowni: Wirtualna Alfa')).toBeVisible(); + await page.getByRole('button', { name: 'Napisz do właścicieli' }).click(); + + // strona kontaktu: nagłówek „Właściciele — …” + leniwy pusty stan + await expect(page.getByText('Właściciele — Wirtualna Alfa')).toBeVisible(); + await expect(page.getByText('Brak wiadomości — napisz pierwszą.')).toBeVisible(); + + // komposer: wysyłka tworzy wątek i bąbelek (stateful mock) + await page.getByRole('textbox', { name: 'Treść wiadomości' }).fill('Czy są wolne miejsca po 18?'); + await page.getByRole('button', { name: 'Wyślij' }).click(); + await expect(page.getByText('Czy są wolne miejsca po 18?')).toBeVisible(); +}); + +test('kontakt: skrzynka właściciela w komunikatorze prowadzi do wątku', async ({ page }) => { + mockApi(page, { + gymContact: OWNER_THREADS, + gymContactInbox: INBOX, + gymContactThread: MEMBER_THREAD, + }); + await login(page); + await page.getByRole('link', { name: 'Komunikator' }).click(); + + // sekcja „Właściciele siłowni”: rozmówca + ostatnia wiadomość + await expect(page.getByRole('heading', { name: 'Właściciele siłowni' })).toBeVisible(); + const section = page.locator('section').filter({ hasText: 'Właściciele siłowni' }); + const row = section.getByRole('button', { name: /Anna Nowak/ }); + await expect(row).toContainText('Kiedy otwarte?'); + await row.click(); + + // wątek właściciela: strumień członka + komposer odpowiedzi + await expect(page).toHaveURL(/\/gyms\/gym-1\/contact\?thread=gconv-1/); + await expect(page.getByText('Anna Nowak').first()).toBeVisible(); + await expect(page.getByText('Kiedy otwarte?')).toBeVisible(); + await page.getByRole('textbox', { name: 'Treść wiadomości' }).fill('Codziennie 6–22.'); + await page.getByRole('button', { name: 'Wyślij' }).click(); + await expect(page.getByText('Codziennie 6–22.')).toBeVisible(); +}); diff --git a/app/test/e2e/gym-stats.spec.ts b/app/test/e2e/gym-stats.spec.ts new file mode 100644 index 0000000..fa17524 --- /dev/null +++ b/app/test/e2e/gym-stats.spec.ts @@ -0,0 +1,53 @@ +import { test, expect } from './fixtures'; +import { mockApi } from './mock-api'; + +async function loginToOwnedGym(page: import('@playwright/test').Page) { + mockApi(page); + await page.goto('/login'); + await page.locator('input[type="email"]').fill('test@fitos.pl'); + await page.locator('input[type="password"]').fill('haslo123'); + await page.getByRole('button', { name: 'Zaloguj' }).click(); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + await page.getByRole('link', { name: 'Siłownie' }).click(); + await page.getByRole('link', { name: 'Żelazna Świątynia' }).click(); +} + +test('statystyki właściciela: kafelek prowadzi do podstrony z KPI i heatmapą', async ({ page }) => { + await loginToOwnedGym(page); + + // REAL + właściciel: czwarty kafelek sekcji „Statystyki” + await page.getByRole('link', { name: 'Statystyki' }).click(); + await expect(page).toHaveURL(/\/gyms\/gym-1\/stats/); + + // KPI (scope do treści — topbar/dolny pasek mogą powielać teksty poza main) + const main = page.getByRole('main'); + await expect(main.getByText('Wizyty', { exact: true })).toBeVisible(); + await expect(main.getByText('Wizyty / dzień')).toBeVisible(); + await expect(main.getByText('Śr. pobyt')).toBeVisible(); + await expect(main.getByText('Członkowie', { exact: true })).toBeVisible(); + await expect(main.getByText('Nowi w okresie')).toBeVisible(); + await expect(main.getByText('Sesje ukończone')).toBeVisible(); + await expect(main.getByText('Ćwiczący')).toBeVisible(); + + // heatmapa dzień × godzina z liczbą w tytule kafla + await expect(page.getByText('Bytność (dzień × godzina)')).toBeVisible(); + await expect(page.getByTitle('Poniedziałek, 18:00 — 3 wizyty')).toBeVisible(); +}); + +test('statystyki właściciela: filtr okresu przebudowuje zapytanie', async ({ page }) => { + await loginToOwnedGym(page); + await page.getByRole('link', { name: 'Statystyki' }).click(); + + await expect(page.getByTitle('Poniedziałek, 18:00 — 3 wizyty')).toBeVisible(); + await page.getByRole('combobox', { name: 'Zakres statystyk' }).selectOption('7'); + // po zmianie okresu (7 dni) zapytanie odświeża dane — heatmapa bez błędu konsoli + await expect(page.getByTitle('Poniedziałek, 18:00 — 3 wizyty')).toBeVisible(); +}); + +test('statystyki właściciela: pozycja w zwiniętej grupie Zarządzaj', async ({ page }) => { + await loginToOwnedGym(page); + + // grupa Zarządzaj (collapsed na lg+) zawiera pozycję Statystyki + await page.getByRole('button', { name: 'Zarządzaj' }).click(); + await expect(page.getByRole('button', { name: 'Statystyki' })).toBeVisible(); +}); diff --git a/app/test/e2e/gyms.spec.ts b/app/test/e2e/gyms.spec.ts index d5f74d4..e8572d3 100644 --- a/app/test/e2e/gyms.spec.ts +++ b/app/test/e2e/gyms.spec.ts @@ -112,7 +112,8 @@ test('właściciel ma menu „Siłownie" i zarządza swoją siłownią', async ( await expect(page.getByText('Mokotowska 12A')).toBeVisible(); await expect(page.getByText('00-900 Warszawa')).toBeVisible(); - // wyjątek dodawany z menu kontekstowego (grupa „Zarządzaj” inline na lg+ → modal „Informacje”) + // wyjątek dodawany z menu kontekstowego (grupa „Zarządzaj” na lg+ zwinięta do kontrolki → dropdown → modal „Informacje”) + await page.getByRole('button', { name: 'Zarządzaj' }).click(); await page.getByRole('button', { name: 'Informacje' }).click(); const excDialog = page.getByRole('dialog'); await excDialog.locator('input[type="date"]').fill('2026-09-01'); diff --git a/app/test/e2e/mock-api.ts b/app/test/e2e/mock-api.ts index b861d87..11aa496 100644 --- a/app/test/e2e/mock-api.ts +++ b/app/test/e2e/mock-api.ts @@ -914,6 +914,14 @@ export interface MockApiOptions { gymAnnouncements?: unknown; /** Ciało GET /gyms/:id/equipment-usage (domyślnie: brak wierszy). */ equipmentUsage?: { equipment: unknown[] }; + /** Ciało GET /gyms/:id/contact (member view lub owner threads; domyślnie: stateful member lazy). */ + gymContact?: unknown; + /** Ciało GET /gym-contact/conversations (skrzynka właściciela; domyślnie: wyprowadzone z memberSends). */ + gymContactInbox?: unknown; + /** Baza ciała GET /gym-contact/conversations/:id (domyślnie: wątek członka z memberSends). */ + gymContactThread?: { role: string; conversation?: unknown; messages: unknown[]; canReply?: boolean }; + /** Ciało GET /gyms/:id/stats/overview (domyślnie: przykładowe KPI REAL + heatmapa). */ + gymStats?: unknown; } /** @@ -946,6 +954,10 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { presenceStats, gymAnnouncements, equipmentUsage, + gymContact, + gymContactInbox, + gymContactThread, + gymStats, } = opts; // Stateful: bytność (check-in) — aktywna obecność + zamknięte wizyty; occupancy liczy się z niej. @@ -1188,13 +1200,17 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { }), ); - page.route('**/api/v1/gyms/*/join', (route) => - route.fulfill({ + page.route('**/api/v1/gyms/*/join', (route) => { + const req = route.request(); + if (req.method() !== 'POST') return route.fallback(); + const gymId = req.url().match(/gyms\/([^/]+)\/join/)?.[1] ?? TEST_GYM_JOINABLE.id; + joinedGyms.add(gymId); + return route.fulfill({ status: 201, contentType: 'application/json', - body: JSON.stringify({ membership: { gymId: TEST_GYM_JOINABLE.id, roles: ['MEMBER'] } }), - }), - ); + body: JSON.stringify({ membership: { gymId, roles: ['MEMBER'] } }), + }); + }); page.route('**/api/v1/equipment', (route) => route.fulfill({ @@ -1890,6 +1906,201 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) { body: JSON.stringify({ plan: { id: planId, gym: gymId ? { id: gymId, name: info!.name } : null } }), }); }); + + // ---------- kontakt członek ↔ właściciele + statystyki właściciela ---------- + interface GymContactMsg { + id: string; + senderId: string; + senderName: string; + body: string; + createdAt: string; + } + const MEMBER_NAME = `${TEST_USER.firstName} ${TEST_USER.lastName}`; + const OWNER_NAME = 'Marek Trener'; + // stateful: wysłane przez członka (TEST_USER) i przez właściciela (odpowiedzi) + const memberSends: GymContactMsg[] = []; + const ownerReplies: GymContactMsg[] = []; + let lastSendGymId = ''; + // dołączenia (POST /gyms/:id/join) — role w detalu VIRTUAL publicznej + const joinedGyms = new Set(); + const gymNameOf = (gymId: string) => + findVirtualGym(gymId)?.name ?? + (gymId === TEST_GYM_OWNED.id + ? TEST_GYM_OWNED.name + : gymId === TEST_GYM_JOINABLE.id + ? TEST_GYM_JOINABLE.name + : gymId); + const memberConversation = () => + memberSends.length === 0 + ? null + : { + id: 'gconv-1', + gymId: lastSendGymId, + gymName: gymNameOf(lastSendGymId), + userId: TEST_USER.id, + memberName: MEMBER_NAME, + createdAt: memberSends[0].createdAt, + updatedAt: memberSends[memberSends.length - 1].createdAt, + }; + + // GET /gyms/:id/contact — member (leniwy wątek) albo owner (lista wątków, gdy podano ciało). + page.route('**/api/v1/gyms/*/contact', (route) => { + if (gymContact !== undefined) + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymContact) }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + role: 'member', + conversation: memberConversation(), + messages: [...memberSends], + canReply: true, + }), + }); + }); + + // POST /gyms/:id/contact/messages — członek inicjuje/odpowiada (upsert per [gymId,userId]). + page.route('**/api/v1/gyms/*/contact/messages', (route) => { + const req = route.request(); + if (req.method() !== 'POST') return route.fallback(); + const gymId = req.url().match(/gyms\/([^/]+)\/contact\/messages/)?.[1] ?? ''; + lastSendGymId = gymId; + const body = (req.postDataJSON() ?? {}) as { body?: string }; + const msg: GymContactMsg = { + id: `gmsg-m-${memberSends.length}`, + senderId: TEST_USER.id, + senderName: MEMBER_NAME, + body: body.body ?? '', + createdAt: new Date().toISOString(), + }; + memberSends.push(msg); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ conversation: memberConversation() }), + }); + }); + + // GET /gym-contact/conversations — skrzynka właściciela. + page.route('**/api/v1/gym-contact/conversations', (route) => { + if (gymContactInbox !== undefined) + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymContactInbox) }); + const conv = memberConversation(); + const last = memberSends[memberSends.length - 1]; + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + conversations: conv + ? [ + { + id: conv.id, + gymId: conv.gymId, + gymName: conv.gymName, + userId: conv.userId, + counterpartName: MEMBER_NAME, + lastMessageBody: last?.body ?? null, + lastMessageAt: last?.createdAt ?? null, + unreadCount: 0, + }, + ] + : [], + }), + }); + }); + + // POST /gym-contact/conversations/:id/messages — odpowiedź właściciela. + page.route('**/api/v1/gym-contact/conversations/*/messages', (route) => { + const req = route.request(); + if (req.method() !== 'POST') return route.fallback(); + const body = (req.postDataJSON() ?? {}) as { body?: string }; + const msg: GymContactMsg = { + id: `gmsg-o-${ownerReplies.length}`, + senderId: 'owner-1', + senderName: OWNER_NAME, + body: body.body ?? '', + createdAt: new Date().toISOString(), + }; + ownerReplies.push(msg); + return route.fulfill({ + status: 201, + contentType: 'application/json', + body: JSON.stringify({ message: msg }), + }); + }); + + // GET /gym-contact/conversations/:id — pojedynczy wątek (read-mark po stronie API pominięty). + page.route('**/api/v1/gym-contact/conversations/*', (route) => { + if (gymContactThread !== undefined) + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ ...gymContactThread, messages: [...(gymContactThread.messages ?? []), ...ownerReplies] }), + }); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + role: 'member', + conversation: memberConversation(), + messages: [...memberSends], + canReply: true, + }), + }); + }); + + // DELETE /gym-contact/messages/:id — tylko autor (twardy delete). + page.route('**/api/v1/gym-contact/messages/*', (route) => { + const id = route.request().url().match(/messages\/([^/?]+)/)?.[1]; + const mi = memberSends.findIndex((m) => m.id === id); + if (mi >= 0) memberSends.splice(mi, 1); + const oi = ownerReplies.findIndex((m) => m.id === id); + if (oi >= 0) ownerReplies.splice(oi, 1); + return route.fulfill({ status: 204 }); + }); + + // GET /gyms/:id/stats/overview — KPI + heatmapa (REAL, właściciel/admin). + page.route('**/api/v1/gyms/*/stats/overview*', (route) => { + const body = + gymStats ?? { + gym: { id: 'gym-1', name: TEST_GYM_OWNED.name, kind: 'REAL', capacity: 50 }, + presence: { + visits: 42, + visitsPerDay: 1.4, + avgStayMinutes: 75, + peak: 5, + live: 2, + heatmap: [{ day: 0, hour: 18, count: 3 }], + }, + members: { total: 12, byRole: { OWNER: 1, TRAINER: 2, MEMBER: 9 }, newInRange: 4 }, + activity: { sessionsStarted: 20, sessionsCompleted: 17, sessionsAbandoned: 3, uniqueExercisers: 6 }, + }; + return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) }); + }); + + // Detale publicznej/prywatnej VIRTUAL (GET /gyms/gym-v1|gym-v2) — przeniesione + // akcje (dołącz/ocena/zaproszenia/claim) operują na detalu, więc GET musi + // zwracać siłownię + role + isAdmin (rejestrowane po ogólnym gyms/*). + page.route('**/api/v1/gyms/gym-v1', (route) => { + const g = findVirtualGym('gym-v1'); + if (!g) return route.fallback(); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + gym: { ...g, photos: [] }, + roles: joinedGyms.has('gym-v1') ? ['MEMBER'] : [], + isAdmin: false, + }), + }); + }); + page.route('**/api/v1/gyms/gym-v2', (route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ gym: { ...privateVirtualGym, photos: [] }, roles: ['OWNER'], isAdmin: false }), + }), + ); } /** diff --git a/app/test/e2e/presence.spec.ts b/app/test/e2e/presence.spec.ts index d33ab9c..59a4fd8 100644 --- a/app/test/e2e/presence.spec.ts +++ b/app/test/e2e/presence.spec.ts @@ -103,7 +103,8 @@ test('modal kodu QR właściciela pokazuje kod i link do strony check-inu', asyn await login(page); await openGymDetail(page); - // akcja „Kod QR” grupy „Zarządzaj” (inline na lg+; tylko REAL + OWNER) + // akcja „Kod QR” grupy „Zarządzaj” (na lg+ zwinięta do kontrolki → dropdown; tylko REAL + OWNER) + await page.getByRole('button', { name: 'Zarządzaj' }).click(); await page.getByRole('button', { name: 'Kod QR' }).click(); const dialog = page.getByRole('dialog'); diff --git a/app/test/e2e/virtual-gyms.spec.ts b/app/test/e2e/virtual-gyms.spec.ts index c0db3e4..f5648c3 100644 --- a/app/test/e2e/virtual-gyms.spec.ts +++ b/app/test/e2e/virtual-gyms.spec.ts @@ -3,15 +3,11 @@ import { mockApi, TEST_GYM_OWNED, TEST_GYM_VIRTUAL_PRIVATE, - TEST_USER, } from './mock-api'; -// Test user owns a REAL gym + a private VIRTUAL gym (to test invitations/claims). +// Test user owns a REAL gym + a private VIRTUAL gym (invitations/claims via detail menu). const MY_GYMS = { - gyms: [ - TEST_GYM_OWNED, - { ...TEST_GYM_VIRTUAL_PRIVATE, roles: ['OWNER'] }, - ], + gyms: [TEST_GYM_OWNED, { ...TEST_GYM_VIRTUAL_PRIVATE, roles: ['OWNER'] }], }; async function loginToGyms(page: import('@playwright/test').Page) { @@ -29,92 +25,109 @@ async function openVirtualTab(page: import('@playwright/test').Page) { await page.getByRole('button', { name: /Wirtualne/ }).click(); } -test('wirtualne siłownie: lista, kciuki góra/dół i cofnięcie', async ({ page }) => { +async function openVirtualGymDetail(page: import('@playwright/test').Page, name: string) { + await openVirtualTab(page); + await page.getByRole('link', { name }).click(); +} + +test('wirtualne siłownie: karty listy są czysto nawigacyjne (bez akcji)', async ({ page }) => { await loginToGyms(page); await openVirtualTab(page); - // publiczna wirtualna siłownia z licznikami głosów - const card = page.getByRole('link', { name: 'Wirtualna Alfa' }).locator('..').locator('..'); - await expect(page.getByText('Wirtualna Alfa')).toBeVisible(); - await expect(card.getByText('Wirtualna', { exact: true })).toBeVisible(); - - // początkowo: 2 góra, 1 dół, użytkownik nie głosował - // exact: „Polecam: …” jest podłańcuchem „Nie polecam: …” - const upBtn = page.getByRole('button', { name: 'Polecam: Wirtualna Alfa', exact: true }); - const downBtn = page.getByRole('button', { name: 'Nie polecam: Wirtualna Alfa', exact: true }); - await expect(upBtn).toContainText('2'); - await expect(downBtn).toContainText('1'); - - // klik „góra” → 3, głos aktywny - await upBtn.click(); - await expect(upBtn).toContainText('3'); - - // ponowne kliknięcie cofa głos → 2 - await upBtn.click(); - await expect(upBtn).toContainText('2'); - - // klik „dół” → 2 (dół rośnie), a „góra” wraca do 2 - await downBtn.click(); - await expect(downBtn).toContainText('2'); + // karta = sam Link: brak VoteButtons/Dołącz/Zaproś/przycisków claimu w treści + const card = page.locator('[data-slot="gym-card"]', { + has: page.getByRole('link', { name: 'Wirtualna Alfa' }), + }); + await expect(card).toBeVisible(); + await expect(card.getByRole('button')).toHaveCount(0); + // status claimu jako tekst bez przycisków + const privateCard = page.locator('[data-slot="gym-card"]', { + has: page.getByRole('link', { name: 'Moja Prywatna Wirtualna' }), + }); + await expect(privateCard.getByRole('button')).toHaveCount(0); }); -test('wirtualne siłownie: dołączenie do publicznej', async ({ page }) => { +test('wirtualne siłownie: ocena publicznej VIRTUAL z menu kontekstowego detalu', async ({ + page, +}) => { await loginToGyms(page); - await openVirtualTab(page); + await openVirtualGymDetail(page, 'Wirtualna Alfa'); - // przycisk w karcie (zakładka „Dołącz” ma tę samą nazwę) - await page - .locator('[data-slot="gym-card"]', { has: page.getByRole('link', { name: 'Wirtualna Alfa' }) }) - .getByRole('button', { name: 'Dołącz', exact: true }) - .click(); + // grupa „Ocena” (inline na lg+): Polecam / Nie polecam + const up = page.getByRole('button', { name: 'Polecam', exact: true }); + const down = page.getByRole('button', { name: 'Nie polecam', exact: true }); + await expect(up).toBeEnabled(); + await expect(down).toBeEnabled(); + + // głos w górę → kontrolka blokowana (oddany głos) + await up.click(); + await expect(up).toBeDisabled(); + + // zmiana głosu w dół → Nie polecam blokowane, Polecam odblokowane + await down.click(); + await expect(down).toBeDisabled(); + await expect(up).toBeEnabled(); +}); + +test('wirtualne siłownie: dołączenie z menu detalu odblokowuje kontakt z właścicielami', async ({ + page, +}) => { + await loginToGyms(page); + await openVirtualGymDetail(page, 'Wirtualna Alfa'); + + // nie-członek: akcja „Dołącz” w grupie Akcje (niewielka — ikona UserPlus) + await page.getByRole('button', { name: 'Dołącz', exact: true }).click(); await expect(page.getByText('Dołączono do siłowni: Wirtualna Alfa')).toBeVisible(); + + // członek: „Dołącz” znika, pojawia się akcja kontaktu + await expect(page.getByRole('button', { name: 'Dołącz', exact: true })).toHaveCount(0); + await expect(page.getByRole('button', { name: 'Napisz do właścicieli' })).toBeVisible(); }); -test('wirtualne siłownie: właściciel składa i wycofuje wniosek o weryfikację', async ({ page }) => { +test('wirtualne siłownie: właściciel składa i wycofuje wniosek z menu detalu', async ({ page }) => { await loginToGyms(page); - await openVirtualTab(page); - - // prywatna wirtualna, której jest właścicielem — bez ocen, z przyciskiem wniosku - await expect(page.getByText('Moja Prywatna Wirtualna')).toBeVisible(); - await expect(page.getByText('Prywatna', { exact: true })).toBeVisible(); + await openVirtualGymDetail(page, 'Moja Prywatna Wirtualna'); + // akcja claimu spoza grupy Zarządzaj — w grupie Akcje (inline na lg+) await page.getByRole('button', { name: 'Złóż wniosek o weryfikację' }).click(); const dialog = page.getByRole('dialog'); await expect(dialog).toBeVisible(); // tryb weryfikacji: opis wymagany await dialog.getByPlaceholder('Krótki opis').fill('Prowadzę tę siłownię'); - // exact: na karcie jest też „Złóż wniosek o weryfikację” await dialog.getByRole('button', { name: 'Złóż wniosek', exact: true }).click(); await expect(page.getByText('Wniosek złożony')).toBeVisible(); - // status PENDING + wycofanie - await expect(page.getByText('Wniosek oczekuje na weryfikację')).toBeVisible(); - await page.getByRole('button', { name: 'Wycofaj' }).click(); + // po złożeniu: akcja zmienia się na wycofanie + await page.getByRole('button', { name: 'Wycofaj wniosek' }).click(); await expect(page.getByText('Wniosek wycofany')).toBeVisible(); await expect(page.getByRole('button', { name: 'Złóż wniosek o weryfikację' })).toBeVisible(); }); -test('wirtualne siłownie: zaproszenie usera do prywatnej + wycofanie', async ({ page }) => { +test('wirtualne siłownie: zaproszenie + wycofanie w modalu Zarządzaj → Zaproszenia', async ({ + page, +}) => { await loginToGyms(page); - await openVirtualTab(page); + await openVirtualGymDetail(page, 'Moja Prywatna Wirtualna'); + + // grupa Zarządzaj zwinięta na lg+ → dropdown → Zaproszenia (bez karty w treści) + await page.getByRole('button', { name: 'Zarządzaj' }).click(); + await page.getByRole('button', { name: 'Zaproszenia' }).click(); - await page.getByRole('button', { name: 'Zaproś usera' }).click(); const dialog = page.getByRole('dialog'); await expect(dialog).toBeVisible(); await dialog.getByPlaceholder('np. Jan').fill('Jan'); await dialog.getByPlaceholder('np. Kowalski').fill('Kowalski'); - // wynik szukajki + // wynik szukajki → zaproszenie await expect(dialog.getByText('Jan Kowalski')).toBeVisible(); await dialog.getByRole('button', { name: 'Zaproś' }).click(); await expect(page.getByText('Zaproszono: Jan Kowalski')).toBeVisible(); - // modal zostaje otwarty (można zapraszać dalej) — zamykamy, by kliknąć „Wycofaj” na karcie - await dialog.getByRole('button', { name: 'Zamknij' }).click(); - - // lista wysłanych zaproszeń na karcie + wycofanie - await expect(page.getByText('Wysłane zaproszenia')).toBeVisible(); - await page.getByRole('button', { name: 'Wycofaj' }).click(); + // sekcja „Wysłane zaproszenia” w modalu + wycofanie z potwierdzeniem + await expect(dialog.getByText('Wysłane zaproszenia')).toBeVisible(); + await dialog.getByRole('button', { name: 'Wycofaj' }).click(); + const confirm = page.getByRole('dialog').filter({ hasText: 'Wycofać zaproszenie dla' }); + await confirm.getByRole('button', { name: 'Wycofaj' }).click(); await expect(page.getByText('Zaproszenie wycofane')).toBeVisible(); }); diff --git a/app/test/gym-contact.test.tsx b/app/test/gym-contact.test.tsx new file mode 100644 index 0000000..26bb5e2 --- /dev/null +++ b/app/test/gym-contact.test.tsx @@ -0,0 +1,238 @@ +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import GymContactPage from '../src/pages/gyms/GymContactPage'; +import { setAccessToken } from '../src/api/client'; +import type { Gym, GymContactMessage } from '../src/api/types'; + +const ME = { + id: 'u-member', + email: 'member@test.local', + firstName: 'Jan', + lastName: 'Członek', +}; + +const GYM: Gym = { + id: 'g1', + name: 'Gym A', + location: null, + availability: null, + capacity: 10, + kind: 'REAL', + isPrivate: false, + equipment: [], + coverPhoto: null, +}; + +const CONVERSATION = { + id: 'c1', + gymId: 'g1', + gymName: 'Gym A', + userId: ME.id, + memberName: 'Jan Członek', + createdAt: '2026-10-20T10:00:00.000Z', + updatedAt: '2026-10-20T12:00:00.000Z', +}; + +const OWNER_MSG: GymContactMessage = { + id: 'm1', + senderId: 'u-owner', + senderName: 'Marek Właściciel', + body: 'Witamy w siłowni!', + createdAt: '2026-10-20T12:00:00.000Z', +}; + +function jsonResponse(status: number, body: unknown) { + if (status === 204) return new Response(null, { status }); + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +interface ContactMockOptions { + role: 'member' | 'owner'; + /** Wątek członka: null = jeszcze nie utworzony (lazy). */ + conversation?: typeof CONVERSATION | null; + /** Widok właściciela: lista wątków. */ + threads?: unknown[]; + /** Odpowiedź GET /gyms/:id/contact: 200 albo błąd dostępu. */ + status?: number; +} + +/** Mock endpointów kontaktu; zwraca listę wysłanych POST-ów. */ +function stubContactFetch(options: ContactMockOptions) { + const posts: { url: string; body: unknown }[] = []; + let extraMemberMessages: GymContactMessage[] = []; + let extraThreadMessages: GymContactMessage[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(String(input), 'http://localhost').pathname.replace(/^\/api\/v1/, ''); + const method = init?.method || 'GET'; + if (method === 'POST' && path.endsWith('/contact/messages')) { + const body = JSON.parse(String(init?.body)) as { body: string }; + posts.push({ url: path, body }); + extraMemberMessages = [ + ...extraMemberMessages, + { + id: `sent-${extraMemberMessages.length}`, + senderId: ME.id, + senderName: 'Jan Członek', + body: body.body, + createdAt: new Date().toISOString(), + }, + ]; + return jsonResponse(201, { conversation: CONVERSATION }); + } + if (method === 'POST' && /\/gym-contact\/conversations\/[^/]+\/messages$/.test(path)) { + const body = JSON.parse(String(init?.body)) as { body: string }; + posts.push({ url: path, body }); + extraThreadMessages = [ + ...extraThreadMessages, + { + id: `reply-${extraThreadMessages.length}`, + senderId: 'u-owner', + senderName: 'Marek Właściciel', + body: body.body, + createdAt: new Date().toISOString(), + }, + ]; + return jsonResponse(201, { message: extraThreadMessages[0] }); + } + if (path.endsWith('/contact')) { + if (options.status && options.status !== 200) + return jsonResponse(options.status, { + error: { code: 'FORBIDDEN', message: 'Tylko członkowie mogą pisać' }, + }); + if (options.role === 'owner') + return jsonResponse(200, { role: 'owner', threads: options.threads ?? [] }); + // lazy: brak wątku do pierwszej wysłanej wiadomości (upsert po stronie API) + const hasPrior = options.conversation !== null; + const started = extraMemberMessages.length > 0; + const conversation = hasPrior || started ? CONVERSATION : null; + return jsonResponse(200, { + role: 'member', + conversation, + messages: [...(hasPrior ? [OWNER_MSG] : []), ...extraMemberMessages], + canReply: true, + }); + } + if (/^\/gym-contact\/conversations\/[^/]+$/.test(path)) + return jsonResponse(200, { + role: 'owner', + conversation: CONVERSATION, + messages: [OWNER_MSG, ...extraThreadMessages], + canReply: true, + }); + if (path === '/me') return jsonResponse(200, { user: ME, memberships: [] }); + if (/^\/gyms\/[^/]+$/.test(path)) + return jsonResponse(200, { gym: { ...GYM, photos: [] }, roles: ['MEMBER'], isAdmin: false }); + throw new Error(`Unexpected fetch: ${path}`); + }), + ); + return posts; +} + +function renderPage(initialPath = '/gyms/g1/contact') { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, refetchInterval: false } }, + }); + return render( + + + + } /> + + + , + ); +} + +beforeEach(() => { + setAccessToken('tok'); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Kontakt z właścicielami — wątek członka', () => { + it('pokazuje strumień wiadomości z etykietą nadawcy i nagłówkiem „Właściciele — …”', async () => { + stubContactFetch({ role: 'member' }); + renderPage(); + expect(await screen.findByText('Witamy w siłowni!')).toBeInTheDocument(); + expect(screen.getByText('Marek Właściciel')).toBeInTheDocument(); + expect(await screen.findByText('Właściciele — Gym A')).toBeInTheDocument(); + }); + + it('member wysyła wiadomość → POST /gyms/:id/contact/messages i nowy bąbelek', async () => { + const posts = stubContactFetch({ role: 'member' }); + const user = userEvent.setup(); + renderPage(); + expect(await screen.findByText('Witamy w siłowni!')).toBeInTheDocument(); + + await user.type(screen.getByRole('textbox', { name: 'Treść wiadomości' }), 'Kiedy otwarte?'); + await user.click(screen.getByRole('button', { name: /Wyślij/ })); + + expect(await screen.findByText('Kiedy otwarte?')).toBeInTheDocument(); + expect(posts.some((p) => p.url.includes('/gyms/g1/contact/messages'))).toBe(true); + }); + + it('brak wątku (lazy null) → pusty stan z CTA i działający komposer', async () => { + const posts = stubContactFetch({ role: 'member', conversation: null }); + const user = userEvent.setup(); + renderPage(); + expect(await screen.findByText('Brak wiadomości — napisz pierwszą.')).toBeInTheDocument(); + + await user.type(screen.getByRole('textbox', { name: 'Treść wiadomości' }), 'Cześć!'); + await user.click(screen.getByRole('button', { name: /Wyślij/ })); + expect(await screen.findByText('Cześć!')).toBeInTheDocument(); + expect(posts.some((p) => p.url.includes('/gyms/g1/contact/messages'))).toBe(true); + }); + + it('brak dostępu (403 z API) → komunikat błędu, brak composera', async () => { + stubContactFetch({ role: 'member', status: 403 }); + renderPage(); + expect(await screen.findByText(/Tylko członkowie mogą pisać/)).toBeInTheDocument(); + expect(screen.queryByRole('textbox', { name: 'Treść wiadomości' })).not.toBeInTheDocument(); + }); +}); + +describe('Kontakt z właścicielami — skrzynka właściciela', () => { + const THREAD_ROW = { + id: 'c1', + gymId: 'g1', + gymName: 'Gym A', + userId: ME.id, + counterpartName: 'Jan Członek', + lastMessageBody: 'Witamy w siłowni!', + lastMessageAt: '2026-10-20T12:00:00.000Z', + unreadCount: 1, + }; + + it('lista wątków: rozmówca + ostatnia wiadomość + badge nieprzeczytanych', async () => { + stubContactFetch({ role: 'owner', threads: [THREAD_ROW] }); + renderPage(); + expect(await screen.findByText('Jan Członek')).toBeInTheDocument(); + expect(screen.getByText('Witamy w siłowni!')).toBeInTheDocument(); + expect(screen.getByText('1')).toBeInTheDocument(); + }); + + it('wybranie wątku (?) → strumień + odpowiedź POST /gym-contact/conversations/:id/messages', async () => { + const posts = stubContactFetch({ role: 'owner', threads: [THREAD_ROW] }); + const user = userEvent.setup(); + renderPage(); + await user.click(await screen.findByRole('button', { name: /Jan Członek/ })); + + expect(await screen.findByRole('textbox', { name: 'Treść wiadomości' })).toBeInTheDocument(); + await user.type(screen.getByRole('textbox', { name: 'Treść wiadomości' }), 'Codziennie 6–22'); + await waitFor(() => + user.click(screen.getByRole('button', { name: /Wyślij/ })), + ); + expect(await screen.findByText('Codziennie 6–22')).toBeInTheDocument(); + expect(posts.some((p) => p.url.includes('/gym-contact/conversations/c1/messages'))).toBe(true); + }); +}); diff --git a/app/test/gym-detail.test.tsx b/app/test/gym-detail.test.tsx index 163430c..2b1eb49 100644 --- a/app/test/gym-detail.test.tsx +++ b/app/test/gym-detail.test.tsx @@ -66,8 +66,10 @@ function jsonResponse(status: number, body: unknown) { }); } -/** Wspólny mock: detal siłowni, ogłoszenia, mapa ciepła, bytność, wnioski/zaproszenia. */ -function stubGymFetch(options: { gym?: Gym; roles?: string[]; announcements?: GymAnnouncement[] } = {}) { +/** Wspólny mock: detal siłowni, ogłoszenia, mapa ciepła, bytność, wnioski/zaproszenia, statystyki. */ +function stubGymFetch( + options: { gym?: Gym; roles?: string[]; announcements?: GymAnnouncement[]; myVote?: 'UP' | 'DOWN' | null } = {}, +) { const gym = options.gym ?? GYM_REAL; const roles = options.roles ?? ['OWNER']; const announcements = options.announcements ?? [ANNOUNCEMENT]; @@ -87,12 +89,23 @@ function stubGymFetch(options: { gym?: Gym; roles?: string[]; announcements?: Gy }, ], }); + if (url.includes('/stats/overview')) + return jsonResponse(200, { + gym: { id: gym.id, name: gym.name, kind: gym.kind, capacity: gym.capacity }, + presence: { visits: 4, visitsPerDay: 0.1, avgStayMinutes: 90, peak: 2, live: 1, heatmap: [] }, + members: { total: 12, byRole: { OWNER: 1, TRAINER: 1, MEMBER: 10 }, newInRange: 3 }, + activity: { sessionsStarted: 6, sessionsCompleted: 5, sessionsAbandoned: 1, uniqueExercisers: 4 }, + }); if (url.includes('/me/presence')) return jsonResponse(200, { presence: null }); if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] }); if (url.includes('/gyms/claims')) return jsonResponse(200, { claims: [] }); if (url.includes('/gyms/invitations')) return jsonResponse(200, { invitations: [] }); if (url.includes('/gyms/g1')) - return jsonResponse(200, { gym: { ...gym, photos: PHOTOS }, roles, isAdmin: false }); + return jsonResponse(200, { + gym: { ...gym, photos: PHOTOS, myVote: options.myVote ?? null }, + roles, + isAdmin: false, + }); throw new Error(`Unexpected fetch: ${url}`); }); vi.stubGlobal('fetch', fetchMock); @@ -134,7 +147,7 @@ afterEach(() => { }); describe('app GymDetail — kafelki i menu „Zarządzaj”', () => { - it('REAL: trzy kafelki sekcji i jedna grupa menu z akcjami', async () => { + it('REAL owner: cztery kafelki sekcji i jedna grupa menu z akcjami', async () => { stubGymFetch(); renderGym(); expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); @@ -151,12 +164,20 @@ describe('app GymDetail — kafelki i menu „Zarządzaj”', () => { 'href', '/gyms/g1/announcements', ); + // 4. kafelek Statystyki (tylko owner + REAL) → podstrona + expect(screen.getByRole('link', { name: /Statystyki/ })).toHaveAttribute( + 'href', + '/gyms/g1/stats', + ); const config = useTopbarStore.getState().config; expect(config?.groups?.map((g) => g.id)).toEqual(['manage']); + // na lg+ grupa zwinięta do jednej kontrolki (opcja collapsed) + expect(config?.groups?.[0]?.collapsed).toBe(true); expect(config?.groups?.[0]?.actions?.map((a) => a.label)).toEqual([ 'Informacje', 'Galeria', + 'Statystyki', 'Kod QR', 'Urządzenia', 'Ogłoszenia', @@ -164,6 +185,20 @@ describe('app GymDetail — kafelki i menu „Zarządzaj”', () => { ]); }); + it('REAL member (nie-owner): brak kafelka Statystyki i grupy Zarządzaj, jest kontakt z właścicielami', async () => { + stubGymFetch({ roles: ['MEMBER'] }); + renderGym(); + expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); + + expect(screen.queryByRole('link', { name: /Statystyki/ })).not.toBeInTheDocument(); + const config = useTopbarStore.getState().config; + expect(config?.groups ?? []).toHaveLength(0); + expect(config?.actions?.map((a) => a.label)).toContain('Napisz do właścicieli'); + expect(config?.actions?.find((a) => a.label === 'Napisz do właścicieli')?.to).toBe( + '/gyms/g1/contact', + ); + }); + it('VIRTUAL: brak kafelka galerii i brak akcji QR/Galeria w menu', async () => { stubGymFetch({ gym: GYM_VIRTUAL }); renderGym(); @@ -181,6 +216,49 @@ describe('app GymDetail — kafelki i menu „Zarządzaj”', () => { 'Usuń siłownię', ]); }); + + it('publiczna VIRTUAL nie-członek: akcja Dołącz + grupa Ocena z głosami', async () => { + stubGymFetch({ gym: GYM_VIRTUAL, roles: [] }); + renderGym(); + expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); + + const config = useTopbarStore.getState().config; + expect(config?.actions?.map((a) => a.label)).toEqual(['Dołącz']); + // grupa Ocena (2 akcje togglowe, nie collapsed); brak oddanego głosu → bez kropki + expect(config?.groups?.map((g) => g.id)).toEqual(['rating']); + expect(config?.groups?.[0]?.collapsed).toBeUndefined(); + expect(config?.groups?.[0]?.active).toBe(false); + expect(config?.groups?.[0]?.actions?.map((a) => a.label)).toEqual([ + 'Polecam', + 'Nie polecam', + ]); + }); + + it('publiczna VIRTUAL z oddanym głosem: kropka aktywności + zablokowana kontrolka', async () => { + stubGymFetch({ gym: GYM_VIRTUAL, roles: [], myVote: 'UP' }); + renderGym(); + expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); + + const config = useTopbarStore.getState().config; + const rating = config?.groups?.find((g) => g.id === 'rating'); + expect(rating?.active).toBe(true); + expect(rating?.actions?.find((a) => a.label === 'Polecam')?.disabled).toBe(true); + expect(rating?.actions?.find((a) => a.label === 'Nie polecam')?.disabled).toBe(false); + }); + + it('prywatna VIRTUAL owner: brak karty Zaproszeń w treści, akcja w grupie Zarządzaj', async () => { + stubGymFetch({ gym: { ...GYM_VIRTUAL, isPrivate: true } }); + renderGym(); + expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); + + // karta przeniesiona do modala — w treści nie ma już sekcji zaproszeń + expect(screen.queryByText(/Prywatna siłownia jest ukryta/)).not.toBeInTheDocument(); + + const config = useTopbarStore.getState().config; + const labels = config?.groups?.[0]?.actions?.map((a) => a.label) ?? []; + expect(labels).toContain('Zaproszenia'); + expect(labels).not.toContain('Zaproś usera'); + }); }); describe('app podstrony sekcji siłowni', () => { diff --git a/app/test/gym-stats.test.tsx b/app/test/gym-stats.test.tsx new file mode 100644 index 0000000..4f50bcd --- /dev/null +++ b/app/test/gym-stats.test.tsx @@ -0,0 +1,142 @@ +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import GymStatsPage from '../src/pages/gyms/GymStatsPage'; +import { setAccessToken } from '../src/api/client'; +import { Topbar } from '../src/topbar'; +import type { Gym } from '../src/api/types'; + +const GYM: Gym = { + id: 'g1', + name: 'Gym A', + location: null, + availability: null, + capacity: 10, + kind: 'REAL', + isPrivate: false, + equipment: [], + coverPhoto: null, +}; + +function statsBody(overrides: { presence?: Record } = {}) { + return { + gym: { id: 'g1', name: 'Gym A', kind: 'REAL', capacity: 10 }, + presence: { + visits: 42, + visitsPerDay: 1.4, + avgStayMinutes: 75, + peak: 5, + live: 2, + heatmap: [{ day: 0, hour: 18, count: 3 }], + ...overrides.presence, + }, + members: { total: 12, byRole: { OWNER: 1, TRAINER: 2, MEMBER: 9 }, newInRange: 4 }, + activity: { sessionsStarted: 20, sessionsCompleted: 17, sessionsAbandoned: 3, uniqueExercisers: 6 }, + }; +} + +/** Mock; zwraca listę URL-i wywołań stats/overview (do sprawdzenia filtra okresu). */ +function stubStatsFetch(body = statsBody()) { + const statsUrls: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes('/stats/overview')) { + statsUrls.push(url); + return jsonResponse(200, body); + } + if (url.includes('/gyms/g1')) + return jsonResponse(200, { gym: { ...GYM, photos: [] }, roles: ['OWNER'], isAdmin: false }); + throw new Error(`Unexpected fetch: ${url}`); + }), + ); + return statsUrls; +} + +function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function renderPage() { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + + + } /> + + + , + ); +} + +beforeEach(() => { + setAccessToken('tok'); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Statystyki właściciela — podstrona', () => { + it('KPI z mocka: wizyty, członkowie, aktywność', async () => { + stubStatsFetch(); + renderPage(); + expect(await screen.findByText('Wizyty')).toBeInTheDocument(); + + const kpi = (label: string) => { + const el = screen.getByText(label); + const card = el.closest('[data-slot="card"]'); + if (!card) throw new Error(`Brak karty KPI: ${label}`); + return within(card as HTMLElement); + }; + expect(kpi('Wizyty').getByText('42')).toBeInTheDocument(); + expect(kpi('Wizyty / dzień').getByText('1.4')).toBeInTheDocument(); + expect(kpi('Śr. pobyt').getByText('75 min')).toBeInTheDocument(); + expect(kpi('Szczyt').getByText('5')).toBeInTheDocument(); + expect(kpi('Teraz').getByText('2')).toBeInTheDocument(); + expect(kpi('Członkowie').getByText('12')).toBeInTheDocument(); + expect(kpi('Nowi w okresie').getByText('4')).toBeInTheDocument(); + expect(kpi('Sesje ukończone').getByText('17')).toBeInTheDocument(); + expect(kpi('Sesje porzucone').getByText('3')).toBeInTheDocument(); + expect(kpi('Ćwiczący').getByText('6')).toBeInTheDocument(); + }); + + it('heatmapa dzień×godzina: kaflu z liczbą w tytule', async () => { + stubStatsFetch(); + renderPage(); + expect(await screen.findByText('Bytność (dzień × godzina)')).toBeInTheDocument(); + expect(screen.getByTitle('Poniedziałek, 18:00 — 3 wizyty')).toBeInTheDocument(); + expect(screen.getByText('Poniedziałek')).toBeInTheDocument(); + }); + + it('filtr okresu 7 dni przebudowuje zapytanie z nowym from', async () => { + const statsUrls = stubStatsFetch(); + const user = userEvent.setup(); + renderPage(); + expect(await screen.findByText('Wizyty')).toBeInTheDocument(); + expect(statsUrls).toHaveLength(1); + + await user.selectOptions(screen.getByRole('combobox', { name: 'Zakres statystyk' }), '7'); + expect(await screen.findByText('Wizyty')).toBeInTheDocument(); + expect(statsUrls).toHaveLength(2); + expect(statsUrls[0]).not.toEqual(statsUrls[1]); + const from0 = new URL(statsUrls[0]).searchParams.get('from') ?? ''; + const from1 = new URL(statsUrls[1]).searchParams.get('from') ?? ''; + // zawężenie okresu: from przesunięte do przodu (krótsze okno) + expect(from1 > from0).toBe(true); + }); + + it('brak danych presence → pusty stan heatmapy', async () => { + stubStatsFetch(statsBody({ presence: { heatmap: [] } })); + renderPage(); + expect(await screen.findByText('Brak wizyt w tym okresie.')).toBeInTheDocument(); + }); +});
{t('contact.emptyThread')}
{t('stats.heatmapEmpty')}