Files
FitOS/admin/test/Logs.test.tsx

264 lines
11 KiB
TypeScript

import { render, screen, act } 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 Logs, { ACTION_KEYS } from '../src/pages/Logs';
import { detailsLines } from '../src/components/LogTable';
import { Topbar } from '../src/topbar';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import i18n from '../src/i18n';
import type { ActivityLog, User } from '../src/api/types';
const LOG1: ActivityLog = {
id: 'log-1',
action: 'plan.activated',
entityType: 'plan',
entityId: 'plan-1',
details: { actorId: 'user-1', title: 'Plan na masę', startDate: '2026-08-24' },
createdAt: '2026-08-20T10:00:00.000Z',
actor: { id: 'user-1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' },
};
const LOG2: ActivityLog = {
id: 'log-2',
action: 'session.completed',
entityType: 'session',
entityId: 'session-1',
details: {
actorId: 'user-2',
dayId: 'day-1',
planId: 'plan-2',
planTitle: 'Plan Anny',
exercises: 4,
sets: 12,
},
createdAt: '2026-08-21T18:30:00.000Z',
actor: { id: 'user-2', email: 'anna@test.local', firstName: 'Anna', lastName: null },
};
const LOG3: ActivityLog = {
id: 'log-3',
action: 'weight.removed',
entityType: 'user',
entityId: 'user-1',
details: { actorId: 'user-1', value: 82.5 },
createdAt: '2026-08-22T09:00:00.000Z',
actor: { id: 'user-1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' },
};
const LOG_EMAIL_DETAIL: ActivityLog = {
id: 'log-4',
action: 'user.created',
entityType: 'user',
entityId: 'user-9',
details: { actorId: 'admin-1', email: 'nowy@test.local', isAdmin: false },
createdAt: '2026-08-23T08:00:00.000Z',
actor: { id: 'admin-1', email: 'ada@test.local', firstName: 'Ada', lastName: 'Admin' },
};
const USER1: User = {
id: 'user-1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
socialMedia: null,
birthDate: null,
heightCm: null,
phone: null,
platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
status: 'ACTIVE',
suspensionUntil: null,
restrictionReason: null,
createdAt: '2026-08-01T10:00:00.000Z',
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockFetchSequence(...responses: Response[]) {
const calls: { url: string; init?: RequestInit }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
// lista userów do filtra „użytkownik” (UserPicker) — poza sekwencją odpowiedzi logów
if (url.includes('/admin/users')) return jsonResponse(200, { users: [USER1] });
calls.push({ url, init });
const next = responses.shift();
if (!next) throw new Error(`No more mocked responses for url: ${url}`);
return next;
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
function renderLogs() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/logs']}>
<QueryClientProvider client={queryClient}>
{/* filtry (akcja, zakres dat) są w top menu — renderujemy też Topbar */}
<Topbar />
<Logs />
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
useListSearch.getState().setQuery('logs', '');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin Logs page', () => {
it('lists activity logs fetched from the API', async () => {
mockFetchSequence(jsonResponse(200, { logs: [LOG1, LOG2, LOG3], total: 3 }));
renderLogs();
// teksty występujące tylko w tabeli (nie w opcjach selecta) — czekamy na dane
// Jan Kowalski w dwóch wierszach (plan.activated + weight.removed)
expect((await screen.findAllByText('Jan Kowalski')).length).toBe(2);
expect(await screen.findByText('Plan na masę')).toBeInTheDocument();
// kolumna daty: dzień na górze, godzina pod spodem
expect(await screen.findByText('20.08.2026')).toBeInTheDocument();
// szczegóły jako naturalny tekst (tytuł i actorId są w innych kolumnach)
expect(await screen.findByText('start: 2026-08-24')).toBeInTheDocument();
// ID aktora w kolumnie „Użytkownik"
expect(screen.getAllByText('user-1').length).toBeGreaterThan(0);
// aktor: e-mail renderowany 1:1 z DTO (redakcja PII jest po stronie serwera)
expect(screen.getByText('anna@test.local')).toBeInTheDocument();
expect(screen.getAllByText('jan@test.local').length).toBeGreaterThan(0);
// etykiety akcji
expect(screen.getAllByText('Plan aktywowany').length).toBeGreaterThan(0);
expect(screen.getAllByText('Sesja zakończona').length).toBeGreaterThan(0);
// usunięcie pomiaru: etykieta PL + naturalne szczegóły z jednostką
expect(screen.getAllByText('Waga usunięta').length).toBeGreaterThan(0);
expect(screen.getByText('wartość: 82.5 kg')).toBeInTheDocument();
// kontekst sesji w szczegółach: tytuł planu i liczniki widoczne, szumne cuidy ukryte
expect(await screen.findByText('plan: Plan Anny')).toBeInTheDocument();
expect(screen.getByText('ćwiczenia: 4')).toBeInTheDocument();
expect(screen.getByText('serie: 12')).toBeInTheDocument();
expect(screen.queryByText(/day-1/)).not.toBeInTheDocument();
expect(screen.queryByText(/plan-2/)).not.toBeInTheDocument();
});
it('sends the action filter to the API', async () => {
const calls = mockFetchSequence(
jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }),
jsonResponse(200, { logs: [LOG2], total: 1 }),
);
renderLogs();
await screen.findByText('Jan Kowalski');
// filtr akcji jest w grupie lejka (ikona „Filtry” w nagłówku)
await userEvent.click(screen.getByRole('button', { name: 'Filtry' }));
await userEvent.selectOptions(
screen.getByRole('combobox', { name: 'Filtruj po akcji' }),
'session.completed',
);
// refetch z nowym queryKey — czekamy na drugi wywołany fetch
await vi.waitFor(() => expect(calls.length).toBe(2));
expect(calls.at(-1)?.url).toContain('action=session.completed');
// mock filtruje po action — w tabeli zostaje tylko wpis sesji
await vi.waitFor(() => expect(screen.queryByText('Plan na masę')).not.toBeInTheDocument());
});
it('wysyła wybranego użytkownika jako serwerowy filtr userId do API', async () => {
const calls = mockFetchSequence(
jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }),
jsonResponse(200, { logs: [LOG1], total: 1 }),
);
renderLogs();
await screen.findByText('Jan Kowalski');
// filtr użytkownika (UserPicker) też żyje w grupie lejka
await userEvent.click(screen.getByRole('button', { name: 'Filtry' }));
await userEvent.click(screen.getByRole('combobox', { name: 'Filtruj po użytkowniku' }));
await userEvent.click(screen.getByRole('option', { name: /Jan Kowalski/ }));
// refetch z nowym queryKey — czekamy na drugi wywołany fetch
await vi.waitFor(() => expect(calls.length).toBe(2));
expect(calls.at(-1)?.url).toContain('userId=user-1');
// mock zwraca tylko wpisy user-1 — w tabeli znika wiersz Anny
await vi.waitFor(() => expect(screen.queryByText('Anna')).not.toBeInTheDocument());
});
it('sends the selected month as from/to to the API', async () => {
const calls = mockFetchSequence(
jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }),
jsonResponse(200, { logs: [LOG1], total: 1 }),
jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }),
);
renderLogs();
await screen.findByText('Jan Kowalski');
// otwieramy grupę „Filtry”, potem panel selektora miesiąca i wybieramy sierpień bieżącego roku
await userEvent.click(screen.getByRole('button', { name: 'Filtry' }));
await userEvent.click(screen.getByRole('button', { name: 'Wszystkie' }));
await userEvent.click(screen.getByRole('button', { name: 'Sie' }));
// refetch z nowym queryKey — czekamy na drugi wywołany fetch
await vi.waitFor(() => expect(calls.length).toBe(2));
const url = new URL(calls.at(-1)!.url, 'http://localhost');
expect(url.searchParams.get('from')).toBe('2026-08-01');
expect(url.searchParams.get('to')).toBe('2026-08-31');
// etykieta przycisku pokazuje wybrany miesiąc
expect(screen.getByRole('button', { name: 'Sierpień 2026' })).toBeInTheDocument();
// ponowne otwarcie panelu i wybór „Wszystkie” cofa filtr miesiąca (brak from/to)
await userEvent.click(screen.getByRole('button', { name: 'Sierpień 2026' }));
await userEvent.click(screen.getByRole('button', { name: 'Wszystkie' }));
await vi.waitFor(() => expect(calls.length).toBe(3));
const url2 = new URL(calls.at(-1)!.url, 'http://localhost');
expect(url2.searchParams.get('from')).toBeNull();
expect(url2.searchParams.get('to')).toBeNull();
expect(screen.getByRole('button', { name: 'Wszystkie' })).toBeInTheDocument();
});
it('filters the loaded page by the header search box', async () => {
mockFetchSequence(jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }));
renderLogs();
await screen.findByText('Jan Kowalski');
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('logs', 'anna'));
expect(screen.queryByText('Jan Kowalski')).not.toBeInTheDocument();
// LOG2: aktor Anna bez nazwiska — widoczna sama pierwsza imienna część
expect(screen.getByText('Anna')).toBeInTheDocument();
});
it('renderuje e-maile w szczegółach logów 1:1 z DTO (redakcja po stronie serwera)', () => {
const lines = detailsLines(LOG_EMAIL_DETAIL);
expect(lines).toContain('e-mail: nowy@test.local');
});
it('shows an error when the logs request fails', async () => {
mockFetchSequence(
jsonResponse(500, { error: { code: 'INTERNAL', message: 'Błąd wewnętrzny' } }),
);
renderLogs();
expect(await screen.findByText(/Błąd: Błąd wewnętrzny/)).toBeInTheDocument();
});
it('shows an empty state when there are no logs', async () => {
mockFetchSequence(jsonResponse(200, { logs: [], total: 0 }));
renderLogs();
expect(await screen.findByText('Brak zdarzeń')).toBeInTheDocument();
});
it('tłumaczy każdą akcję dostępną w filtrze', () => {
// strażnik spójności: każdy klucz ACTION_KEYS musi mieć etykietę PL w logs.json
for (const action of ACTION_KEYS) {
const label = i18n.t(`logs:actions.${action}`, { defaultValue: '' });
expect(label, `brak tłumaczenia akcji: ${action}`).not.toBe('');
}
});
});