Files
FitOS/admin/test/UserDetail.test.tsx

269 lines
9.8 KiB
TypeScript

import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserDetail from '../src/pages/users/UserDetail';
import { setAccessToken } from '../src/api/client';
import type { Gym, User } from '../src/api/types';
const G1: Gym = {
id: 'g1',
name: 'Gym A',
location: 'Warszawa',
availability: null,
capacity: 50,
equipment: [],
_count: { memberships: 1 },
};
const U1: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: 'jano',
socialMedia: null,
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: null,
isAdmin: true,
availability: null,
priorities: null,
exclusions: null,
developMuscles: ['chest'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
status: 'ACTIVE',
suspensionUntil: null,
restrictionReason: null,
createdAt: '2026-08-01T10:00:00.000Z',
memberships: [{ gymId: 'g1', roles: ['OWNER', 'TRAINER'], gym: G1 }],
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
/**
* Mockuje fetch wg fragmentu URL (odporny na kolejność żądań). Zwraca listę wywołań.
* Fragmenty pasujące do wielu endpointów muszą być rejestrowane od najbardziej ogólnego.
*/
function mockFetchRoutes(routes: Array<[string, () => unknown]>) {
const calls: { url: string; init?: RequestInit }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
calls.push({ url, init });
// odwrócona kolejność rejestracji: specyficzne trasy wygrywają z ogólnymi
const entry = [...routes].reverse().find(([frag]) => url.includes(frag));
if (!entry) throw new Error(`No mocked route for url: ${url}`);
return jsonResponse(200, entry[1]());
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
const BASE_ROUTES: Array<[string, () => unknown]> = [
['/admin/users', () => ({ users: [U1] })],
['/claims', () => ({ claims: [] })],
['/activity', () => ({ logs: [], total: 0 })],
];
function renderUserDetail() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/users/u1']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/users/:id" element={<UserDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserDetail (konsola użytkownika)', () => {
it('pokazuje badge bana na koncie zablokowanym', async () => {
mockFetchRoutes([
...BASE_ROUTES,
['/admin/users', () => ({ users: [{ ...U1, status: 'BANNED', restrictionReason: 'Powód' }] })],
]);
renderUserDetail();
expect(await screen.findByText('Zablokowane')).toBeInTheDocument();
expect(screen.getByText('Powód: Powód')).toBeInTheDocument();
});
it('pokazuje badge zawieszenia z terminem', async () => {
mockFetchRoutes([
...BASE_ROUTES,
[
'/admin/users',
() => ({
users: [
{
...U1,
status: 'SUSPENDED',
suspensionUntil: '2026-11-01T12:00:00.000Z',
restrictionReason: null,
},
],
}),
],
]);
renderUserDetail();
expect(await screen.findByText(/Zawieszone do/)).toBeInTheDocument();
});
it('renderuje konsolę: nagłówek h2, panel podsumowania i sekcje bez statystyk treningowych', async () => {
mockFetchRoutes([
...BASE_ROUTES,
['/claims', () => ({ claims: [{ id: 'c1', gymName: 'Gym B', status: 'PENDING', createdAt: '2026-09-01T10:00:00.000Z', user: { firstName: 'Jan', lastName: 'Kowalski', email: 'jan@test.local' } }] })],
]);
renderUserDetail();
// nagłówek: nazwa (h2) + powrót na listę
expect(await screen.findByRole('heading', { level: 2, name: 'jano' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Wróć' })).toHaveAttribute('href', '/users');
// panel podsumowania: e-mail + nick + badge admina + pasek danych administracyjnych
expect(screen.getByText('jan@test.local')).toBeInTheDocument();
expect(screen.getByText('@jano')).toBeInTheDocument();
expect(screen.getByText('Admin')).toBeInTheDocument();
expect(screen.getByText('Ostatnie logowanie')).toBeInTheDocument();
expect(screen.getByText('Członkostwa')).toBeInTheDocument();
expect(screen.getByText('Konto od')).toBeInTheDocument();
expect(screen.getByText('Utworzony 01.08.2026')).toBeInTheDocument();
// statystyki treningowe zniknęły z panelu admina
expect(screen.queryByText('Killstreak')).not.toBeInTheDocument();
expect(screen.queryByText('Objętość 7 dni')).not.toBeInTheDocument();
expect(screen.queryByText('Sesje')).not.toBeInTheDocument();
// brak linków do usuniętych podstron
for (const to of ['info', 'body-parameters', 'history', 'progress', 'memberships', 'claims']) {
expect(screen.queryByRole('link', { name: new RegExp(to, 'i') })).not.toBeInTheDocument();
}
// karta Wnioski: wiersz prowadzi do /verifications/:id ze statusem
const claimLink = screen.getByRole('link', { name: 'Gym B' });
expect(claimLink).toHaveAttribute('href', '/verifications/c1');
expect(claimLink.closest('div')).toHaveTextContent('Oczekuje');
});
it('karta członkostw: wiersz otwiera menu i zapis ról wysyła PATCH z pełną listą', async () => {
const calls = mockFetchRoutes([
...BASE_ROUTES,
['/memberships/', () => ({})],
]);
renderUserDetail();
// wiersz: siłownia + role jako pigułki (spójne z konsolą siłowni)
const row = await screen.findByText('Gym A');
expect(row.closest('tr')).toHaveTextContent('Warszawa');
expect(row.closest('tr')).toHaveTextContent('Właściciel');
expect(row.closest('tr')).toHaveTextContent('Trener');
fireEvent.click(row.closest('tr') as HTMLElement);
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('Członkostwo: Gym A');
// zmiana: odejmij TRAINER, zostaw OWNER → PATCH pełnej listy
fireEvent.click(within(dialog).getByRole('checkbox', { name: 'Trener — Gym A' }));
fireEvent.click(within(dialog).getByRole('button', { name: 'Zapisz role' }));
await waitFor(() => {
const patch = calls.find((c) => c.init?.method === 'PATCH');
expect(patch?.url).toContain('/admin/users/u1/memberships/g1');
expect(JSON.parse(String(patch?.init?.body))).toEqual({ roles: ['OWNER'] });
});
});
it('karta członkostw: wyrzucenie wymaga powodu i wysyła DELETE z powodem w ciele', async () => {
const calls = mockFetchRoutes([
...BASE_ROUTES,
['/memberships/', () => ({})],
]);
renderUserDetail();
const row = await screen.findByText('Gym A');
fireEvent.click(row.closest('tr') as HTMLElement);
const dialog = await screen.findByRole('dialog');
const removeBtn = within(dialog).getByRole('button', { name: 'Wyrzuć członka' });
expect(removeBtn).toBeDisabled();
fireEvent.change(within(dialog).getByRole('textbox', { name: 'Powód' }), {
target: { value: 'Wielokrotne łamanie regulaminu' },
});
fireEvent.click(removeBtn);
await waitFor(() => {
const del = calls.find((c) => c.init?.method === 'DELETE');
expect(del?.url).toContain('/admin/users/u1/memberships/g1');
expect(JSON.parse(String(del?.init?.body))).toEqual({
reason: 'Wielokrotne łamanie regulaminu',
});
});
});
it('karta logi konta: aktor, akcja, IP logowania i kara z powodem', async () => {
const logs = [
{
id: 'l1',
action: 'user.status.changed',
entityType: 'user',
entityId: 'u1',
details: { actorId: 'a1', status: 'BANNED', restrictionReason: 'Sprzedaż kont' },
createdAt: '2026-10-20T08:00:00.000Z',
actor: { id: 'a1', email: 'ada@test.local', firstName: 'Ada', lastName: 'Admin' },
},
{
id: 'l2',
action: 'user.logged_in',
entityType: 'user',
entityId: 'u1',
details: { actorId: 'u1', client: 'app', ip: '203.0.113.9' },
createdAt: '2026-10-19T18:30:00.000Z',
actor: { id: 'u1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' },
},
];
mockFetchRoutes([
['/admin/users', () => ({ users: [{ ...U1, lastLoginAt: '2026-10-19T18:30:00.000Z' }] })],
['/claims', () => ({ claims: [] })],
['/activity', () => ({ logs, total: logs.length })],
]);
renderUserDetail();
// komórka ostatniego logowania w panelu podsumowania
expect(await screen.findByText('Ostatnie logowanie')).toBeInTheDocument();
expect(screen.getAllByText(/19\.10\.2026/).length).toBeGreaterThanOrEqual(1);
// logi: kto (aktor-admin) wykonał akcję + szczegóły kary + IP logowania
expect(screen.getByText('Logi konta')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Wszystkie logi' })).toHaveAttribute(
'href',
'/users/u1/logs',
);
expect(screen.getByText('przez Ada Admin')).toBeInTheDocument();
expect(screen.getByText('Zmiana statusu konta')).toBeInTheDocument();
expect(screen.getByText(/powód kary: Sprzedaż kont/)).toBeInTheDocument();
expect(screen.getByText(/adres IP: 203\.0\.113\.9/)).toBeInTheDocument();
});
it('karta logi konta: stan pusty', async () => {
mockFetchRoutes(BASE_ROUTES);
renderUserDetail();
expect(await screen.findByText('Logi konta')).toBeInTheDocument();
expect(screen.getByText('Brak zdarzeń konta.')).toBeInTheDocument();
});
});