App: kontakt z wlascicielami sirowni (podstrona /gyms/:id/contact + sekcja w komunikatorze + badge) i statystyki wlasciciela REAL (kafelek + podstrona /gyms/:id/stats); karty VIRTUAL czysto nawigacyjne, akcje dolacz/ocena/zarzadzaj przeniesione do menu detalu (grupa Zarzadzaj zwinieta na lg+)
This commit is contained in:
@@ -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() {
|
||||
<Route path="/gyms/:id/gallery" element={<GymGalleryPage />} />
|
||||
<Route path="/gyms/:id/equipment" element={<GymEquipmentPage />} />
|
||||
<Route path="/gyms/:id/announcements" element={<GymAnnouncementsPage />} />
|
||||
<Route path="/gyms/:id/contact" element={<GymContactPage />} />
|
||||
<Route path="/gyms/:id/stats" element={<GymStatsPage />} />
|
||||
<Route
|
||||
path="/trainees"
|
||||
element={
|
||||
|
||||
@@ -35,8 +35,13 @@ import type {
|
||||
CircumferenceSeries,
|
||||
Invitation,
|
||||
GymClaim,
|
||||
GymContactMessage,
|
||||
GymContactThread,
|
||||
GymContactThreadListItem,
|
||||
GymContactView,
|
||||
GymInvitation,
|
||||
GymKind,
|
||||
GymStatsOverview,
|
||||
VirtualGym,
|
||||
Trainee,
|
||||
TraineeDetail,
|
||||
@@ -159,6 +164,80 @@ export function useGymEquipmentUsage(gymId: string | undefined, rangeDays: numbe
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- kontakt członek ↔ właściciele siłowni ----------
|
||||
/** Widok kontaktu per siłownia: member → własny wątek; owner/admin → lista wątków gyma. */
|
||||
export function useGymContactView(gymId: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['gym-contact', 'view', gymId],
|
||||
queryFn: () => api<GymContactView>(`/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<GymContactThread>(`/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<GymStatsOverview>(
|
||||
`/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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<SentInvitationsList gymId={gym.id} />
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* 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<GymInvitation | null>(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 (
|
||||
<div className="mt-4 border-t border-line pt-4">
|
||||
<div className="mb-1.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
|
||||
{t('invite.sentTitle')}
|
||||
</div>
|
||||
<div className="divide-y divide-line">
|
||||
{sent.map((inv) => {
|
||||
const invName =
|
||||
[inv.user?.firstName, inv.user?.lastName].filter(Boolean).join(' ') ||
|
||||
inv.user?.email ||
|
||||
'—';
|
||||
return (
|
||||
<ListRow
|
||||
key={inv.id}
|
||||
title={
|
||||
<span className="flex items-center gap-2.5">
|
||||
<Avatar name={invName} size={28} />
|
||||
{invName}
|
||||
</span>
|
||||
}
|
||||
actions={
|
||||
<Button variant="ghost" size="sm" type="button" onClick={() => setToWithdraw(inv)}>
|
||||
{t('invites.withdraw')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<ConfirmDialog
|
||||
open={toWithdraw != null}
|
||||
onClose={() => setToWithdraw(null)}
|
||||
onConfirm={() => void withdraw()}
|
||||
title={t('invites.withdraw')}
|
||||
description={t('invites.confirmWithdraw', { name })}
|
||||
confirmLabel={t('invites.withdraw')}
|
||||
danger
|
||||
busy={busy}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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.",
|
||||
|
||||
358
app/src/pages/gyms/GymContactPage.tsx
Normal file
358
app/src/pages/gyms/GymContactPage.tsx
Normal file
@@ -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 (
|
||||
<div className={`flex ${mine ? 'justify-end' : 'justify-start'} gap-2`}>
|
||||
{!mine && <Avatar name={message.senderName} size={28} className="mt-1 shrink-0" />}
|
||||
<div
|
||||
className={`group relative max-w-[85%] rounded-2xl px-3 py-2 ${
|
||||
mine ? 'border border-accent/30 bg-accent/15' : 'border border-line bg-input'
|
||||
}`}
|
||||
>
|
||||
{!mine && (
|
||||
<div className="mb-0.5 text-[0.72rem] font-bold text-accent-text">
|
||||
{message.senderName}
|
||||
</div>
|
||||
)}
|
||||
<div className="whitespace-pre-wrap break-words text-[0.95rem]">{message.body}</div>
|
||||
<div className="mt-1 flex items-center justify-end gap-2 text-[0.75rem] text-dim">
|
||||
{mine && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('contact.deleteAria')}
|
||||
onClick={() => onDelete(message.id)}
|
||||
className="cursor-pointer rounded-md p-0.5 text-dim/70 transition-colors hover:text-danger"
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
className="h-3.5 w-3.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
<span className="tabular-nums">{fmtDateTime(message.createdAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* 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 (
|
||||
<Card className="shrink-0">
|
||||
<Textarea
|
||||
rows={2}
|
||||
maxLength={MAX_BODY}
|
||||
placeholder={t('contact.composerPlaceholder')}
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
aria-label={t('contact.composerAria')}
|
||||
/>
|
||||
<div className="mt-2 flex items-center justify-between gap-2">
|
||||
<span className="text-[0.72rem] tabular-nums text-dim">
|
||||
{t('contact.counter', { n: body.length, max: MAX_BODY })}
|
||||
</span>
|
||||
<Button size="sm" onClick={send} disabled={busy || !body.trim()}>
|
||||
<Send className="h-4 w-4" />
|
||||
{busy ? t('contact.sending') : t('contact.send')}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<HTMLDivElement>(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<string | null>(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 (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-9 w-56" />
|
||||
<Skeleton className="h-64" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<BackButton to={`/gyms/${id}`} className="mb-4" />
|
||||
<ErrorText>
|
||||
{t('common:errorPrefix')}
|
||||
{(error as Error).message}
|
||||
</ErrorText>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* Widok właściciela/admina bez wybranego wątku: lista rozmów tego gyma. */
|
||||
if (managerView && !selectedId) {
|
||||
const threads = managerView.threads;
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t('contact.threadsTitle', { name: gymData?.gym.name ?? '' })}
|
||||
actions={<BackButton to={`/gyms/${id}`} />}
|
||||
/>
|
||||
<Card>
|
||||
{threads.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={MessageSquare}
|
||||
title={t('contact.emptyThreadsTitle')}
|
||||
description={t('contact.emptyThreadsDesc')}
|
||||
/>
|
||||
) : (
|
||||
<div className="divide-y divide-line">
|
||||
{threads.map((thr) => {
|
||||
const unread = thr.unreadCount > 0;
|
||||
return (
|
||||
<button
|
||||
key={thr.id}
|
||||
type="button"
|
||||
onClick={() => 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"
|
||||
>
|
||||
<div className="relative shrink-0">
|
||||
<Avatar name={thr.counterpartName} size={44} />
|
||||
{unread && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -right-0.5 -top-0.5 h-3 w-3 rounded-full border-2 border-card bg-accent"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span
|
||||
className={`min-w-0 truncate text-[0.95rem] ${unread ? 'font-bold text-ink' : 'font-semibold'}`}
|
||||
>
|
||||
{thr.counterpartName}
|
||||
</span>
|
||||
{thr.lastMessageAt && (
|
||||
<span
|
||||
className={`shrink-0 text-[0.7rem] tabular-nums ${unread ? 'font-bold text-accent-text' : 'text-dim'}`}
|
||||
>
|
||||
{timeAgo(thr.lastMessageAt)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 flex items-center justify-between gap-2">
|
||||
<span
|
||||
className={`min-w-0 truncate text-[0.8125rem] ${unread ? 'font-semibold text-ink' : 'text-dim'}`}
|
||||
>
|
||||
{thr.lastMessageBody ?? '—'}
|
||||
</span>
|
||||
{unread && (
|
||||
<span className="grid h-[18px] min-w-[18px] shrink-0 place-items-center rounded-full bg-accent px-1 text-[0.65rem] font-extrabold text-accent-ink">
|
||||
{thr.unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* 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 (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-9 w-56" />
|
||||
<Skeleton className="h-64" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100dvh-175px)] min-h-[320px] flex-col md:h-[calc(100dvh-131px)]">
|
||||
<PageHeader
|
||||
title={isManager ? memberName : t('contact.ownersTitle', { name: gymName })}
|
||||
leading={<Avatar name={isManager ? memberName : t('contact.ownersAvatar')} size={28} />}
|
||||
actions={
|
||||
isManager ? (
|
||||
<BackButton onClick={() => setSearchParams({})} />
|
||||
) : (
|
||||
<BackButton to={`/gyms/${id}`} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<Card ref={listRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
|
||||
{messages.length === 0 ? (
|
||||
<p className="text-dim">{t('contact.emptyThread')}</p>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{messages.map((m, i, arr) => {
|
||||
const prev = i > 0 ? arr[i - 1] : null;
|
||||
const newDay = !prev || fmtDate(prev.createdAt) !== fmtDate(m.createdAt);
|
||||
return (
|
||||
<Fragment key={m.id}>
|
||||
{newDay && (
|
||||
<div className="flex justify-center py-1">
|
||||
<span className="rounded-full bg-dim/13 px-3 py-0.5 text-[0.7rem] font-bold text-dim">
|
||||
{fmtDate(m.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Bubble
|
||||
message={m}
|
||||
mine={m.senderId === myId}
|
||||
onDelete={(mid) => setPendingDelete(mid)}
|
||||
/>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Composer onSend={(text) => void doSend(text)} busy={busy} />
|
||||
|
||||
<ConfirmDialog
|
||||
open={pendingDelete != null}
|
||||
onClose={() => setPendingDelete(null)}
|
||||
onConfirm={() => void doDelete()}
|
||||
title={t('contact.deleteTitle')}
|
||||
description={t('contact.deleteDesc')}
|
||||
confirmLabel={t('common:remove')}
|
||||
danger
|
||||
busy={deleteBusy}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<Link
|
||||
to={`/gyms/${gym.id}/stats`}
|
||||
className="flex flex-col rounded-2xl border border-line bg-card p-3 transition-colors hover:border-accent/55"
|
||||
>
|
||||
<div className="grid h-20 place-items-center rounded-[10px] border border-line bg-input/40 text-dim">
|
||||
<BarChart3 className="h-5 w-5" aria-hidden="true" />
|
||||
</div>
|
||||
<div className="mt-2.5 flex items-center justify-between gap-2">
|
||||
<span className="min-w-0 truncate font-display text-[0.9rem] font-bold">
|
||||
{t('detail.groupStats')}
|
||||
</span>
|
||||
<span className="shrink-0 text-[0.72rem] font-semibold tabular-nums text-dim">
|
||||
{data ? t('common:counters.members', { count: data.members.total }) : '—'}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/* 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' && <GalleryTile gym={gym} />}
|
||||
<EquipmentTile gym={gym} />
|
||||
<AnnouncementsTile gymId={gym.id} />
|
||||
{gym.kind === 'REAL' && isOwner && <StatsTile gym={gym} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -784,9 +898,6 @@ export default function GymDetail() {
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
{isOwner && gym.kind === 'VIRTUAL' && gym.isPrivate && (
|
||||
<GymInvitationsSection gym={gym} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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 (
|
||||
<Card>
|
||||
<SectionHeader title={t('detail.groupInvites')} description={t('invites.desc')} />
|
||||
<div className="divide-y divide-line">
|
||||
{sent.length === 0 && (
|
||||
<span className="py-3 text-[0.875rem] text-dim">{t('invites.empty')}</span>
|
||||
)}
|
||||
{sent.map((inv) => {
|
||||
const name =
|
||||
[inv.user?.firstName, inv.user?.lastName].filter(Boolean).join(' ') ||
|
||||
inv.user?.email ||
|
||||
'—';
|
||||
return (
|
||||
<ListRow
|
||||
key={inv.id}
|
||||
title={
|
||||
<span className="flex items-center gap-2.5">
|
||||
<Avatar name={name} size={28} />
|
||||
{name}
|
||||
</span>
|
||||
}
|
||||
actions={
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={() => void withdraw(inv.id)}
|
||||
>
|
||||
{t('invites.withdraw')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
178
app/src/pages/gyms/GymStatsPage.tsx
Normal file
178
app/src/pages/gyms/GymStatsPage.tsx
Normal file
@@ -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 (
|
||||
<Card className="p-3.5">
|
||||
<div className="text-[0.72rem] font-bold uppercase tracking-[0.08em] text-dim">{label}</div>
|
||||
<div className="mt-1 font-display text-[1.35rem] font-bold tabular-nums">{value}</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/* 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 (
|
||||
<Card>
|
||||
<SectionHeader title={t('stats.heatmapTitle')} />
|
||||
{cells.length === 0 ? (
|
||||
<p className="text-[0.875rem] text-dim">{t('stats.heatmapEmpty')}</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<div
|
||||
className="grid min-w-[34rem] gap-[3px]"
|
||||
style={{ gridTemplateColumns: 'minmax(5rem, 7rem) repeat(24, minmax(0, 1fr))' }}
|
||||
>
|
||||
<span />
|
||||
{Array.from({ length: 24 }, (_, hour) => (
|
||||
<span
|
||||
key={hour}
|
||||
className="text-center text-[0.6rem] font-bold tabular-nums text-dim"
|
||||
>
|
||||
{hour % 3 === 0 ? String(hour).padStart(2, '0') : ''}
|
||||
</span>
|
||||
))}
|
||||
{Array.from({ length: 7 }, (_, day) => (
|
||||
<HeatmapRow key={day} day={day} cells={cells} max={max} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function HeatmapRow({
|
||||
day,
|
||||
cells,
|
||||
max,
|
||||
}: {
|
||||
day: number;
|
||||
cells: GymStatsOverview['presence']['heatmap'];
|
||||
max: number;
|
||||
}) {
|
||||
const { t } = useTranslation('gyms');
|
||||
return (
|
||||
<>
|
||||
<span className="flex min-w-0 items-center pr-1 text-[0.68rem] font-semibold text-dim">
|
||||
<span className="truncate">{dayName(day + 1)}</span>
|
||||
</span>
|
||||
{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 (
|
||||
<span
|
||||
key={hour}
|
||||
title={t('stats.cellTitle', {
|
||||
day: dayName(day + 1),
|
||||
hour: String(hour).padStart(2, '0'),
|
||||
count,
|
||||
})}
|
||||
className="aspect-square rounded-[2px] border border-line/40"
|
||||
style={{
|
||||
background:
|
||||
intensity > 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 = (
|
||||
<Select
|
||||
size="sm"
|
||||
value={rangeDays}
|
||||
onChange={(e) => setRangeDays(Number(e.target.value))}
|
||||
aria-label={t('stats.rangeAria')}
|
||||
>
|
||||
{RANGE_OPTIONS.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{t('stats.rangeDays', { count: d })}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
);
|
||||
useTopbar({
|
||||
title: t('stats.title'),
|
||||
back: `/gyms/${id}`,
|
||||
filters: [rangeFilter],
|
||||
filterActive: rangeDays !== 30,
|
||||
});
|
||||
|
||||
if (isLoading) return <Loading />;
|
||||
if (error || !data) {
|
||||
return (
|
||||
<>
|
||||
<BackButton to={`/gyms/${id}`} className="mb-4" />
|
||||
<ErrorText>
|
||||
{t('common:errorPrefix')}
|
||||
{(error as Error).message}
|
||||
</ErrorText>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const { presence, members, activity } = data;
|
||||
return (
|
||||
<>
|
||||
{/* HERO-LITE: nazwa siłowni (tytuł h1 należy do topbaru) */}
|
||||
<div className="mb-5 flex flex-wrap items-end justify-between gap-3">
|
||||
<span className="font-display text-[1.35rem] font-bold tracking-[-0.02em]">
|
||||
{gymData?.gym.name ?? ''}
|
||||
</span>
|
||||
<BackButton to={`/gyms/${id}`} />
|
||||
</div>
|
||||
|
||||
<div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
|
||||
<Kpi label={t('stats.visits')} value={presence.visits} />
|
||||
<Kpi label={t('stats.visitsPerDay')} value={presence.visitsPerDay} />
|
||||
<Kpi
|
||||
label={t('stats.avgStay')}
|
||||
value={
|
||||
presence.avgStayMinutes != null
|
||||
? t('stats.minutes', { n: presence.avgStayMinutes })
|
||||
: '—'
|
||||
}
|
||||
/>
|
||||
<Kpi label={t('stats.peak')} value={presence.peak} />
|
||||
<Kpi label={t('stats.live')} value={presence.live} />
|
||||
<Kpi label={t('stats.members')} value={members.total} />
|
||||
<Kpi label={t('stats.newInRange')} value={members.newInRange} />
|
||||
<Kpi label={t('stats.sessionsCompleted')} value={activity.sessionsCompleted} />
|
||||
<Kpi label={t('stats.sessionsAbandoned')} value={activity.sessionsAbandoned} />
|
||||
<Kpi label={t('stats.uniqueExercisers')} value={activity.uniqueExercisers} />
|
||||
</div>
|
||||
|
||||
<PresenceHeatmap stats={data} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex items-center gap-2" title={t('page.voteTitle')}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('page.voteUpAria', { name: gym.name })}
|
||||
aria-pressed={gym.myVote === 'UP'}
|
||||
onClick={() => 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'
|
||||
}`}
|
||||
>
|
||||
<ThumbsUp className="h-4 w-4" />
|
||||
{gym.up}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('page.voteDownAria', { name: gym.name })}
|
||||
aria-pressed={gym.myVote === 'DOWN'}
|
||||
onClick={() => 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'
|
||||
}`}
|
||||
>
|
||||
<ThumbsDown className="h-4 w-4" />
|
||||
{gym.down}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* 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 (
|
||||
<GymCard
|
||||
gym={gym}
|
||||
onClick={onClick}
|
||||
memberCount={gym.memberCount}
|
||||
rating={gym.up + gym.down > 0 ? Math.round((gym.up / (gym.up + gym.down)) * 100) : null}
|
||||
extraBadges={
|
||||
isMember ? <Badge color="green">{t('common:statuses.gymRole.MEMBER')}</Badge> : null
|
||||
}
|
||||
>
|
||||
{!gym.isPrivate && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<VoteButtons gym={gym} onRate={(v) => void rate(v)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{!isMember && !gym.isPrivate && (
|
||||
<Button size="sm" onClick={() => void join()} disabled={busy}>
|
||||
{t('join.submit')}
|
||||
</Button>
|
||||
)}
|
||||
{gym.isPrivate && isOwner && (
|
||||
<Button size="sm" variant="secondary" onClick={onInvite}>
|
||||
{t('detail.actionInvite')}
|
||||
</Button>
|
||||
)}
|
||||
{isOwner && !gym.isPrivate && gym.claimStatus === 'PENDING' && (
|
||||
<>
|
||||
<span className="text-[0.875rem] text-dim">{t('page.claimPending')}</span>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => void withdrawClaim()}
|
||||
disabled={busy}
|
||||
>
|
||||
{t('invites.withdraw')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{isOwner && !gym.isPrivate && gym.claimStatus === 'REJECTED' && (
|
||||
<>
|
||||
<span className="text-[0.875rem] text-danger">
|
||||
{t('page.rejected')}
|
||||
{gym.rejectReason ? `: ${gym.rejectReason}` : ''}
|
||||
</span>
|
||||
<Button size="sm" variant="secondary" onClick={() => setClaimOpen(true)}>
|
||||
{t('page.resubmit')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{isOwner && !gym.isPrivate && !gym.claimStatus && (
|
||||
<Button size="sm" variant="secondary" onClick={() => setClaimOpen(true)}>
|
||||
{t('detail.actionClaimVerify')}
|
||||
</Button>
|
||||
)}
|
||||
{gym.isPrivate && isOwner && (
|
||||
<ClaimStatusInline
|
||||
gym={gym}
|
||||
onResubmit={() => setClaimOpen(true)}
|
||||
onWithdraw={() => void withdrawClaim()}
|
||||
busy={busy}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gym.isPrivate && isOwner && sentInvitations.length > 0 && (
|
||||
<div className="mt-3 border-t border-line pt-3">
|
||||
<div className="mb-1.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
|
||||
{t('page.sentInvites')}
|
||||
</div>
|
||||
<div className="divide-y divide-line">
|
||||
{sentInvitations.map((inv) => {
|
||||
const name =
|
||||
[inv.user?.firstName, inv.user?.lastName].filter(Boolean).join(' ') ||
|
||||
inv.user?.email ||
|
||||
'—';
|
||||
return (
|
||||
<ListRow
|
||||
key={inv.id}
|
||||
title={name}
|
||||
actions={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => void withdrawInvitation(inv.id)}
|
||||
>
|
||||
{t('invites.withdraw')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ClaimModal
|
||||
open={claimOpen}
|
||||
onClose={() => setClaimOpen(false)}
|
||||
gym={{ id: gym.id, name: gym.name }}
|
||||
initial={claim ?? null}
|
||||
/>
|
||||
</GymCard>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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' && (
|
||||
<span className="text-[0.875rem] text-dim">{t('page.claimPending')}</span>
|
||||
<Button size="sm" variant="secondary" onClick={onWithdraw} disabled={busy}>
|
||||
{t('invites.withdraw')}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (gym.claimStatus === 'REJECTED') {
|
||||
return (
|
||||
<>
|
||||
)}
|
||||
{gym.claimStatus === 'REJECTED' && (
|
||||
<span className="text-[0.875rem] text-danger">
|
||||
{t('page.rejected')}
|
||||
{gym.rejectReason ? `: ${gym.rejectReason}` : ''}
|
||||
</span>
|
||||
<Button size="sm" variant="secondary" onClick={onResubmit}>
|
||||
{t('page.resubmit')}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Button size="sm" variant="secondary" onClick={onResubmit}>
|
||||
{t('detail.actionClaimVerify')}
|
||||
</Button>
|
||||
)}
|
||||
</GymCard>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<Tab | null>(null);
|
||||
useEffect(() => {
|
||||
@@ -605,11 +352,8 @@ export default function Gyms() {
|
||||
<VirtualGymCard
|
||||
key={g.id}
|
||||
gym={g}
|
||||
isOwner={ownerIds.has(g.id)}
|
||||
isMember={memberIds.has(g.id)}
|
||||
claim={claimsByGym.get(g.id) ?? null}
|
||||
sentInvitations={sentGymInvitations.filter((i) => i.gym.id === g.id)}
|
||||
onInvite={() => setInviteGym({ id: g.id, name: g.name })}
|
||||
onClick={() => navigate(`/gyms/${g.id}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -620,7 +364,6 @@ export default function Gyms() {
|
||||
|
||||
<GymCreateModal open={createOpen} onClose={() => setCreateOpen(false)} />
|
||||
<JoinGymModal open={joinOpen} onClose={() => setJoinOpen(false)} />
|
||||
{inviteGym && <InviteGymModal open onClose={() => setInviteGym(null)} gym={inviteGym} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
) : (
|
||||
<Card>{renderRows(filtered)}</Card>
|
||||
))}
|
||||
|
||||
{/* 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 (
|
||||
<section className="mt-6">
|
||||
<div className="mb-3 flex items-center gap-2.5">
|
||||
<H3 className="mb-0">{t('gymOwnersSection')}</H3>
|
||||
<Badge color="gray">{items.length}</Badge>
|
||||
</div>
|
||||
<Card>
|
||||
<div className="divide-y divide-line">
|
||||
{items.map((c) => {
|
||||
const unread = c.unreadCount > 0;
|
||||
return (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
onClick={() => 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"
|
||||
>
|
||||
<div className="relative shrink-0">
|
||||
<Avatar name={c.counterpartName} size={44} />
|
||||
{unread && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -right-0.5 -top-0.5 h-3 w-3 rounded-full border-2 border-card bg-accent"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span className="min-w-0 truncate text-[0.95rem] font-semibold">
|
||||
{c.counterpartName}
|
||||
<span className="ml-1.5 text-[0.8rem] font-normal text-dim">
|
||||
{c.gymName}
|
||||
</span>
|
||||
</span>
|
||||
{c.lastMessageAt && (
|
||||
<span
|
||||
className={`shrink-0 text-[0.7rem] tabular-nums ${unread ? 'font-bold text-accent-text' : 'text-dim'}`}
|
||||
>
|
||||
{timeAgo(c.lastMessageAt)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-0.5 flex items-center justify-between gap-2">
|
||||
<span
|
||||
className={`min-w-0 truncate text-[0.8125rem] ${unread ? 'font-semibold text-ink' : 'text-dim'}`}
|
||||
>
|
||||
{c.lastMessageBody ?? '—'}
|
||||
</span>
|
||||
{unread && (
|
||||
<span className="grid h-[18px] min-w-[18px] shrink-0 place-items-center rounded-full bg-accent px-1 text-[0.65rem] font-extrabold text-accent-ink">
|
||||
{c.unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Card>
|
||||
</section>
|
||||
);
|
||||
})()}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 (<md): panel grupy renderowany płasko w dolnym pasku zamiast akordeonu. */
|
||||
@@ -40,6 +40,12 @@ interface GroupButtonProps {
|
||||
* gdzie akcje to główna nawigacja (np. wizard). Telefon bez zmian.
|
||||
*/
|
||||
alwaysInlineFromMd?: boolean;
|
||||
/**
|
||||
* lg+: grupa pozostaje zwinięta do JEDNEJ kontrolki (ikona + etykieta +
|
||||
* strzałka); otwarty panel jako dropdown pod przyciskiem. Poniżej lg
|
||||
* zachowanie bez zmian (akordeon tablet / pigułka telefon).
|
||||
*/
|
||||
collapsed?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
@@ -58,6 +64,7 @@ export function GroupButton({
|
||||
onToggle,
|
||||
flatOnMobile,
|
||||
alwaysInlineFromMd,
|
||||
collapsed,
|
||||
children,
|
||||
}: GroupButtonProps) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
@@ -92,6 +99,7 @@ export function GroupButton({
|
||||
return (
|
||||
<div ref={ref} className="md:relative flex items-center gap-2">
|
||||
{/* 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 <md
|
||||
@@ -118,14 +129,20 @@ export function GroupButton({
|
||||
'relative grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border shadow-card transition-all duration-150',
|
||||
// tryb płaski: ikona niepotrzebna na telefonie (akcje płasko w pasku)
|
||||
// i na lg+ (panel inline); md–lg zostaje akordeon od ikonki;
|
||||
// alwaysInlineFromMd: ikona niepotrzebna od md+ (panel inline)
|
||||
alwaysInlineFromMd
|
||||
// alwaysInlineFromMd: ikona niepotrzebna od md+ (panel inline);
|
||||
// collapsed: kontrolka zostaje widoczna na lg+ (z etykietą + strzałką)
|
||||
collapsed
|
||||
? flatOnMobile
|
||||
? 'hidden'
|
||||
: 'md:hidden'
|
||||
: flatOnMobile
|
||||
? 'max-md:hidden lg:hidden'
|
||||
: 'lg:hidden',
|
||||
? 'max-md:hidden'
|
||||
: undefined
|
||||
: alwaysInlineFromMd
|
||||
? flatOnMobile
|
||||
? 'hidden'
|
||||
: 'md:hidden'
|
||||
: flatOnMobile
|
||||
? 'max-md:hidden lg:hidden'
|
||||
: 'lg:hidden',
|
||||
collapsed && 'lg:w-auto lg:px-3 lg:gap-1.5',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60',
|
||||
open
|
||||
? 'border-accent/55 bg-accent/10 text-accent-text'
|
||||
@@ -133,6 +150,12 @@ export function GroupButton({
|
||||
)}
|
||||
>
|
||||
<Icon className="w-4 h-4" />
|
||||
{collapsed && (
|
||||
<span className="hidden whitespace-nowrap text-[0.8125rem] font-semibold lg:inline">
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
{collapsed && <ChevronDown className="hidden h-3.5 w-3.5 lg:block" aria-hidden="true" />}
|
||||
{active && (
|
||||
<span className="absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full bg-accent" />
|
||||
)}
|
||||
|
||||
@@ -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) => (
|
||||
<ActionButton key={action.label} action={action} onNavigate={navigate} />
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
100
app/test/e2e/gym-contact.spec.ts
Normal file
100
app/test/e2e/gym-contact.spec.ts
Normal file
@@ -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();
|
||||
});
|
||||
53
app/test/e2e/gym-stats.spec.ts
Normal file
53
app/test/e2e/gym-stats.spec.ts
Normal file
@@ -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();
|
||||
});
|
||||
@@ -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');
|
||||
|
||||
@@ -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<string>();
|
||||
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 }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
238
app/test/gym-contact.test.tsx
Normal file
238
app/test/gym-contact.test.tsx
Normal file
@@ -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(
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Routes>
|
||||
<Route path="/gyms/:id/contact" element={<GymContactPage />} />
|
||||
</Routes>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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', () => {
|
||||
|
||||
142
app/test/gym-stats.test.tsx
Normal file
142
app/test/gym-stats.test.tsx
Normal file
@@ -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<string, unknown> } = {}) {
|
||||
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(
|
||||
<MemoryRouter initialEntries={['/gyms/g1/stats']}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Topbar />
|
||||
<Routes>
|
||||
<Route path="/gyms/:id/stats" element={<GymStatsPage />} />
|
||||
</Routes>
|
||||
</QueryClientProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user