Silownie: usuniecie /profile/gyms (dublowalo /gyms i /gyms/:id) - zakladka Moje silownie pokazuje wszystkie czlonkostwa z rolami, wiersz Silownie w profilu prowadzi na /gyms; naprawa przestarzalego testu plans.spec (stopka edytora usunieta w 57eccd4)

This commit is contained in:
tisachi
2026-09-13 18:54:18 +02:00
parent 06966067c1
commit 9bf43ed744
10 changed files with 59 additions and 646 deletions

View File

@@ -15,7 +15,6 @@ import ProfileInfo from './pages/profile/ProfileInfo';
import ProfileBodyParameters from './pages/profile/ProfileBodyParameters';
import ProfileHistory from './pages/profile/ProfileHistory';
import ProfileProgress from './pages/profile/ProfileProgress';
import ProfileGyms from './pages/profile/ProfileGyms';
import ProfileClaims from './pages/profile/ProfileClaims';
import Gyms from './pages/gyms/Gyms';
import GymDetail from './pages/gyms/GymDetail';
@@ -62,7 +61,6 @@ export default function App() {
<Route path="/profile/body-parameters" element={<ProfileBodyParameters />} />
<Route path="/profile/history" element={<ProfileHistory />} />
<Route path="/profile/progress" element={<ProfileProgress />} />
<Route path="/profile/gyms" element={<ProfileGyms />} />
<Route path="/profile/claims" element={<ProfileClaims />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />

View File

@@ -200,13 +200,6 @@ export function removeGymEquipment(gymId: string, equipmentId: string) {
return api(`/gyms/${gymId}/equipment/${encodeURIComponent(equipmentId)}`, { method: 'DELETE' });
}
/** The user's gyms where they hold the OWNER role (for gym management). */
export function useOwnedGyms() {
const { data, ...rest } = useGyms();
const owned = (data?.gyms ?? []).filter((g) => g.roles.includes('OWNER'));
return { ...rest, data: { gyms: owned } };
}
export function updateGym(
gymId: string,
body: {

View File

@@ -1,211 +0,0 @@
import { useQueryClient } from '@tanstack/react-query';
import { Link } from 'react-router-dom';
import { Eye, X } from 'lucide-react';
import {
addGymEquipment,
joinGym,
removeGymEquipment,
updateGymEquipmentQuantity,
useAllGyms,
useEquipment,
useGyms,
type UserGym,
} from '../../api/queries';
import { GYM_ROLE } from '../../lib/labels';
import { Badge, Button, Card, H3, Loading, Select } from '../ui';
import { useToast } from '../toast';
import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment';
import GymCreateModal from './GymCreateModal';
export default function GymsSection({
createOpen,
onCreateOpenChange,
}: {
/** Modal „Stwórz siłownię" — stan trzyma strona (przycisk jest w menu kontekstowym). */
createOpen: boolean;
onCreateOpenChange: (open: boolean) => void;
}) {
const { data, isLoading } = useGyms();
const { data: allData, isLoading: allLoading } = useAllGyms();
const queryClient = useQueryClient();
const { push } = useToast();
const gyms = data?.gyms ?? [];
const allGyms = allData?.gyms ?? [];
const joinedIds = new Set(gyms.map((g) => g.id));
const joinable = allGyms.filter((g) => !joinedIds.has(g.id));
const invalidateGyms = () => {
queryClient.invalidateQueries({ queryKey: ['gyms'] });
queryClient.invalidateQueries({ queryKey: ['me'] });
};
const handleJoin = async (gymId: string, gymName: string) => {
try {
await joinGym(gymId);
invalidateGyms();
push(`Dołączono do siłowni: ${gymName}`, 'success');
} catch (e) {
push((e as Error).message, 'error');
}
};
return (
<Card>
{isLoading && <Loading />}
<H3>Twe siłownie</H3>
{!isLoading && gyms.length === 0 && (
<p className="text-dim">Nie należysz jeszcze do żadnej siłowni.</p>
)}
{gyms.length > 0 && (
<div className="divide-y divide-line">
{gyms.map((g) => (
<GymItem key={g.id} gym={g} onChanged={invalidateGyms} />
))}
</div>
)}
<div className="mt-5">
<H3>Wybierz istniejącą siłownię</H3>
{allLoading && <Loading />}
{!allLoading && joinable.length === 0 && (
<p className="text-dim">Brak innych dostępnych siłowni.</p>
)}
{joinable.length > 0 && (
<div className="divide-y divide-line">
{joinable.map((g) => (
<div
key={g.id}
className="flex items-center justify-between gap-3 px-1 py-3"
>
<div className="min-w-0">
<Link to={`/gyms/${g.id}`} className="text-[0.95rem] font-semibold hover:text-accent-text">
{g.name}
</Link>
{g.location && <span className="text-dim"> — {g.location}</span>}
</div>
<div className="flex shrink-0 items-center gap-2">
<Link
to={`/gyms/${g.id}`}
className="inline-flex cursor-pointer items-center gap-1.5 rounded-full border border-line px-3 py-1.5 text-[0.875rem] font-semibold text-dim hover:border-accent hover:text-accent-text"
>
<Eye className="h-4 w-4" />
Zobacz
</Link>
<Button
variant="secondary"
size="sm"
onClick={() => handleJoin(g.id, g.name)}
>
Dołącz
</Button>
</div>
</div>
))}
</div>
)}
</div>
<GymCreateModal open={createOpen} onClose={() => onCreateOpenChange(false)} />
</Card>
);
}
function GymItem({ gym, onChanged }: { gym: UserGym; onChanged: () => void }) {
const { push } = useToast();
const { data: eqData } = useEquipment();
const isOwner = gym.roles.includes('OWNER');
const catalog = eqData?.equipment ?? [];
const quantities = new Map(gym.equipment.map((e) => [e.equipmentId, e.quantity]));
const handleAddEquipment = async (equipmentId: string) => {
if (!equipmentId) return;
const existing = quantities.get(equipmentId);
try {
if (existing != null) {
await updateGymEquipmentQuantity(gym.id, equipmentId, existing + 1);
push(`Zwiększono ilość (łącznie ${existing + 1})`, 'success');
} else {
await addGymEquipment(gym.id, equipmentId);
push('Sprzęt dodany', 'success');
}
onChanged();
} catch (err) {
push((err as Error).message, 'error');
}
};
const handleRemoveEquipment = async (equipmentId: string, name: string) => {
try {
await removeGymEquipment(gym.id, equipmentId);
onChanged();
push(`Usunięto: ${name}`, 'success');
} catch (err) {
push((err as Error).message, 'error');
}
};
return (
<div className="px-1 py-3">
<div className="flex flex-wrap items-center gap-2">
<Link to={`/gyms/${gym.id}`} className="text-[0.95rem] font-semibold hover:text-accent-text">
{gym.name}
</Link>
{gym.roles.map((r) => (
<Badge key={r} color={GYM_ROLE[r].color}>
{GYM_ROLE[r].label}
</Badge>
))}
{gym.location && <span className="text-[0.875rem] text-dim">— {gym.location}</span>}
</div>
{isOwner && (
<div className="mt-3">
<div className="flex flex-wrap items-center gap-2">
{gym.equipment.length === 0 && (
<span className="text-[0.875rem] text-dim">Brak sprzętu.</span>
)}
{gym.equipment.map((item) => (
<span
key={item.id}
className="inline-flex items-center gap-1 border border-line bg-card rounded-full py-0.5 pl-2.5 pr-1 text-[0.875rem]"
>
{formatGymEquipment(item)}
<button
type="button"
onClick={() => handleRemoveEquipment(item.equipmentId, item.equipment.name)}
aria-label={`Usuń ${item.equipment.name}`}
className="text-dim hover:text-danger cursor-pointer"
>
<X className="w-3.5 h-3.5" />
</button>
</span>
))}
</div>
<div className="mt-2">
<Select
value=""
onChange={(e) => handleAddEquipment(e.target.value)}
className="max-w-[220px]"
aria-label={`Dodaj sprzęt do ${gym.name}`}
>
<option value="">+ dodaj sprzęt…</option>
{catalog.map((e) => {
const qty = quantities.get(e.id);
const spec = formatEquipmentSpec(e.spec);
return (
<option key={e.id} value={e.id}>
{e.name}
{spec ? ` · ${spec}` : ''}
{qty != null ? ` (${qty} szt.)` : ''}
</option>
);
})}
</Select>
</div>
</div>
)}
</div>
);
}

View File

@@ -17,9 +17,7 @@ import {
rateGym,
useGyms,
useGymInvitations,
useMe,
useMyGymClaims,
useOwnedGyms,
useVirtualGyms,
withdrawGymClaim,
withdrawGymInvitation,
@@ -41,6 +39,7 @@ import { useToast } from '../../components/toast';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
import { DAY_NAMES, 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';
@@ -456,17 +455,15 @@ function ClaimStatusInline({
export default function Gyms() {
const navigate = useNavigate();
const { data: ownedData, isLoading: ownedLoading, error: ownedError } = useOwnedGyms();
const { data: gymsData } = useGyms();
// „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 { data: me } = useMe();
const isAdmin = me?.user.isAdmin ?? false;
const ownedGyms = ownedData?.gyms ?? [];
const memberIds = new Set((gymsData?.gyms ?? []).map((g) => g.id));
const ownerIds = new Set(ownedGyms.map((g) => g.id));
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]));
@@ -477,10 +474,10 @@ export default function Gyms() {
const [tab, setTab] = useState<Tab | null>(null);
useEffect(() => {
if (tab === null && !ownedLoading) {
setTab(ownedGyms.length > 0 ? 'mine' : 'virtual');
if (tab === null && !gymsLoading) {
setTab(myGyms.length > 0 ? 'mine' : 'virtual');
}
}, [tab, ownedLoading, ownedGyms.length]);
}, [tab, gymsLoading, myGyms.length]);
useTopbar({
title: 'Siłownie',
@@ -499,7 +496,7 @@ export default function Gyms() {
const matches = (g: { name: string; location: string | null }) =>
!q || [g.name, g.location].filter(Boolean).some((s) => s!.toLowerCase().includes(q));
const filteredMine = ownedGyms.filter(matches);
const filteredMine = myGyms.filter(matches);
const filteredVirtual = virtualGyms.filter(matches);
return (
@@ -517,19 +514,17 @@ export default function Gyms() {
{tab === 'mine' && (
<>
{ownedLoading && <Loading />}
{ownedError && <ErrorText>Błąd: {(ownedError as Error).message}</ErrorText>}
{!ownedLoading && !ownedError && filteredMine.length === 0 && (
{gymsLoading && <Loading />}
{gymsError && <ErrorText>Błąd: {(gymsError as Error).message}</ErrorText>}
{!gymsLoading && !gymsError && filteredMine.length === 0 && (
<Card>
<EmptyState
icon={Building2}
title={q ? 'Brak wyników' : 'Brak własnych siłowni'}
title={q ? 'Brak wyników' : 'Brak siłowni'}
description={
q
? 'Brak wyników dla podanego zapytania.'
: isAdmin
? 'Nie jesteś właścicielem żadnej siłowni. Utwórz pierwszą przyciskiem poniżej.'
: 'Nie jesteś właścicielem żadnej siłowni.'
: 'Nie należysz do żadnej siłowni. Utwórz pierwszą lub dołącz do istniejącej.'
}
action={
!q ? (
@@ -555,6 +550,11 @@ export default function Gyms() {
gym={g}
cover={g.coverPhoto}
onClick={() => navigate(`/gyms/${g.id}`)}
extraBadges={g.roles.map((r) => (
<Badge key={r} color={GYM_ROLE[r].color}>
{GYM_ROLE[r].label}
</Badge>
))}
/>
))}
</div>

View File

@@ -270,7 +270,7 @@ export default function Profile() {
summary={progressSummary}
/>
<SectionLink
to="/profile/gyms"
to="/gyms"
title="Siłownie"
icon={Building2}
summary={gymsSummary}

View File

@@ -1,29 +0,0 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus } from 'lucide-react';
import { useMe } from '../../api/queries';
import GymsSection from '../../components/gyms/GymsSection';
import { BackButton, PageHeader } from '../../components/ui';
import { useTopbar } from '../../topbar';
export default function ProfileGyms() {
const navigate = useNavigate();
const { data: me } = useMe();
const isAdmin = me?.user.isAdmin ?? false;
const [createOpen, setCreateOpen] = useState(false);
useTopbar({
title: 'Profil — siłownie',
back: '/profile',
actions: isAdmin
? [{ label: 'Stwórz siłownię', onClick: () => setCreateOpen(true), icon: Plus }]
: undefined,
});
return (
<>
<PageHeader title="Siłownie" actions={<BackButton onClick={() => navigate('/profile')} />} />
<GymsSection createOpen={createOpen} onCreateOpenChange={setCreateOpen} />
</>
);
}

View File

@@ -1,327 +0,0 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import App from '../src/App';
import { useAuth } from '../src/store/auth';
import { setAccessToken } from '../src/api/client';
import type { User } from '../src/api/types';
const USER: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
age: 30,
heightCm: 180,
phone: null,
isAdmin: false,
availability: null,
priorities: 'chest',
exclusions: 'knee',
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
const TEST_EQUIPMENT = [
{ id: 'eq-1', name: 'sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: null },
{ id: 'eq-2', name: 'hantle', kind: 'DUMBBELL', spec: { minKg: 2.5, maxKg: 25 }, description: null },
{ id: 'eq-3', name: 'Kettlebell', kind: 'KETTLEBELL', spec: { minKg: 4, maxKg: 32 }, description: null },
];
const MY_GYM = {
id: 'gym-1',
name: 'Żelazna Świątynia',
location: 'Warszawa',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 50,
equipment: [
{ id: 'ge-1', gymId: 'gym-1', equipmentId: 'eq-1', quantity: 1, equipment: TEST_EQUIPMENT[0] },
{ id: 'ge-2', gymId: 'gym-1', equipmentId: 'eq-2', quantity: 2, equipment: TEST_EQUIPMENT[1] },
],
roles: ['OWNER', 'TRAINER'],
};
const OTHER_GYM = {
id: 'gym-2',
name: 'Mega Gym',
location: 'Kraków',
availability: null,
capacity: null,
equipment: [],
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
type GymEquipmentLink = {
id: string;
gymId: string;
equipmentId: string;
quantity: number;
equipment: (typeof TEST_EQUIPMENT)[number];
};
function mockApi(opts: { isAdmin?: boolean } = {}) {
const user: User = { ...USER, isAdmin: opts.isAdmin ?? false };
// Stateful gym list: equipment added via POST /gyms/:id/equipment appears on refetch.
const gymsState: { id: string; name: string; location: string | null; availability: unknown; capacity: number | null; equipment: GymEquipmentLink[]; roles: string[] }[] = [
{ ...MY_GYM, equipment: [...MY_GYM.equipment] },
];
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method || 'GET';
if (url.includes('/auth/login')) return jsonResponse(200, { user, accessToken: 'tok-1' });
if (url.includes('/auth/refresh'))
return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } });
if (url.includes('/me/body-parameters'))
return jsonResponse(200, { weight: [], circumferences: [] });
if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] });
if (url.includes('/me'))
return jsonResponse(200, {
user,
memberships: [{ gymId: gymsState[0].id, roles: ['OWNER', 'TRAINER'], gym: gymsState[0] }],
});
if (method === 'GET' && url.endsWith('/equipment'))
return jsonResponse(200, { equipment: TEST_EQUIPMENT });
if (url.includes('/gyms')) {
if (method === 'PATCH' && url.includes('/equipment')) {
const body = JSON.parse(String(init?.body)) as { quantity: number };
const eqId = url.match(/equipment\/([^/]+)$/)?.[1];
gymsState[0] = {
...gymsState[0],
equipment: gymsState[0].equipment.map((l) =>
l.equipmentId === eqId ? { ...l, quantity: body.quantity } : l,
),
};
return jsonResponse(200, { gym: gymsState[0] });
}
if (method === 'POST' && url.includes('/equipment')) {
const body = JSON.parse(String(init?.body)) as { equipmentId: string; quantity?: number };
if (gymsState[0].equipment.some((l) => l.equipmentId === body.equipmentId)) {
return jsonResponse(409, {
error: { code: 'CONFLICT', message: 'Equipment already exists' },
});
}
const eq = TEST_EQUIPMENT.find((e) => e.id === body.equipmentId);
const link: GymEquipmentLink = {
id: `ge-${body.equipmentId}`,
gymId: gymsState[0].id,
equipmentId: body.equipmentId,
quantity: body.quantity ?? 1,
equipment: eq,
};
gymsState[0] = { ...gymsState[0], equipment: [...gymsState[0].equipment, link] };
return jsonResponse(200, { gym: gymsState[0] });
}
if (method === 'DELETE' && url.includes('/equipment')) return jsonResponse(204, {});
if (method === 'POST' && url.includes('/join'))
return jsonResponse(201, { membership: { gymId: OTHER_GYM.id, roles: ['MEMBER'] } });
if (method === 'POST' && url.endsWith('/gyms'))
return jsonResponse(201, { gym: { ...OTHER_GYM, roles: ['OWNER'] } });
if (url.includes('/gyms/all'))
return jsonResponse(200, { gyms: [...gymsState, OTHER_GYM] });
return jsonResponse(200, { gyms: gymsState });
}
if (url.includes('/dashboard'))
return jsonResponse(200, {
killstreak: 0,
activePlan: null,
nextTraining: null,
progress: null,
extra: null,
missing: null,
});
if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] });
if (url.includes('/plans')) return jsonResponse(200, { plans: [] });
if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] });
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
}),
);
}
async function loginToProfile(user: userEvent.User) {
// not logged in -> redirected to /login
expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument();
const email = document.querySelector('input[type="email"]') as HTMLInputElement;
const password = document.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(email, 'jan@test.local');
await user.type(password, 'Password123!');
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Profil' }));
expect(await screen.findByRole('heading', { name: 'Profil' })).toBeInTheDocument();
// gyms section lives on its own subpage — open it via the tile
// (the sidebar also has a „Siłownie" link when the user owns a gym — the tile name carries the gym name)
await user.click(await screen.findByRole('link', { name: /^Siłownie / }));
// tytuł podstrony jest tylko w topmenu (nagłówek Layout)
expect(await screen.findByRole('heading', { name: 'Profil — siłownie' })).toBeInTheDocument();
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('Profile — gyms section', () => {
it('shows the user gym with role and equipment, and a joinable gym', async () => {
mockApi();
const user = userEvent.setup();
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
await loginToProfile(user);
expect(await screen.findByText('Żelazna Świątynia')).toBeInTheDocument();
// a user can hold several roles in the same gym
expect(screen.getByText('Właściciel')).toBeInTheDocument();
// „Trener" appears both as a gym role badge and as the sidebar role label
expect(screen.getAllByText('Trener').length).toBeGreaterThan(0);
// equipment chips show quantity and the type-specific spec
expect(screen.getByText('sztanga · do 100 kg')).toBeInTheDocument();
expect(screen.getByText('hantle ×2 · 2.5–25 kg')).toBeInTheDocument();
expect(screen.getByText('Mega Gym')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Dołącz' })).toBeInTheDocument();
});
it('admin creates a gym from the modal', async () => {
mockApi({ isAdmin: true });
const user = userEvent.setup();
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
await loginToProfile(user);
await screen.findByText('Żelazna Świątynia');
// akcja „Stwórz siłownię” jest za ikoną ➕ (grupa dodawania)
await user.click(screen.getByRole('button', { name: 'Dodawanie' }));
await user.click(screen.getByRole('button', { name: 'Stwórz siłownię' }));
const dialog = await screen.findByRole('dialog');
const nameInput = dialog.querySelector('input') as HTMLInputElement;
await user.type(nameInput, 'Nowa Siłownia');
// wirtualna siłownia (domyślny typ) wymaga lokalizacji
await user.type(screen.getByPlaceholderText('np. Warszawa'), 'Testowo 1');
await user.click(screen.getByRole('button', { name: 'Utwórz' }));
expect(await screen.findByText('Siłownia utworzona')).toBeInTheDocument();
});
it('hides the gym creation button for a non-admin user', async () => {
mockApi();
const user = userEvent.setup();
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
await loginToProfile(user);
await screen.findByText('Żelazna Świątynia');
// non-admin — brak ikony ➕ w nagłówku (akcja „Stwórz siłownię” nie istnieje)
expect(screen.queryByRole('button', { name: 'Dodawanie' })).not.toBeInTheDocument();
});
it('joins an existing gym', async () => {
mockApi();
const user = userEvent.setup();
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
await loginToProfile(user);
await screen.findByText('Mega Gym');
await user.click(screen.getByRole('button', { name: 'Dołącz' }));
expect(await screen.findByText('Dołączono do siłowni: Mega Gym')).toBeInTheDocument();
});
it('adds equipment to an owned gym', async () => {
mockApi();
const user = userEvent.setup();
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
await loginToProfile(user);
await screen.findByText('Żelazna Świątynia');
const equipSelect = screen.getByLabelText('Dodaj sprzęt do Żelazna Świątynia');
await user.selectOptions(equipSelect, 'eq-3');
await waitFor(() => {
expect(screen.getByText('Kettlebell · 4–32 kg')).toBeInTheDocument();
});
expect(screen.getByText('Sprzęt dodany')).toBeInTheDocument();
});
it('adding already-added equipment increases its quantity', async () => {
mockApi();
const user = userEvent.setup();
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
await loginToProfile(user);
await screen.findByText('Żelazna Świątynia');
expect(screen.getByText('hantle ×2 · 2.5–25 kg')).toBeInTheDocument();
// select pokazuje cały katalog — sprzęt już dodany jest oznaczony bieżącą ilością
const equipSelect = screen.getByLabelText('Dodaj sprzęt do Żelazna Świątynia');
await user.selectOptions(equipSelect, 'eq-2');
await waitFor(() => {
expect(screen.getByText('hantle ×3 · 2.5–25 kg')).toBeInTheDocument();
});
expect(screen.getByText('Zwiększono ilość (łącznie 3)')).toBeInTheDocument();
});
});

View File

@@ -1,59 +1,45 @@
import { test, expect } from './fixtures';
import { mockApi, TEST_USER } from './mock-api';
import { mockApi } from './mock-api';
async function loginToProfile(page: import('@playwright/test').Page) {
async function loginToGyms(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();
await page.getByRole('link', { name: 'Profil' }).click();
await expect(page.getByRole('heading', { name: 'Profil' })).toBeVisible();
// gyms section lives on its own subpage — open it via the tile
// (the sidebar also has a „Siłownie" link — the tile name carries the gym name)
await page.getByRole('link', { name: /^Siłownie / }).click();
// tytuł podstrony jest tylko w topmenu (nagłówek Layout)
await expect(page.getByRole('heading', { name: 'Profil — siłownie', exact: true })).toBeVisible();
await page.getByRole('link', { name: 'Siłownie' }).click();
await expect(page.getByRole('heading', { name: 'Siłownie', exact: true })).toBeVisible();
}
test('profil pokazuje siłownie użytkownika z rolą i sprzętem oraz listę do dołączenia', async ({
page,
}) => {
test('/gyms: zakładka „Moje siłownie” pokazuje członkostwa z rolami', async ({ page }) => {
mockApi(page);
await loginToProfile(page);
await loginToGyms(page);
await expect(page.getByRole('heading', { name: 'Profil — siłownie', exact: true })).toBeVisible();
// domyślnie zakładka „Moje siłownie” (user ma członkostwo)
await expect(page.getByRole('heading', { name: 'Moje siłownie' })).toBeVisible();
await expect(page.getByText('Żelazna Świątynia')).toBeVisible();
// user may hold several roles in the same gym
// user may hold several roles in the same gym — badge per role
await expect(page.getByText('Właściciel')).toBeVisible();
await expect(page.getByText('Trener')).toBeVisible();
// equipment chips show quantity and the type-specific spec
// (exact: opcja selectu zawiera specyfikację jako podłańcuch, np. „Sztanga · do 100 kg (1 szt.)”)
await expect(page.getByText('Sztanga · do 100 kg', { exact: true })).toBeVisible();
await expect(page.getByText('Hantle ×2 · 2.5–25 kg', { exact: true })).toBeVisible();
await expect(page.getByText('Mega Gym')).toBeVisible();
await expect(page.getByRole('button', { name: 'Dołącz' })).toBeVisible();
// a non-admin user cannot create gyms — the ➕ icon is absent from the header
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
});
test('użytkownik może dołączyć do istniejącej siłowni', async ({ page }) => {
test('/gyms: modal Dołącz listuje siłownie spoza członkostw', async ({ page }) => {
mockApi(page);
await loginToProfile(page);
await loginToGyms(page);
await page.getByRole('button', { name: 'Dołącz' }).click();
await expect(page.getByText('Dołączono do siłowni: Mega Gym')).toBeVisible();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(dialog.getByText('Mega Gym')).toBeVisible();
// mojej siłowni (właściciel) w liście do dołączenia nie ma
await expect(dialog.getByText('Żelazna Świątynia')).toHaveCount(0);
});
test('admin może stworzyć siłownię i dodać do niej sprzęt', async ({ page }) => {
const adminUser = { ...TEST_USER, isAdmin: true };
mockApi(page, {
loginBody: { user: adminUser, accessToken: 'test-access-token' },
me: { user: adminUser, memberships: [] },
});
await loginToProfile(page);
test('/gyms: można stworzyć siłownię z modala', async ({ page }) => {
mockApi(page);
await loginToGyms(page);
// akcja „Stwórz siłownię” w menu kontekstowym — na PC rozwinięta inline
// akcja „Stwórz siłownię” w topbarze — na PC rozwinięta inline
await page.getByRole('button', { name: 'Stwórz siłownię' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
@@ -62,12 +48,6 @@ test('admin może stworzyć siłownię i dodać do niej sprzęt', async ({ page
await dialog.getByPlaceholder('np. Warszawa').fill('Warszawa');
await page.getByRole('button', { name: 'Utwórz' }).click();
await expect(page.getByText('Siłownia utworzona')).toBeVisible();
const equipSelect = page.getByLabel('Dodaj sprzęt do Żelazna Świątynia');
await equipSelect.selectOption('eq-3');
// exact: opcja selectu zawiera specyfikację jako podłańcuch, np. „Kettlebell · 4–32 kg (1 szt.)”
await expect(page.getByText('Kettlebell · 4–32 kg', { exact: true })).toBeVisible();
await expect(page.getByText('Sprzęt dodany')).toBeVisible();
});
test('/gyms: modal Dołącz — wyszukiwanie i dołączanie do siłowni, do której nie należę', async ({

View File

@@ -50,7 +50,7 @@ test('formularz nowego planu ma wybór tygodnia startu i przycisk „Wstecz” w
await expect(page.getByRole('heading', { name: 'Plan e2e' })).toBeVisible();
});
test('walidacja tytułu i podsumowanie stopki', async ({ page }) => {
test('walidacja tytułu i podsumowanie w kroku 3', async ({ page }) => {
mockPlans(page);
await login(page);
@@ -62,15 +62,16 @@ test('walidacja tytułu i podsumowanie stopki', async ({ page }) => {
await expect(page.getByRole('button', { name: 'Dalej' })).toBeDisabled();
await expect(page.getByRole('button', { name: 'Zapisz' })).toBeDisabled();
// stopka z podsumowaniem tylko na kroku 2 (krok 1 = brak dni, krok 3 = PlanSummary)
// na kroku 1 brak podsumowania (sticky stopka edytora usunięta — podsumowanie tylko w kroku 3)
await expect(page.getByText(/dni · /)).toHaveCount(0);
// dodaj dzień + ćwiczenie (krok 2) → podsumowanie stopki (tyg. 2–4 odzwierciedlają tyg. 1)
// dodaj dzień + ćwiczenie (krok 2) → podsumowanie PlanSummary (tyg. 2–4 odzwierciedlają tyg. 1)
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
await page.getByRole('option', { name: /Przysiady/ }).click();
await page.getByRole('button', { name: 'Dalej' }).click();
await expect(page.getByText(/4 dni · 4 ćwiczenia · 4 serii/)).toBeVisible();
await expect(page.getByText(/bez ćwiczeń/)).toHaveCount(0);
});

View File

@@ -187,20 +187,28 @@ test('mobile 320px: brak poziomego scrolla na podstronach profilu', async ({ pag
await login(page);
await openProfile(page);
const pages: [RegExp, string][] = [
// trzeci element = exact (potrzebne przy „Siłownie” — w treści jest też H3 „Moje siłownie”)
const pages: [RegExp, string, boolean?][] = [
[/Dane osobowe/, 'Profil — dane osobowe'],
[/Parametry ciała/, 'Profil — parametry ciała'],
[/Historia treningów/, 'Profil — historia'],
[/Postępy/, 'Profil — postępy'],
[/^Siłownie /, 'Profil — siłownie'],
// wiersz „Siłownie” prowadzi na /gyms (podstrona /profile/gyms usunięta)
[/^Siłownie /, 'Siłownie', true],
[/^Wnioski /, 'Profil — wnioski'],
];
for (const [linkRe, heading] of pages) {
for (const [linkRe, heading, exact] of pages) {
await page.getByRole('link', { name: linkRe }).click();
await expect(page.getByRole('heading', { name: heading })).toBeVisible();
await expect(page.getByRole('heading', { name: heading, exact: exact ?? false })).toBeVisible();
await expectNoHorizontalScroll(page, heading);
// wstecz na przegląd („<” w topmenu)
await page.locator('header').getByRole('button', { name: 'Wstecz' }).click();
if (heading === 'Siłownie') {
// /gyms to strona główna nawigacji (bez „Wstecz” w topmenu) — powrót przez menu
await page.getByRole('button', { name: 'Otwórz menu' }).click();
await page.getByRole('link', { name: 'Profil' }).click();
} else {
// wstecz na przegląd („<” w topmenu)
await page.locator('header').getByRole('button', { name: 'Wstecz' }).click();
}
await expect(page.getByRole('heading', { name: 'Profil' })).toBeVisible();
}
});