Files
FitOS/app/test/PlanDetail.test.tsx

560 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { render, screen, waitFor, within } 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 OWNER: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: null,
isAdmin: false,
availability: null,
priorities: 'chest',
exclusions: 'knee',
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
const RECIPIENT: User = {
...OWNER,
id: 'u2',
email: 'anna@test.local',
firstName: 'Anna',
lastName: 'Nowak',
};
const TRAINEE = {
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
gyms: [{ id: 'gym-1', name: 'Żelazna Świątynia' }],
activePlan: null,
killstreak: 0,
lastSessionAt: null,
flags: [],
};
/** Detal planu (właściciel = u1); warianty: canManage / shares / sharedBy. */
function planDetail(overrides: Record<string, unknown> = {}) {
return {
id: 'plan-1',
userId: 'u1',
title: 'Plan masowy',
status: 'DRAFT',
weeksCount: 1,
startDate: null,
gym: null,
creator: null,
canManage: true,
shares: [],
weeks: [
{
id: 'tw-1',
index: 0,
customName: null,
days: [
{
id: 'td-1',
dayOfWeek: 1,
date: null,
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'tpe-1',
exerciseId: 'ex-1',
order: 0,
exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
sets: [
{
id: 'tps-1',
index: 0,
reps: 10,
loadKg: 60,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
],
},
],
},
],
...overrides,
};
}
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
interface MockOpts {
user: User;
memberships?: { gymId: string; roles: string[] }[];
plans?: Record<string, unknown>[];
sharedWithMe?: Record<string, unknown>[];
plan?: Record<string, unknown>;
trainees?: unknown[];
trainers?: unknown[];
}
interface Capture {
shareBody?: Record<string, unknown>;
reopenUrl?: string;
suspendUrl?: string;
resumeUrl?: string;
deleteUrl?: string;
}
function mockApi(capture: Capture, opts: MockOpts) {
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: opts.user, accessToken: 'tok-1' });
if (url.includes('/auth/refresh'))
return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } });
if (url.includes('/me/active-session')) return jsonResponse(200, { session: null });
if (url.endsWith('/me'))
return jsonResponse(200, { user: opts.user, memberships: opts.memberships ?? [] });
if (url.includes('/me/trainers')) return jsonResponse(200, { trainers: opts.trainers ?? [] });
if (url.includes('/trainer/trainees'))
return jsonResponse(200, { trainees: opts.trainees ?? [] });
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('/gyms')) return jsonResponse(200, { gyms: [] });
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
if (url.includes('/plans/shared-with-me'))
return jsonResponse(200, { plans: opts.sharedWithMe ?? [] });
if (url.includes('/plans/plan-1/share')) {
if (method === 'POST') {
capture.shareBody = JSON.parse(String(init?.body));
return jsonResponse(201, { ok: true });
}
if (method === 'DELETE') return jsonResponse(200, { ok: true });
}
if (url.endsWith('/plans')) return jsonResponse(200, { plans: opts.plans ?? [] });
if (url.includes('/plans/plan-1/reopen') && method === 'POST') {
capture.reopenUrl = url;
return jsonResponse(200, { ok: true });
}
if (url.includes('/plans/plan-1/suspend') && method === 'POST') {
capture.suspendUrl = url;
return jsonResponse(200, { ok: true });
}
if (url.includes('/plans/plan-1/resume') && method === 'POST') {
capture.resumeUrl = url;
return jsonResponse(200, { ok: true, movedDays: 0 });
}
if (url.endsWith('/plans/plan-1') && method === 'DELETE') {
capture.deleteUrl = url;
return new Response(null, { status: 204 });
}
if (url.includes('/plans/plan-1'))
return jsonResponse(200, { plan: opts.plan ?? planDetail() });
return jsonResponse(200, {});
}),
);
}
function renderApp() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
}
async function loginAndOpenPlans(user: userEvent.User, email: string) {
expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument();
const emailInput = document.querySelector('input[type="email"]') as HTMLInputElement;
const password = document.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(emailInput, email);
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: 'Plany treningowe' }));
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
// hub sekcji → kategoria „Aktualne” (powrót „Wstecz” w topbarze do huba)
await user.click(await screen.findByRole('link', { name: /^Aktualne/ }));
expect(await screen.findByRole('button', { name: 'Wstecz' })).toBeInTheDocument();
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('PlanDetail — udostępnianie planów (WP4)', () => {
it('właściciel: akcje w topmenu (Aktywuj/Edytuj/Usuń/Udostępnij) i wybór tygodnia startu', async () => {
mockApi(
{},
{
user: OWNER,
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
plans: [planDetail()],
},
);
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
expect(within(header).getByRole('button', { name: 'Aktywuj' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Edytuj' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Usuń' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Udostępnij' })).toBeInTheDocument();
// DRAFT + canManage — wybór tygodnia startu w karcie
expect(screen.getByText('Tydzień startu')).toBeInTheDocument();
});
it('szkic z planowanym startem: picker preuzupełnia tydzień, „Aktywuj” aktywny od razu', async () => {
const now = new Date();
const mon = new Date(now.getFullYear(), now.getMonth(), now.getDate());
mon.setDate(mon.getDate() - ((mon.getDay() + 6) % 7) + 7); // poniedziałek przyszłego tygodnia
const key = `${mon.getFullYear()}-${String(mon.getMonth() + 1).padStart(2, '0')}-${String(
mon.getDate(),
).padStart(2, '0')}`;
const draft = planDetail({ startDate: `${key}T00:00:00.000Z` });
mockApi({}, { user: OWNER, plans: [draft], plan: draft });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
// zapisany planowany start widoczny jako podsum tygodnia…
const sun = new Date(mon);
sun.setDate(mon.getDate() + 6);
const fmt = (d: Date) =>
`${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}.${d.getFullYear()}`;
expect(await screen.findByText(`Start: tydzień ${fmt(mon)} – ${fmt(sun)}`)).toBeInTheDocument();
// …i „Aktywuj” w topmenu jest aktywny bez ręcznego zaznaczania tygodnia
const header = document.querySelector('header')!;
expect(within(header).getByRole('button', { name: 'Aktywuj' })).toBeEnabled();
});
it('odbiorca share’a: sekcja „Udostępnione mi”, plan read-only (bez akcji i bez tygodnia startu)', async () => {
const shared = planDetail({
canManage: false,
shares: undefined,
sharedBy: { id: 'u1', firstName: 'Jan', lastName: 'Kowalski' },
});
mockApi(
{},
{
user: RECIPIENT,
plans: [],
sharedWithMe: [shared],
plan: shared,
},
);
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, RECIPIENT.email);
await user.click(screen.getByRole('button', { name: 'Wstecz' }));
await user.click(await screen.findByRole('link', { name: /^Udostępnione/ }));
// sekcja „Udostępnione mi” z etykietą twórcy
expect(await screen.findByRole('heading', { name: 'Udostępnione mi' })).toBeInTheDocument();
expect(screen.getByText('udostępnił: Jan Kowalski')).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
// read-only: brak akcji statusowych, „Udostępnij” i wyboru tygodnia startu
expect(screen.queryByRole('button', { name: 'Aktywuj' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Edytuj' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Usuń' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Udostępnij' })).not.toBeInTheDocument();
expect(screen.queryByText('Tydzień startu')).not.toBeInTheDocument();
});
it('dialog „Udostępnij plan”: podopieczni z checkboxem, share = POST /plans/:id/share', async () => {
const capture: Capture = {};
mockApi(capture, {
user: OWNER,
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
plans: [planDetail()],
trainees: [TRAINEE],
});
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Udostępnij' }));
const dialog = await screen.findByRole('dialog', { name: 'Udostępnij plan' });
expect(within(dialog).getByText('Moje podopieczne')).toBeInTheDocument();
expect(within(dialog).getByText('Anna Nowak')).toBeInTheDocument();
const checkbox = within(dialog).getByRole('checkbox') as HTMLInputElement;
await user.click(checkbox);
await waitFor(() => expect(capture.shareBody).toMatchObject({ userId: 'trainee-1' }));
});
it('właściciel z udostępnionym planem: etykieta „udostępnione: …” w meta', async () => {
mockApi(
{},
{
user: OWNER,
plans: [planDetail()],
plan: planDetail({
shares: [
{
userId: 'trainee-1',
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' },
},
],
}),
},
);
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
expect(screen.getByText('udostępnione: Anna Nowak')).toBeInTheDocument();
});
});
describe('PlanDetail — statusy i klikalność dni', () => {
it('szkic: wiersz dnia bez linku (dzień klikalny tylko w aktywnym planie)', async () => {
mockApi({}, { user: OWNER, plans: [planDetail()] });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
expect(screen.getByText('Poniedziałek')).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /Poniedziałek/ })).not.toBeInTheDocument();
});
it('plan aktywny: cały dzień to link do /day/:id; tylko „Porzuć” (bez „Wznów”)', async () => {
const active = planDetail({ status: 'ACTIVE', weeksCount: 1, startDate: '2026-10-12' });
mockApi({}, { user: OWNER, plans: [active], plan: active });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
// cały wiersz dnia = jeden link do dnia treningu (pojedynczy hover)
const dayLink = await screen.findByRole('link', { name: /Poniedziałek/ });
expect(dayLink).toHaveAttribute('href', '/day/td-1');
expect(screen.queryByRole('button', { name: 'Wykonaj' })).not.toBeInTheDocument();
const header = document.querySelector('header')!;
expect(within(header).getByRole('button', { name: 'Porzuć' })).toBeInTheDocument();
// dzień PLANNED = plan w trakcie realizacji
expect(
within(header).queryByRole('button', { name: 'Oznacz jako ukończony' }),
).not.toBeInTheDocument();
expect(within(header).queryByRole('button', { name: 'Wznów' })).not.toBeInTheDocument();
});
it('plan ukończony: akcja „Wznów”; potwierdzenie = POST /plans/:id/reopen', async () => {
const capture: Capture = {};
const closed = planDetail({ status: 'COMPLETED' });
mockApi(capture, { user: OWNER, plans: [closed], plan: closed });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('button', { name: 'Wstecz' }));
await user.click(await screen.findByRole('link', { name: /^Archiwum/ }));
await user.click(await screen.findByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
await user.click(within(header).getByRole('button', { name: 'Wznów' }));
const dialog = await screen.findByRole('dialog', { name: 'Wznowić plan?' });
await user.click(within(dialog).getByRole('button', { name: 'Wznów' }));
await waitFor(() => expect(capture.reopenUrl).toContain('/plans/plan-1/reopen'));
});
it('plan ukończony przy innym aktywnym: „Wznów” zablokowany + hint', async () => {
const closed = planDetail({ status: 'COMPLETED' });
const other = planDetail({
id: 'plan-2',
title: 'Inny plan',
status: 'ACTIVE',
weeksCount: 1,
startDate: '2026-10-12',
});
mockApi({}, { user: OWNER, plans: [closed, other], plan: closed });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('button', { name: 'Wstecz' }));
await user.click(await screen.findByRole('link', { name: /^Archiwum/ }));
await user.click(await screen.findByRole('link', { name: /Plan masowy/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
expect(within(header).getByRole('button', { name: 'Wznów' })).toBeDisabled();
expect(screen.getByText(/Aby wznowić ten plan/)).toBeInTheDocument();
});
it('plan aktywny: akcja „Zawiesź"; potwierdzenie = POST /plans/:id/suspend', async () => {
const capture: Capture = {};
const active = planDetail({ status: 'ACTIVE', weeksCount: 1, startDate: '2026-10-12' });
mockApi(capture, { user: OWNER, plans: [active], plan: active });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
await user.click(within(header).getByRole('button', { name: 'Zawiesź' }));
const dialog = await screen.findByRole('dialog', { name: 'Zawiesić plan?' });
expect(within(dialog).getByText(/Slot aktywnego planu zostanie zwolniony/)).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Zawiesź' }));
await waitFor(() => expect(capture.suspendUrl).toContain('/plans/plan-1/suspend'));
});
it('plan zawieszony: akcja „Wznów"; potwierdzenie = POST /plans/:id/resume (bez „Edytuj")', async () => {
const capture: Capture = {};
const paused = planDetail({ status: 'SUSPENDED', weeksCount: 1, startDate: '2026-10-12' });
mockApi(capture, { user: OWNER, plans: [paused], plan: paused });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
// dzień wstrzymanego planu nie jest klikalnym treningiem
expect(screen.queryByRole('link', { name: /Poniedziałek/ })).not.toBeInTheDocument();
const header = document.querySelector('header')!;
expect(within(header).queryByRole('button', { name: 'Edytuj' })).not.toBeInTheDocument();
expect(within(header).queryByRole('button', { name: 'Zawiesź' })).not.toBeInTheDocument();
await user.click(within(header).getByRole('button', { name: 'Wznów' }));
const dialog = await screen.findByRole('dialog', { name: 'Wznowić plan?' });
expect(within(dialog).getByText(/dni nie zostaną usunięte/)).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Wznów' }));
await waitFor(() => expect(capture.resumeUrl).toContain('/plans/plan-1/resume'));
});
it('plan aktywny: „Edytuj” i „Usuń” w topmenu; potwierdzenie = DELETE /plans/:id', async () => {
const capture: Capture = {};
const active = planDetail({ status: 'ACTIVE', weeksCount: 1, startDate: '2026-10-12' });
mockApi(capture, { user: OWNER, plans: [active], plan: active });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
expect(within(header).getByRole('button', { name: 'Edytuj' })).toBeInTheDocument();
await user.click(within(header).getByRole('button', { name: 'Usuń' }));
const dialog = await screen.findByRole('dialog', { name: 'Usunąć plan?' });
expect(within(dialog).getByText(/historią sesji/)).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Usuń' }));
await waitFor(() => expect(capture.deleteUrl).toContain('/plans/plan-1'));
});
it('plan ukończony: obok „Wznów” jest „Usuń”', async () => {
const closed = planDetail({ status: 'COMPLETED' });
mockApi({}, { user: OWNER, plans: [closed], plan: closed });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('button', { name: 'Wstecz' }));
await user.click(await screen.findByRole('link', { name: /^Archiwum/ }));
await user.click(await screen.findByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
expect(within(header).getByRole('button', { name: 'Wznów' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Usuń' })).toBeInTheDocument();
// plan zamknięty — brak edycji struktury (najpierw wznowienie)
expect(within(header).queryByRole('button', { name: 'Edytuj' })).not.toBeInTheDocument();
});
it('historia edycji aktywnego planu: notatka, autor i liczniki zmian', async () => {
const active = planDetail({
status: 'ACTIVE',
weeksCount: 1,
startDate: '2026-10-12',
edits: [
{
id: 'pe-1',
note: 'Zamiana dni po kontuzji kolana',
createdAt: '2026-10-20T10:00:00.000Z',
summary: { setsChanged: 3, exercisesAdded: 1, daysRemoved: 0 },
actor: { id: 'u1', firstName: 'Jan', lastName: 'Kowalski' },
},
],
});
mockApi({}, { user: OWNER, plans: [active], plan: active });
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Historia zmian w planie' })).toBeInTheDocument();
expect(screen.getByText('Zamiana dni po kontuzji kolana')).toBeInTheDocument();
expect(screen.getByText('+1 ćwiczenie')).toBeInTheDocument();
expect(screen.getByText('3 serie')).toBeInTheDocument();
// autor to zalogowany właściciel
expect(screen.getByText('Ty')).toBeInTheDocument();
});
});