Baseline: stan przed refaktoryzacja struktury

This commit is contained in:
tisachi
2026-09-04 19:06:19 +02:00
commit 1c8594ad96
369 changed files with 71407 additions and 0 deletions

9
.gitignore vendored Normal file
View File

@@ -0,0 +1,9 @@
node_modules/
dist/
.env
*.log
.DS_Store
.vite/
test-results/
playwright-report/
blob-report/

32
AGENTS.md Normal file
View File

@@ -0,0 +1,32 @@
# FitOS — zasady pracy z kodem
## Struktura
- `app` (React+Vite, 5173), `admin` (React+Vite, 5174), `api` (Express+Prisma+PostgreSQL, 9002).
## Testy — obowiązkowe po każdej zmianie
- `app`/`admin`: `npm test` (vitest), `npm run test:e2e` (Playwright, API mockowane, dev server sam). `api`: `npm test` (unit+integration, supertest).
- Testy aktualizujesz w tej samej zmiance co kod. Zmiana UI → najpierw grep starych tekstów/selectorów w testach.
- e2e: `import { test } from './fixtures'` (NIE `@playwright/test`) — guard FAIL przy `console.error`/`pageerror`; wyjątek: `allowConsoleError(page, /re/)` + komentarz. Ignorowane: 401. 403/404/5xx = FAIL.
- e2e bez API/DB: `mockApi(page, ...)` z `e2e/mock-api.ts`. Nowe pliki: `e2e/<obszar>.spec.ts`, opisy PL.
- Selektory: `getByRole`/`getByText`/`input[type=...]` — `getByLabel` NIE działa (`Field` bez `<label>`).
## Zmiana kontraktu API — aktualizuj WSZYSTKO w jednej zmiance
1. `api/src/routes/**` + walidacja zod + `api/test/**`
2. typy: `app/src/api/types.ts` i/lub `admin/src/api/types.ts`
3. front: `api/queries.ts`, `pages/**`, `store/auth.ts`
4. mocki `app|admin/e2e/mock-api.ts` + testy e2e
5. `npm test` (api) + `npm test`/`test:e2e` (dotknięte fronty)
`prisma/schema.prisma` → `npm run prisma:migrate` (kontener API sam robi `migrate deploy` + seed przy starcie).
## Kontenery — rebuilduj tylko dotknięte
- `api/`: `fitos-api` (9002) + `fitos-db` (pg16, wolumen `fitos_pgdata`). `admin/`: 9000 (nginx+dist). `app/`: 9001 (nginx+dist).
- Zmiana `<pkg>/src/**` (albo `api/prisma/**`, `index.html`) → w katalogu `<pkg>/`: `docker compose build <pkg> && docker compose up -d`.
- `.env` api → `up -d --force-recreate api`. Nigdy nie ruszaj wolumenu `fitos_pgdata`.
- Weryfikacja po zmianie api: `docker compose ps` + `curl localhost:9002/health`.
## Komendy
| | komenda |
| --- | --- |
| app/admin | `npm test`, `npm run test:e2e`, `test:e2e:ui`, `test:e2e:install` |
| api | `npm test`, `npm run seed`, `npm run prisma:migrate` |

114
README.md Normal file
View File

@@ -0,0 +1,114 @@
# FitOS
Silnik planów treningowych. Trzy niezależne aplikacje (osobne kontenery Docker):
| Aplikacja | Folder | Stack | Port (dev) |
|---|---|---|---|
| FitOS App | `app/` | React + Vite (PWA) + nginx | 9001 |
| FitOS Api | `api/` | Node.js + Express + Prisma + PostgreSQL | 9002 |
| FitOS Admin | `admin/` | React + Vite + nginx | 9000 |
Koncepcja: `1787402270027-fit-os-koncepcja.md`.
## Uruchomienie
### 1. API + PostgreSQL
```bash
cd api
copy .env.example .env # edytuj sekrety
docker compose up -d --build
```
Przy starcie kontenera API: `prisma migrate deploy` → seed (pula ćwiczeń + pierwszy admin z env) → start serwera.
- API: `http://tisachi.ddns.net:9002/api/v1`
- Swagger: `http://tisachi.ddns.net:9002/api/docs`
- Health: `http://tisachi.ddns.net:9002/health`
- Pierwszy admin: `FITOS_FIRST_ADMIN_EMAIL` / `FITOS_FIRST_ADMIN_PASSWORD` z `.env`
### 2. App
```bash
cd app
copy .env.example .env # API_URL (opcjonalnie; domyślnie http://tisachi.ddns.net:9002)
docker compose up -d --build
```
- App: `http://tisachi.ddns.net:9001`
Adres API podpinany w runtime przez `app/public/config.js` (`window.__FITOS_CONFIG__.apiUrl`) — bez rebuildu. `VITE_API_URL` tylko jako fallback build-time.
### 3. Admin
```bash
cd admin
copy .env.example .env
docker compose up -d --build
```
- Admin: `http://tisachi.ddns.net:9000`
## Dev bez Dockera
```bash
# API (wymaga lokalnego PostgreSQL na DATABASE_URL)
cd api
npm install
npx prisma migrate dev
npm run seed
npm run dev
# App
cd app
npm install
npm run dev # http://localhost:5173
# Admin
cd admin
npm install
npm run dev # http://localhost:5174
```
## Testy
W każdym projekcie: `npm test` (pojedynczy przebieg) lub `npm run test:watch`.
### API (`api/`)
- Framework: Vitest + Supertest; testy w `api/test/` (unit + integration).
- Unit (bez bazy): jwt, walidacja, error handler, middleware auth, killstreak (fake timers + property-based fast-check), scheduler.
- Integration (wymagają lokalnego PostgreSQL na `localhost:5432`, user/pass `fitos`): auth, me, plans, sessions, calendar, dashboard, admin, puzzles/gyms.
- Baza testowa `fitos_test` jest tworzona automatycznie przez `test/globalSetup.ts` (raz na uruchomienie) + `prisma migrate deploy`; zmienne środowiskowe testowe w `test/env.ts`.
- Testy integracyjne uruchamiane równolegle na wspólnej bazie — dane tworzone z losowymi sufiksami (bez globalnego czyszczenia).
### App i Admin (`app/`, `admin/`)
- Framework: Vitest + jsdom + Testing Library (React); testy w `test/`.
- Zakres: klient API (tokeny, 401→refresh→retry, logout event), store auth (login/register/logout/init), helpery, strony Login/Register (app) oraz Login/Users (admin).
- Bez backendu — `fetch` mockowany; `localStorage` polyfillowane w `test/setup.ts`.
## Kluczowe decyzje (MVP)
- Autoryzacja: e-mail + hasło, JWT access (15 min, header) + refresh (7 dni, httpOnly cookie), `token_version` do odwołania.
- Plan: draft → active → completed/abandoned; tygodnie zdefiniowane osobno; data startu (poniedziałek) — można ją podać przy tworzeniu (plan tworzony i aktywowany w jednym kroku) albo później przy aktywacji; daty dni liczone automatycznie.
- Dzień: planned → completed/skipped; auto-wygasanie o 23:59 → skipped (scheduler).
- Sesja: in_progress → completed/abandoned; auto-abandon po 24h (scheduler); jedna aktywna sesja na dzień.
- Killstreak: liczba kolejnych skutecznych treningów (wszystkie serie sesji = zaplanowane + dodane); reset po pominięciu lub dniu częściowym.
- Pula ćwiczeń: seed (idempotentny upsert po slug + seed_version), cała pula dostępna w MVP (bez filtrowania przez sprzęt siłowni).
- PWA: tylko instalowalność (manifest), bez cache offline.
- Panel admina: osobna aplikacja (dodawanie siłowni, zarządzanie użytkownikami i rolami).
## Migracje (ręcznie, CLI)
```bash
cd api
npx prisma migrate dev --name <nazwa> # tworzy + aplikuje migrację
npx prisma migrate deploy # aplikuje w środowisku docelowym
```
## Backup
```bash
docker compose -f api/docker-compose.yml exec db pg_dump -U fitos fitos > backup.sql
```

4
admin/.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
node_modules
dist
.env
*.log

2
admin/.env.example Normal file
View File

@@ -0,0 +1,2 @@
# Build-time fallback (runtime config.js takes precedence)
VITE_API_URL=http://tisachi.ddns.net:9002

6
admin/.prettierrc.json Normal file
View File

@@ -0,0 +1,6 @@
{
"semi": true,
"singleQuote": true,
"printWidth": 100,
"trailingComma": "all"
}

11
admin/Dockerfile Normal file
View File

@@ -0,0 +1,11 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 9000

7
admin/docker-compose.yml Normal file
View File

@@ -0,0 +1,7 @@
services:
admin:
build: .
container_name: fitos-admin
ports:
- "9000:9000"
restart: unless-stopped

159
admin/e2e/admin.spec.ts Normal file
View File

@@ -0,0 +1,159 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { mockApi, TEST_GYM, TEST_GYM_2, TEST_USER } from './mock-api';
async function loginAsAdmin(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
}
test('kliknięcie w siłownię otwiera podstronę z detalami', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
await expect(page.getByRole('heading', { name: 'Fit Factory' })).toBeVisible();
// menu kontekstowe podstrony detalu nie dziedziczy akcji ze strony listy (brak ikony ➕)
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
});
test('dodawanie już dodanego sprzętu zwiększa jego ilość', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
await expect(page.getByText('Dywan ×3')).toBeVisible();
// select pokazuje cały katalog — ponowne dodanie zwiększa ilość
await page.getByLabel('Dodaj urządzenie').selectOption('eq-2');
await page.getByRole('button', { name: 'Dodaj', exact: true }).click();
await expect(page.getByText('Dywan ×4')).toBeVisible();
});
test('kliknięcie w użytkownika otwiera podstronę z detalami', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await expect(page).toHaveURL(/\/users\/user-1$/);
await expect(page.getByRole('heading', { name: 'Jan Kowalski' })).toBeVisible();
// w edycji konkretnego usera menu kontekstowe nie ma akcji „Nowy użytkownik” (brak ikony ➕)
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
// podsumowanie ról w nagłówku (user może mieć wiele ról naraz)
await expect(page.getByText('Ćwiczący: Fit Factory')).toBeVisible();
// ostatnia rola jest zablokowana — usunięcie członkostwa wymaga przycisku „Usuń”
await expect(page.getByRole('checkbox', { name: 'Ćwiczący w Fit Factory' })).toBeDisabled();
await expect(page.getByRole('checkbox', { name: 'Właściciel w Fit Factory' })).toBeEnabled();
});
test('odznaczenie checkboxa roli dodaje ją i wysyła PATCH z pełną listą', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await expect(page.getByRole('heading', { name: 'Jan Kowalski' })).toBeVisible();
const patchPromise = page.waitForRequest(
(req) =>
req.url().includes('/admin/users/user-1/memberships/gym-1') && req.method() === 'PATCH',
);
// click (not .check): the mock is stateless, so the checkbox reverts after refetch
await page.getByRole('checkbox', { name: 'Właściciel w Fit Factory' }).click();
const req = await patchPromise;
expect(req.postDataJSON()).toEqual({ roles: ['MEMBER', 'OWNER'] });
});
test('dodawanie członkostwa przez wyszukiwarkę siłowni wysyła POST do API', async ({ page }) => {
mockApi(page, {
gyms: { gyms: [TEST_GYM, TEST_GYM_2] },
users: { users: [TEST_USER] },
});
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await expect(page.getByRole('heading', { name: 'Jan Kowalski' })).toBeVisible();
const postPromise = page.waitForRequest(
(req) => req.url().includes('/admin/users/user-1/memberships') && req.method() === 'POST',
);
await page.getByRole('combobox', { name: 'Szukaj siłowni' }).click();
// siłownia, do której user już należy, jest ukryta na liście
await expect(page.getByRole('option', { name: /Fit Factory/ })).not.toBeVisible();
await page.getByRole('option', { name: /Mega Gym/ }).click();
await page.getByRole('button', { name: 'Dodaj członkostwo' }).click();
const req = await postPromise;
expect(req.postDataJSON()).toEqual({ gymId: 'gym-2', roles: ['MEMBER'] });
});
test('edycja profilu treningowego wysyła PATCH z nowymi polami', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] }, users: { users: [TEST_USER] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await page.getByRole('link', { name: 'Jan Kowalski' }).click();
await expect(page.getByRole('heading', { name: 'Jan Kowalski' })).toBeVisible();
// sekcja profilu treningowego w formularzu edycji
await expect(page.getByRole('heading', { name: 'Profil treningowy' })).toBeVisible();
const patchPromise = page.waitForRequest(
(req) =>
req.method() === 'PATCH' &&
req.url().includes('/admin/users/user-1') &&
!req.url().includes('/memberships'),
);
await page.getByRole('checkbox', { name: 'Pon: dostępny' }).check();
await page.getByRole('button', { name: 'Zapisz' }).click();
const req = await patchPromise;
expect(req.postDataJSON()).toMatchObject({
availability: [{ start: '18:00', end: '20:00' }, null, null, null, null, null, null],
});
});
test('przycisk w prawym górnym rogu prowadzi do formularza dodawania', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
// akcja „Nowa siłownia” w menu kontekstowym — na PC rozwinięta inline
await page.getByRole('button', { name: 'Nowa siłownia' }).click();
await expect(page).toHaveURL(/\/gyms\/new$/);
await expect(page.getByRole('heading', { name: 'Nowa siłownia' })).toBeVisible();
// na formularzu dodawania akcja w nagłówku znika (jest tylko na liście) — brak ikony ➕
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
// nawigacja po stronie (SPA) — pełny reload straciłby sesję w mocku
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await expect(page).toHaveURL(/\/users$/);
await expect(page.getByRole('button', { name: 'Nowy użytkownik' })).toBeVisible();
});
test('wyszukiwarka w menu kontekstowym filtruje listę użytkowników', async ({ page }) => {
const anna = {
...TEST_USER,
id: 'user-2',
email: 'anna@fitos.pl',
firstName: 'Anna',
lastName: 'Nowak',
memberships: [],
};
mockApi(page, { users: { users: [TEST_USER, anna] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Użytkownicy' }).click();
await expect(page.getByText('Jan Kowalski')).toBeVisible();
await expect(page.getByText('Anna Nowak')).toBeVisible();
// wyszukiwarka jest w menu kontekstowym (nagłówek) — na PC rozwinięta inline
await page.getByRole('searchbox', { name: 'Szukaj użytkownika' }).fill('anna');
await expect(page.getByText('Jan Kowalski')).not.toBeVisible();
await expect(page.getByText('Anna Nowak')).toBeVisible();
});
test('wyszukiwarka w menu kontekstowym filtruje listę siłowni', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM, TEST_GYM_2] } });
await loginAsAdmin(page);
// po logowaniu jesteśmy na /gyms
await expect(page.getByText('Fit Factory')).toBeVisible();
await expect(page.getByText('Mega Gym')).toBeVisible();
await page.getByRole('searchbox', { name: 'Szukaj siłowni' }).fill('kraków');
await expect(page.getByText('Fit Factory')).not.toBeVisible();
await expect(page.getByText('Mega Gym')).toBeVisible();
});

75
admin/e2e/auth.spec.ts Normal file
View File

@@ -0,0 +1,75 @@
import { test, expect } from './fixtures';
import { mockApi } from './mock-api';
test('przekierowuje niezalogowanego użytkownika na /login', async ({ page }) => {
mockApi(page);
await page.goto('/');
await expect(page).toHaveURL(/\/login$/);
await expect(page.getByRole('heading', { name: 'FitOS Admin' })).toBeVisible();
});
test('udane logowanie admina przekierowuje na /gyms', async ({ page }) => {
mockApi(page);
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
await expect(page.getByRole('heading', { name: 'Siłownie' })).toBeVisible();
});
test('zapamiętaj mnie zapisuje e-mail i podpowiada go po wylogowaniu', async ({ page }) => {
mockApi(page);
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('checkbox', { name: 'Zapamiętaj mnie' }).check();
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
await page.getByRole('button', { name: 'Wyloguj' }).click();
await expect(page).toHaveURL(/\/login$/);
await expect(page.locator('input[type="email"]')).toHaveValue('admin@fitos.pl');
});
test('bez zaznaczenia zapamiętaj mnie e-mail nie jest zapisywany', async ({ page }) => {
mockApi(page);
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
const stored = await page.evaluate(() => localStorage.getItem('fitos-remembered-email'));
expect(stored).toBeNull();
});
test('logowanie nie-admina zostaje odrzucone', async ({ page }) => {
mockApi(page, {
loginBody: {
user: {
id: 'user-1',
email: 'user@fitos.pl',
firstName: 'User',
lastName: null,
age: null,
heightCm: null,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-01-01T00:00:00.000Z',
},
accessToken: 'test-access-token',
},
});
await page.goto('/login');
await page.locator('input[type="email"]').fill('user@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/login$/);
await expect(page.getByText('Dostęp tylko dla administratorów')).toBeVisible();
});

View File

@@ -0,0 +1,95 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { mockApi } from './mock-api';
async function loginAsAdmin(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
}
test('katalog urządzeń renderuje listę maszyn z opisami i specyfikacją', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Urządzenia' }).click();
await expect(page).toHaveURL(/\/equipment$/);
// przycisk „Nowe urządzenie” jest w menu kontekstowym (nagłówek) — na PC rozwinięty inline
await expect(page.getByRole('button', { name: 'Nowe urządzenie' })).toHaveCount(1);
await expect(page.getByText('Sztanga z talerzami.')).toBeVisible();
// type-specific spec summary (BARBELL → max load)
await expect(page.getByText('do 100 kg')).toBeVisible();
await expect(page.getByText('Dywan do ćwiczeń.')).toBeVisible();
});
test('formularz urządzenia pokazuje pola specyfikacji zależne od rodzaju', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Urządzenia' }).click();
// przycisk w menu kontekstowym (nagłówek) — na PC rozwinięty inline, otwiera modal
await page.getByRole('button', { name: 'Nowe urządzenie' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
const kindSelect = dialog.locator('select');
const minKg = dialog.getByPlaceholder('np. 2.5');
const maxKg = dialog.getByPlaceholder('np. 25');
const maxLoadKg = dialog.getByPlaceholder('np. 100');
const maxSpeed = dialog.getByPlaceholder('np. 16');
// default kind (OTHER) — no spec fields
await expect(minKg).not.toBeVisible();
await expect(maxLoadKg).not.toBeVisible();
// DUMBBELL → load range fields
await kindSelect.selectOption('DUMBBELL');
await expect(minKg).toBeVisible();
await expect(maxKg).toBeVisible();
await expect(maxLoadKg).not.toBeVisible();
// BARBELL → max load field
await kindSelect.selectOption('BARBELL');
await expect(maxLoadKg).toBeVisible();
await expect(minKg).not.toBeVisible();
// CARDIO → speed/incline fields
await kindSelect.selectOption('CARDIO');
await expect(maxSpeed).toBeVisible();
await expect(maxLoadKg).not.toBeVisible();
});
test('dodawanie urządzenia wysyła POST do API', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Urządzenia' }).click();
const postPromise = page.waitForRequest(
(req) => req.url().includes('/admin/equipment') && req.method() === 'POST',
);
// przycisk w menu kontekstowym (nagłówek) — na PC rozwinięty inline, otwiera modal
await page.getByRole('button', { name: 'Nowe urządzenie' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await dialog.locator('input').first().fill('Kettlebell');
await dialog.getByRole('button', { name: 'Dodaj', exact: true }).click();
const req = await postPromise;
expect(req.postDataJSON()).toMatchObject({ name: 'Kettlebell' });
});
test('usuwanie urządzenia wysyła DELETE do API', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Urządzenia' }).click();
const deletePromise = page.waitForRequest(
(req) => req.url().includes('/admin/equipment/eq-1') && req.method() === 'DELETE',
);
await page.getByRole('button', { name: 'Usuń Sztanga' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await dialog.getByRole('button', { name: 'Usuń', exact: true }).click();
const req = await deletePromise;
expect(req.url()).toContain('/admin/equipment/eq-1');
});

View File

@@ -0,0 +1,55 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { mockApi } from './mock-api';
async function loginAsAdmin(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
}
test('lista rodzajów ćwiczeń renderuje ćwiczenia z mięśniami i maszynami', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Rodzaje ćwiczeń' }).click();
await expect(page).toHaveURL(/\/exercises$/);
await expect(page.getByText('Wyciskanie sztangi leżąc')).toBeVisible();
await expect(page.getByText('chest')).toBeVisible();
await expect(page.getByText('Sztanga')).toBeVisible();
});
test('przycisk „Nowe ćwiczenie” w menu kontekstowym otwiera modal', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Rodzaje ćwiczeń' }).click();
await expect(page).toHaveURL(/\/exercises$/);
// przycisk jest w nagłówku (menu kontekstowe) — na PC rozwinięty inline
await page.getByRole('button', { name: 'Nowe ćwiczenie' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
await expect(dialog.getByPlaceholder('np. Wyciskanie sztangi leżąc')).toBeVisible();
});
test('edycja ćwiczenia pozwala przypisać urządzenia i wysyła PATCH', async ({ page }) => {
mockApi(page);
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Rodzaje ćwiczeń' }).click();
const patchPromise = page.waitForRequest(
(req) => req.url().includes('/admin/exercises/ex-1') && req.method() === 'PATCH',
);
await page.getByRole('button', { name: 'Edytuj Wyciskanie sztangi leżąc' }).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
// Sztanga (eq-1) jest już przypisane, Dywan (eq-2) nie — oznaczamy Dywan
await dialog.getByRole('checkbox', { name: 'Dywan' }).check();
await dialog.getByRole('button', { name: 'Zapisz' }).click();
const req = await patchPromise;
expect(req.postDataJSON()).toMatchObject({
name: 'Wyciskanie sztangi leżąc',
primaryMuscle: 'chest',
equipmentIds: ['eq-1', 'eq-2'],
});
});

78
admin/e2e/fixtures.ts Normal file
View File

@@ -0,0 +1,78 @@
import { test as base, expect, type Page } from '@playwright/test';
export interface ConsoleIssue {
kind: 'console.error' | 'pageerror';
text: string;
}
interface GuardState {
issues: ConsoleIssue[];
allowed: RegExp[];
}
const guards = new WeakMap<Page, GuardState>();
/**
* Wzorce ignorowane domyślnie:
* - 401 z sieci: oczekiwany (refresh bez sesji przy starcie, login z błędnym hasłem).
* Pozostałe statusy (403/404/5xx) nadal powodują FAIL.
*/
const DEFAULT_ALLOWED: RegExp[] = [
/Failed to load resource: the server responded with a status of 401/,
];
/**
* Test z automatycznym guardem błędów konsoli.
*
* Każdy test importujący `test` z tego pliku FAILUJE, jeśli na stronie pojawi się:
* - console.error (błąd z konsoli przeglądarki)
* - nieobsłużony wyjątek (pageerror)
*
* Assert dzieje się automatycznie w afterEach — nie trzeba nic deklarować w teście.
* Do ignorowania znanych, akceptowalnych błędów użyj `allowConsoleError(page, regex)`.
*/
export const test = base;
test.beforeEach(({ page }) => {
const state: GuardState = { issues: [], allowed: [...DEFAULT_ALLOWED] };
guards.set(page, state);
page.on('console', (msg) => {
if (msg.type() !== 'error') return;
const text = msg.text();
if (state.allowed.some((re) => re.test(text))) return;
state.issues.push({ kind: 'console.error', text });
});
page.on('pageerror', (err) => {
const text = `${err.message}${err.stack ? `\n${err.stack}` : ''}`;
if (state.allowed.some((re) => re.test(err.message))) return;
state.issues.push({ kind: 'pageerror', text });
});
});
test.afterEach(({ page }, testInfo) => {
const state = guards.get(page);
if (!state || state.issues.length === 0) return;
testInfo.annotations.push({
type: 'console-errors',
description: state.issues.map((i) => `[${i.kind}] ${i.text}`).join('\n'),
});
expect(
state.issues,
`Wykryto błędy konsoli / nieobsłużone wyjątki:\n${state.issues.map((i) => ` [${i.kind}] ${i.text}`).join('\n')}`,
).toEqual([]);
});
/**
* Dozwól ignorowania błędów konsoli pasujących do wzorca.
* Wywołaj w teście, np. `allowConsoleError(page, /znane ostrzeżenie biblioteki/)`.
*/
export function allowConsoleError(page: Page, pattern: RegExp) {
const state = guards.get(page);
if (state) state.allowed.push(pattern);
}
export { expect };

View File

@@ -0,0 +1,46 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { mockApi, TEST_GYM } from './mock-api';
const TINY_PNG = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64',
);
async function loginAsAdmin(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
}
test('admin zarządza galerią zdjęć siłowni REAL (upload/okładka/usuwanie)', async ({ page }) => {
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Fit Factory' }).click();
await expect(page).toHaveURL(/\/gyms\/gym-1$/);
await expect(page.getByRole('heading', { name: 'Galeria zdjęć' })).toBeVisible();
// start: 2 zdjęcia, pierwsze jest okładką
const removeBtn = page.getByRole('button', { name: 'Usuń zdjęcie' });
await expect(removeBtn).toHaveCount(2);
await expect(page.getByText('Okładka', { exact: true })).toBeVisible();
// upload nowego zdjęcia
await page.locator('input[type="file"]').setInputFiles({
name: 'nowe.png',
mimeType: 'image/png',
buffer: TINY_PNG,
});
await expect(removeBtn).toHaveCount(3);
// ustaw drugie zdjęcie jako okładkę
await page.getByRole('button', { name: 'Ustaw jako okładkę' }).first().click();
await expect(page.getByText('Okładka', { exact: true })).toBeVisible();
// usuń zdjęcie (potwierdzenie w systemowym dialogu confirm)
page.on('dialog', (dialog) => dialog.accept());
await removeBtn.first().click();
await expect(removeBtn).toHaveCount(2);
});

73
admin/e2e/logs.spec.ts Normal file
View File

@@ -0,0 +1,73 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { mockApi, TEST_LOGS } from './mock-api';
async function loginAsAdmin(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
}
test('strona Logi wyświetla tabelę zdarzeń z API', async ({ page }) => {
mockApi(page, { logs: { logs: TEST_LOGS, total: TEST_LOGS.length } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Logi' }).click();
await expect(page).toHaveURL(/\/logs$/);
// wiersze tabeli: akcja (etykieta PL w komórce, nie w opcji selecta), aktor, nazwa obiektu
await expect(page.getByRole('cell', { name: 'Plan aktywowany' })).toBeVisible();
await expect(page.getByRole('cell', { name: 'Sesja zakończona' })).toBeVisible();
// oba wpisy należą do tego samego użytkownika — nazwa występuje w dwóch wierszach
await expect(page.getByText('Jan Kowalski').first()).toBeVisible();
// exact: nazwa planu występuje też w kolumnie „Szczegóły" (formatowany JSON)
await expect(page.getByText('Plan na masę', { exact: true })).toBeVisible();
// szczegóły jako naturalny tekst (tytuł i actorId są w innych kolumnach)
await expect(page.getByText('start: 2026-08-24')).toBeVisible();
// usunięcie pomiaru: etykieta PL + naturalne szczegóły z jednostką
await expect(page.getByRole('cell', { name: 'Waga usunięta' })).toBeVisible();
await expect(page.getByText('wartość: 82.5 kg')).toBeVisible();
});
test('filtr akcji wysyła parametr action do API', async ({ page }) => {
mockApi(page, { logs: { logs: TEST_LOGS, total: TEST_LOGS.length } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Logi' }).click();
await expect(page.getByRole('cell', { name: 'Plan aktywowany' })).toBeVisible();
const fetchPromise = page.waitForRequest(
(req) =>
req.method() === 'GET' &&
new URL(req.url()).searchParams.get('action') === 'session.completed',
);
// filtr akcji jest w menu kontekstowym — na PC rozwinięty inline
await page.getByRole('combobox', { name: 'Filtruj po akcji' }).selectOption('session.completed');
const req = await fetchPromise;
expect(new URL(req.url()).searchParams.get('limit')).toBe('100');
// mock filtruje po action — w tabeli zostaje tylko sesja
await expect(page.getByRole('cell', { name: 'Sesja zakończona' })).toBeVisible();
await expect(page.getByRole('cell', { name: 'Plan aktywowany' })).not.toBeVisible();
});
test('wyszukiwarka w menu kontekstowym filtruje logi po użytkowniku', async ({ page }) => {
const anna = {
...TEST_LOGS[0],
id: 'log-4',
action: 'weight.added',
entityType: 'user',
entityId: 'user-2',
details: { actorId: 'user-2', value: 70.5 },
createdAt: '2026-08-22T09:00:00.000Z',
actor: { id: 'user-2', email: 'anna@fitos.pl', firstName: 'Anna', lastName: 'Nowak' },
};
mockApi(page, { logs: { logs: [...TEST_LOGS, anna], total: TEST_LOGS.length + 1 } });
await loginAsAdmin(page);
await page.getByRole('link', { name: 'Logi' }).click();
// oba wpisy Jan Kowalskiego + wpis Anny
await expect(page.getByText('Jan Kowalski').first()).toBeVisible();
await expect(page.getByText('Anna Nowak')).toBeVisible();
// wyszukiwarka jest w menu kontekstowym (nagłówek) — na PC rozwinięta inline
await page.getByRole('searchbox', { name: 'Szukaj użytkownika' }).fill('anna');
await expect(page.getByText('Jan Kowalski')).not.toBeVisible();
await expect(page.getByText('Anna Nowak')).toBeVisible();
});

487
admin/e2e/mock-api.ts Normal file
View File

@@ -0,0 +1,487 @@
import type { Page } from '@playwright/test';
import type { ActivityLog, Gym, GymClaim, User } from '../src/api/types';
export const TEST_ADMIN = {
id: 'admin-test',
email: 'admin@fitos.pl',
firstName: 'Admin',
lastName: 'Test',
age: null,
heightCm: null,
phone: null,
isAdmin: true,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-01-01T00:00:00.000Z',
};
export const TEST_EQUIPMENT = [
{ id: 'eq-1', name: 'Sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: 'Sztanga z talerzami.' },
{ id: 'eq-2', name: 'Dywan', kind: 'OTHER', spec: null, description: 'Dywan do ćwiczeń.' },
];
export const TEST_GYM_PHOTOS = [
{ id: 'photo-1', url: '/gyms/gym-1/photos/photo-1', order: 0, createdAt: '2026-01-01T00:00:00.000Z' },
{ id: 'photo-2', url: '/gyms/gym-1/photos/photo-2', order: 1, createdAt: '2026-01-02T00:00:00.000Z' },
];
export const TEST_GYM: Gym = {
id: 'gym-1',
name: 'Fit Factory',
location: 'Warszawa, Mokotów',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 120,
kind: 'REAL',
isPrivate: false,
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: 3, equipment: TEST_EQUIPMENT[1] },
],
coverPhoto: '/gyms/gym-1/photos/photo-1',
photos: TEST_GYM_PHOTOS,
_count: { memberships: 12 },
};
export const TEST_GYM_2: Gym = {
id: 'gym-2',
name: 'Mega Gym',
location: 'Kraków',
availability: null,
capacity: null,
kind: 'REAL',
isPrivate: false,
equipment: [],
coverPhoto: null,
_count: { memberships: 4 },
};
/** Wniosek o weryfikację wirtualnej siłowni (PENDING, z dokumentem). */
export const TEST_CLAIM_VERIFICATION: GymClaim = {
id: 'claim-v1',
gymId: 'gym-v1',
type: 'verification',
gym: { id: 'gym-v1', name: 'Wirtualna Alfa', kind: 'VIRTUAL', isPrivate: true },
gymName: null,
gymLocation: null,
gymAvailability: null,
gymCapacity: null,
description: 'Prowadzę tę siłownię od 2020 roku.',
companyName: 'Alfa Sp. z o.o.',
nip: '1234567890',
phone: '+48 600 100 200',
email: 'alfa@fitos.pl',
address: 'ul. Morska 1, Gdynia',
status: 'PENDING',
rejectReason: null,
decidedAt: null,
createdAt: '2026-08-25T10:00:00.000Z',
user: { id: 'user-v1', firstName: 'Marek', lastName: 'Wirtualny', email: 'alfa@fitos.pl', phone: '+48 600 100 200' },
documentCount: 1,
documents: [{ id: 'doc-v1', originalName: 'akt-y.pdf', mimeType: 'application/pdf', sizeBytes: 1024, createdAt: '2026-08-25T10:00:00.000Z' }],
};
/** Wniosek o nową realną siłownię (PENDING). */
export const TEST_CLAIM_NEW: GymClaim = {
id: 'claim-n1',
gymId: null,
type: 'new',
gym: null,
gymName: 'Nowa Realna Siłownia',
gymLocation: 'ul. Długa 5, Warszawa',
gymAvailability: null,
gymCapacity: 40,
description: 'Nowa siłownia, otwieramy w październiku.',
companyName: null,
nip: null,
phone: '+48 700 300 400',
email: 'nowa@fitos.pl',
address: null,
status: 'PENDING',
rejectReason: null,
decidedAt: null,
createdAt: '2026-08-26T12:00:00.000Z',
user: { id: 'user-n1', firstName: 'Anna', lastName: 'Nowa', email: 'nowa@fitos.pl', phone: '+48 700 300 400' },
documentCount: 0,
documents: [],
};
export const TEST_USER: User = {
id: 'user-1',
email: 'jan@fitos.pl',
firstName: 'Jan',
lastName: 'Kowalski',
age: 30,
heightCm: 180,
phone: '+48 500 100 200',
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: ['chest'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: ['legs'],
createdAt: '2026-01-01T00:00:00.000Z',
memberships: [{ gymId: 'gym-1', roles: ['MEMBER'], gym: TEST_GYM }],
};
export const TEST_EXERCISES = [
{
id: 'ex-1',
slug: 'bench-press',
name: 'Wyciskanie sztangi leżąc',
primaryMuscle: 'chest',
secondaryMuscles: ['triceps'],
equipment: [TEST_EQUIPMENT[0]],
hasReps: true,
hasLoad: true,
hasRest: true,
hasSets: true,
hasRir: true,
hasDifficulty: true,
hasCardio: false,
hasTime: false,
hasSpeed: false,
description: 'Podstawowe ćwiczenie na klatkę.',
howTo: null,
commonMistakes: null,
difficulty: 4,
source: 'BUILTIN',
},
];
export const TEST_FOCUS_AREAS = [
{ id: 'fa-1', name: 'Klatka piersiowa', muscle: 'chest', description: 'Wyciskanie, rozpiętki.', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' },
{ id: 'fa-2', name: 'Nogi', muscle: 'legs', description: 'Przysiady, wykroki.', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' },
];
export const TEST_FOCUS_CHAIN = {
develop: [{ muscle: 'chest', name: 'Klatka piersiowa', exercises: [{ id: 'pz-2', name: 'Wyciskanie' }] }],
canDo: [],
difficult: [],
avoid: [{ muscle: 'legs', name: 'Nogi', exercises: [{ id: 'pz-1', name: 'Przysiady' }] }],
};
export const TEST_LOGS: 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@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
},
{
id: 'log-2',
action: 'session.completed',
entityType: 'session',
entityId: 'session-1',
details: null,
createdAt: '2026-08-21T18:30:00.000Z',
actor: { id: 'user-1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
},
{
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@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
},
];
export interface MockApiOptions {
/** Status odpowiedzi POST /auth/login (domyślnie 200). */
loginStatus?: number;
/** Ciało odpowiedzi POST /auth/login. */
loginBody?: unknown;
/** Ciało odpowiedzi GET /admin/gyms. */
gyms?: unknown;
/** Ciało odpowiedzi GET /admin/users. */
users?: unknown;
/** Ciało odpowiedzi GET /admin/logs. */
logs?: unknown;
/** Ciało odpowiedzi GET /admin/gyms/claims. */
claims?: unknown;
}
/**
* Mockuje API pod /api/v1. Niezamockowane endpointy zwracają 200 z {}.
* Kolejność rejestracji jest ważna: fallback musi być pierwszy
* (Playwright dopasowuje route'y w odwrotnej kolejności rejestracji).
*/
export function mockApi(page: Page, opts: MockApiOptions = {}) {
const {
loginStatus = 200,
loginBody = { user: TEST_ADMIN, accessToken: 'test-access-token' },
gyms = { gyms: [] },
users = { users: [] },
logs = { logs: TEST_LOGS, total: TEST_LOGS.length },
claims = { claims: [] as GymClaim[] },
} = opts;
// Stateful: claims persist across list/detail/approve/reject.
const claimsState: GymClaim[] = (claims as { claims: GymClaim[] }).claims.map((c) => ({ ...c }));
page.route('**/api/v1/**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({}) }),
);
page.route('**/api/v1/auth/refresh', (route) =>
route.fulfill({
status: 401,
contentType: 'application/json',
body: JSON.stringify({ error: { message: 'No session' } }),
}),
);
page.route('**/api/v1/auth/login', (route) =>
route.fulfill({
status: loginStatus,
contentType: 'application/json',
body: JSON.stringify(loginBody ?? { error: { message: 'Nieprawidłowy e-mail lub hasło' } }),
}),
);
page.route('**/api/v1/me', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ user: TEST_ADMIN, memberships: [] }),
}),
);
// Stateful: quantities of TEST_GYM equipment persist across refetches (PATCH/DELETE).
const gymEquipmentState = TEST_GYM.equipment.map((e) => ({ ...e }));
// Stateful: galeria zdjęć siłowni REAL (gym-1) — upload/delete/cover.
const gymPhotosState = TEST_GYM_PHOTOS.map((p) => ({ ...p }));
let photoSeq = TEST_GYM_PHOTOS.length;
const coverOf = (photos: typeof gymPhotosState) =>
photos.length ? `/gyms/gym-1/photos/${photos[0].id}` : null;
const gymDetailBody = () =>
JSON.stringify({
...TEST_GYM,
equipment: gymEquipmentState,
photos: [...gymPhotosState],
coverPhoto: coverOf(gymPhotosState),
});
// Detal siłowni (GET /admin/gyms/gym-1) — pełna galeria (lista ma tylko okładkę).
page.route('**/api/v1/admin/gyms/gym-1', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() }),
);
// POST /gyms/gym-1/photos — upload (multipart, pole `photos`).
page.route('**/api/v1/gyms/*/photos', (route) => {
const req = route.request();
if (req.method() !== 'POST') {
return route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() });
}
const raw = req.postData() || '';
const count = (raw.match(/name="photos"/g) || []).length;
for (let i = 0; i < count; i += 1) {
photoSeq += 1;
gymPhotosState.push({
id: `photo-${photoSeq}`,
url: `/gyms/gym-1/photos/photo-${photoSeq}`,
order: gymPhotosState.length,
createdAt: new Date().toISOString(),
});
}
return route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() });
});
// /gyms/gym-1/photos/:photoId — DELETE / PATCH .../cover / GET (serwowanie obrazu).
page.route('**/api/v1/gyms/*/photos/*', (route) => {
const req = route.request();
const url = req.url();
const photoId = url.match(/photos\/([^/?]+)$/)?.[1];
if (req.method() === 'DELETE') {
const idx = gymPhotosState.findIndex((p) => p.id === photoId);
if (idx >= 0) gymPhotosState.splice(idx, 1);
gymPhotosState.forEach((p, i) => (p.order = i));
return route.fulfill({ status: 204 });
}
if (req.method() === 'PATCH' && url.endsWith('/cover')) {
const idx = gymPhotosState.findIndex((p) => p.id === photoId);
if (idx >= 0) {
const [moved] = gymPhotosState.splice(idx, 1);
gymPhotosState.unshift(moved);
gymPhotosState.forEach((p, i) => (p.order = i));
}
return route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() });
}
return route.fulfill({
status: 200,
contentType: 'image/png',
body: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64',
),
});
});
page.route('**/api/v1/admin/gyms', (route) => {
const list = (gyms as { gyms?: Array<Record<string, unknown>> } | null)?.gyms;
const body = list
? {
...gyms,
gyms: list.map((g) => (g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g)),
}
: gyms;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(body),
});
});
page.route('**/api/v1/admin/gyms/*/equipment/*', (route) => {
const req = route.request();
const eqId = req.url().match(/equipment\/([^/]+)$/)?.[1];
if (req.method() === 'PATCH') {
const body = JSON.parse(req.postData() || '{}');
const link = gymEquipmentState.find((e) => e.equipmentId === eqId);
if (link && typeof body.quantity === 'number') link.quantity = body.quantity;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ gym: { ...TEST_GYM, equipment: gymEquipmentState } }),
});
}
if (req.method() === 'DELETE') {
const idx = gymEquipmentState.findIndex((e) => e.equipmentId === eqId);
if (idx >= 0) gymEquipmentState.splice(idx, 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 204 });
});
page.route('**/api/v1/admin/users', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(users) }),
);
// Stateful: honors the `action` query parameter (server-side filter).
// `*` at the end matches the optional query string.
page.route('**/api/v1/admin/logs*', (route) => {
const body = (logs ?? { logs: TEST_LOGS, total: TEST_LOGS.length }) as {
logs?: ActivityLog[];
total?: number;
};
const action = new URL(route.request().url()).searchParams.get('action');
const list = action ? body.logs?.filter((l) => l.action === action) : body.logs;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ logs: list ?? [], total: list?.length ?? 0 }),
});
});
page.route('**/api/v1/admin/focus-areas', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ focusAreas: TEST_FOCUS_AREAS }),
}),
);
page.route('**/api/v1/admin/equipment', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ equipment: TEST_EQUIPMENT }),
}),
);
page.route('**/api/v1/admin/exercises', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ exercises: TEST_EXERCISES }),
}),
);
page.route('**/api/v1/admin/users/*/focus-chain', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_FOCUS_CHAIN),
}),
);
page.route('**/api/v1/admin/users/*/memberships/*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ membership: {} }),
}),
);
// ---------- gym claims (verifications) ----------
// Kolejność rejestracji: list (catch-all) najpierw, potem coraz bardziej
// specyficzne route'y (Playwright dopasowuje w odwrotnej kolejności).
page.route('**/api/v1/admin/gyms/claims*', (route) => {
const status = new URL(route.request().url()).searchParams.get('status');
const list = status ? claimsState.filter((c) => c.status === status) : claimsState;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ claims: list }),
});
});
page.route('**/api/v1/admin/gyms/claims/*', (route) => {
const id = route.request().url().match(/claims\/([^/?]+)$/)?.[1];
const claim = claimsState.find((c) => c.id === id);
if (!claim) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Claim not found' } }),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ claim }),
});
});
page.route('**/api/v1/admin/gyms/claims/*/approve', (route) => {
const id = route.request().url().match(/claims\/([^/]+)\/approve$/)?.[1];
const claim = claimsState.find((c) => c.id === id);
if (claim && claim.status === 'PENDING') {
claim.status = 'APPROVED';
claim.decidedAt = new Date().toISOString();
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
});
page.route('**/api/v1/admin/gyms/claims/*/reject', (route) => {
const id = route.request().url().match(/claims\/([^/]+)\/reject$/)?.[1];
const body = JSON.parse(route.request().postData() || '{}');
const claim = claimsState.find((c) => c.id === id);
if (claim && claim.status === 'PENDING') {
claim.status = 'REJECTED';
claim.rejectReason = body.reason ?? null;
claim.decidedAt = new Date().toISOString();
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
});
page.route('**/api/v1/admin/gyms/claims/*/documents/*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/pdf',
body: 'mock-document-content',
}),
);
}

10
admin/e2e/smoke.spec.ts Normal file
View File

@@ -0,0 +1,10 @@
import { test, expect } from './fixtures';
import { mockApi } from './mock-api';
test('strona logowania renderuje się bez błędów konsoli', async ({ page }) => {
mockApi(page);
await page.goto('/login');
await expect(page.getByRole('heading', { name: 'FitOS Admin' })).toBeVisible();
await expect(page.locator('input[type="email"]')).toBeVisible();
await expect(page.locator('input[type="password"]')).toBeVisible();
});

View File

@@ -0,0 +1,97 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { mockApi, TEST_CLAIM_NEW, TEST_CLAIM_VERIFICATION } from './mock-api';
async function loginAsAdmin(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('admin@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page).toHaveURL(/\/gyms$/);
}
async function openVerifications(page: Page) {
await page.getByRole('link', { name: 'Weryfikacje' }).click();
await expect(page).toHaveURL(/\/verifications$/);
}
test('lista wniosków: obie typy z badge i statusem', async ({ page }) => {
mockApi(page, { claims: { claims: [TEST_CLAIM_VERIFICATION, TEST_CLAIM_NEW] } });
await loginAsAdmin(page);
await openVerifications(page);
// obie typy + badge typu
await expect(page.getByText('Wirtualna Alfa')).toBeVisible();
await expect(page.getByText('Weryfikacja', { exact: true })).toBeVisible();
await expect(page.getByText('Nowa Realna Siłownia')).toBeVisible();
await expect(page.getByText('Nowa siłownia', { exact: true })).toBeVisible();
// status PENDING (oba wnioski oczekujące)
await expect(page.getByText('Oczekuje', { exact: true }).first()).toBeVisible();
});
test('szczegóły wniosku o nową realną: dane siłowni + wnioskodawca', async ({ page }) => {
mockApi(page, { claims: { claims: [TEST_CLAIM_NEW] } });
await loginAsAdmin(page);
await openVerifications(page);
await page.getByRole('link', { name: 'Nowa Realna Siłownia' }).click();
await expect(page).toHaveURL(/\/verifications\/claim-n1$/);
// dane siłowni (typ nowa realna)
await expect(page.getByText('ul. Długa 5, Warszawa')).toBeVisible();
// wnioskodawca
await expect(page.getByText('Anna Nowa')).toBeVisible();
await expect(page.getByText('nowa@fitos.pl').first()).toBeVisible();
});
test('szczegóły wniosku o weryfikację: siłownia + dokument do pobrania', async ({ page }) => {
mockApi(page, { claims: { claims: [TEST_CLAIM_VERIFICATION] } });
await loginAsAdmin(page);
await openVerifications(page);
await page.getByRole('link', { name: 'Wirtualna Alfa' }).click();
await expect(page).toHaveURL(/\/verifications\/claim-v1$/);
// siłownia wirtualna + prywatna
await expect(page.getByText('Wirtualna', { exact: true })).toBeVisible();
await expect(page.getByText('Prywatna', { exact: true })).toBeVisible();
// adres nadpisujący lokalizację
await expect(page.getByText('ul. Morska 1, Gdynia')).toBeVisible();
// dokument do pobrania
await expect(page.getByText('akt-y.pdf')).toBeVisible();
await expect(page.getByRole('button', { name: 'Pobierz' })).toBeVisible();
});
test('zatwierdzenie wniosku przez ConfirmDialog', async ({ page }) => {
mockApi(page, { claims: { claims: [TEST_CLAIM_VERIFICATION] } });
await loginAsAdmin(page);
await openVerifications(page);
await page.getByRole('link', { name: 'Wirtualna Alfa' }).click();
await expect(page).toHaveURL(/\/verifications\/claim-v1$/);
const postPromise = page.waitForRequest(
(req) => req.url().includes('/admin/gyms/claims/claim-v1/approve') && req.method() === 'POST',
);
// akcja „Zatwierdź” otwiera ConfirmDialog
await page.getByRole('button', { name: 'Zatwierdź' }).click();
const dialog = page.getByRole('dialog');
await dialog.getByRole('button', { name: 'Zatwierdź' }).click();
await postPromise;
// po zatwierdzeniu wracamy na listę
await expect(page).toHaveURL(/\/verifications$/);
});
test('odrzucenie wniosku z powodem', async ({ page }) => {
mockApi(page, { claims: { claims: [TEST_CLAIM_NEW] } });
await loginAsAdmin(page);
await openVerifications(page);
await page.getByRole('link', { name: 'Nowa Realna Siłownia' }).click();
await expect(page).toHaveURL(/\/verifications\/claim-n1$/);
const postPromise = page.waitForRequest(
(req) => req.url().includes('/admin/gyms/claims/claim-n1/reject') && req.method() === 'POST',
);
await page.getByPlaceholder('np. Brak potwierdzenia adresu prowadzenia siłowni').fill('Brak adresu');
await page.getByRole('button', { name: 'Odrzuć' }).click();
const req = await postPromise;
expect(req.postDataJSON()).toEqual({ reason: 'Brak adresu' });
await expect(page).toHaveURL(/\/verifications$/);
});

39
admin/eslint.config.js Normal file
View File

@@ -0,0 +1,39 @@
import js from '@eslint/js';
import prettier from 'eslint-config-prettier';
import ts from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
const files = ['**/*.{js,ts,mjs,cjs}'];
export default [
{ ignores: ['dist/', 'node_modules/'] },
{
...js.configs.recommended,
files,
languageOptions: {
parser: tsParser,
globals: {
console: 'readonly',
window: 'readonly',
document: 'readonly',
localStorage: 'readonly',
fetch: 'readonly',
setTimeout: 'readonly',
clearTimeout: 'readonly',
URL: 'readonly',
Event: 'readonly',
},
},
plugins: {
'@typescript-eslint': ts,
},
rules: {
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
},
},
{
...prettier,
files,
},
];

15
admin/index.html Normal file
View File

@@ -0,0 +1,15 @@
<!doctype html>
<html lang="pl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#141210" />
<link rel="icon" href="/icons/icon-192.png" type="image/png" />
<title>FitOS Admin</title>
</head>
<body>
<div id="root"></div>
<script src="/config.js"></script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

15
admin/nginx.conf Normal file
View File

@@ -0,0 +1,15 @@
server {
listen 9000;
server_name _;
root /usr/share/nginx/html;
index index.html;
location ~ ^/(index\.html|config\.js|manifest\.json)$ {
add_header Cache-Control "no-cache";
try_files $uri /index.html;
}
location / {
try_files $uri /index.html;
}
}

6030
admin/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

57
admin/package.json Normal file
View File

@@ -0,0 +1,57 @@
{
"name": "fitos-admin",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint src",
"test": "vitest run",
"test:watch": "vitest",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:install": "playwright install chromium",
"format": "prettier --write src"
},
"dependencies": {
"@fontsource/manrope": "^5.3.0",
"@fontsource/space-grotesk": "^5.3.0",
"@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-separator": "^1.1.15",
"@tailwindcss/vite": "^4.3.3",
"@tanstack/react-query": "^5.62.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^1.33.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3",
"tw-animate-css": "^1.4.0",
"zustand": "^5.0.2"
},
"devDependencies": {
"@eslint/js": "^9.15.0",
"@playwright/test": "^1.62.1",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.6",
"@types/node": "^26.2.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@typescript-eslint/eslint-plugin": "^8.15.0",
"@typescript-eslint/parser": "^8.15.0",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.15.0",
"eslint-config-prettier": "^9.1.0",
"jsdom": "^25.0.1",
"prettier": "^3.3.3",
"typescript": "^5.6.0",
"vite": "^6.0.0",
"vitest": "^3.2.7"
}
}

View File

@@ -0,0 +1,22 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
timeout: 30_000,
expect: { timeout: 5_000 },
fullyParallel: true,
retries: process.env.CI ? 1 : 0,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: 'http://localhost:5174',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
webServer: {
command: 'npm run dev',
url: 'http://localhost:5174',
reuseExistingServer: !process.env.CI,
timeout: 60_000,
},
});

5
admin/public/config.js Normal file
View File

@@ -0,0 +1,5 @@
// Runtime configuration (no rebuild needed).
// Always use the DDNS domain so the app works from any device (and locally, via router hairpin).
window.__FITOS_CONFIG__ = {
apiUrl: 'http://tisachi.ddns.net:9002',
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

50
admin/src/App.tsx Normal file
View File

@@ -0,0 +1,50 @@
import { useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from './store/auth';
import Layout from './components/Layout';
import Login from './pages/Login';
import GymsList from './pages/GymsList';
import GymForm from './pages/GymForm';
import GymDetail from './pages/GymDetail';
import UsersList from './pages/UsersList';
import UserForm from './pages/UserForm';
import UserDetail from './pages/UserDetail';
import FocusAreas from './pages/FocusAreas';
import Exercises from './pages/Exercises';
import EquipmentCatalog from './pages/Equipment';
import Logs from './pages/Logs';
import VerificationsList, { VerificationDetail } from './pages/Verifications';
export default function App() {
const { user, ready, init } = useAuth();
useEffect(() => {
void init();
}, [init]);
if (!ready) {
return <div className="min-h-screen flex items-center justify-center text-dim">Ładowanie…</div>;
}
return (
<Routes>
<Route path="/login" element={user ? <Navigate to="/" replace /> : <Login />} />
<Route element={user ? <Layout /> : <Navigate to="/login" replace />}>
<Route path="/" element={<Navigate to="/gyms" replace />} />
<Route path="/gyms" element={<GymsList />} />
<Route path="/gyms/new" element={<GymForm />} />
<Route path="/gyms/:id" element={<GymDetail />} />
<Route path="/users" element={<UsersList />} />
<Route path="/users/new" element={<UserForm />} />
<Route path="/users/:id" element={<UserDetail />} />
<Route path="/focus-areas" element={<FocusAreas />} />
<Route path="/exercises" element={<Exercises />} />
<Route path="/equipment" element={<EquipmentCatalog />} />
<Route path="/verifications" element={<VerificationsList />} />
<Route path="/verifications/:id" element={<VerificationDetail />} />
<Route path="/logs" element={<Logs />} />
</Route>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
);
}

83
admin/src/api/client.ts Normal file
View File

@@ -0,0 +1,83 @@
import { API_BASE } from '../config';
import type { ApiErrorBody } from './types';
export class ApiError extends Error {
constructor(
public status: number,
public body: ApiErrorBody | null,
) {
super(body?.error?.message || `HTTP ${status}`);
}
}
let accessToken: string | null = localStorage.getItem('fitos_admin_access');
let refreshing: Promise<boolean> | null = null;
export function setAccessToken(token: string | null) {
accessToken = token;
if (token) localStorage.setItem('fitos_admin_access', token);
else localStorage.removeItem('fitos_admin_access');
}
export function getAccessToken() {
return accessToken;
}
async function tryRefresh(): Promise<boolean> {
if (!refreshing) {
refreshing = fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
credentials: 'include',
})
.then(async (res) => {
if (!res.ok) return false;
const data = await res.json();
setAccessToken(data.accessToken);
return true;
})
.catch(() => false)
.finally(() => {
setTimeout(() => (refreshing = null), 0);
});
}
return refreshing;
}
export async function api<T>(path: string, opts: { method?: string; body?: unknown } = {}): Promise<T> {
const doFetch = () =>
fetch(`${API_BASE}${path}`, {
method: opts.method || 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
let res = await doFetch();
if (res.status === 401 && path !== '/auth/refresh' && path !== '/auth/login' && path !== '/auth/register') {
const ok = await tryRefresh();
if (ok) res = await doFetch();
else {
setAccessToken(null);
window.dispatchEvent(new Event('fitos:logout'));
}
}
const text = await res.text();
let json: unknown = null;
if (text) {
try {
json = JSON.parse(text);
} catch {
// ciało nie-JSON (np. rate limiter, proxy) — traktujemy jako nieprzezroczysty błąd
}
}
if (!res.ok) {
const body = (json ?? (text ? { error: { code: `HTTP_${res.status}`, message: text } } : null)) as ApiErrorBody | null;
throw new ApiError(res.status, body);
}
return json as T;
}

216
admin/src/api/types.ts Normal file
View File

@@ -0,0 +1,216 @@
export type GymRole = 'OWNER' | 'TRAINER' | 'MEMBER';
export interface DayAvailability {
start: string;
end: string;
}
export type Availability = Array<DayAvailability | null>;
export type SocialMediaPlatform = 'INSTAGRAM' | 'TIKTOK' | 'YOUTUBE' | 'FACEBOOK' | 'X' | 'OTHER';
export interface SocialMediaEntry {
platform: SocialMediaPlatform;
url: string;
label?: string;
}
export interface User {
id: string;
email: string;
firstName: string | null;
lastName: string | null;
nickname: string | null;
socialMedia: SocialMediaEntry[] | null;
age: number | null;
heightCm: number | null;
phone: string | null;
isAdmin: boolean;
availability: Availability | null;
priorities: string | null;
exclusions: string | null;
developMuscles: string[];
canDoMuscles: string[];
difficultMuscles: string[];
avoidMuscles: string[];
createdAt: string;
memberships?: { gymId: string; roles: GymRole[]; gym: Gym }[];
}
export interface FocusArea {
id: string;
name: string;
muscle: string;
description: string | null;
setsMin: number | null;
setsMax: number | null;
createdAt: string;
updatedAt: string;
}
export interface FocusChainEntry {
muscle: string;
name: string;
exercises: { id: string; name: string }[];
}
export interface FocusChain {
develop: FocusChainEntry[];
canDo: FocusChainEntry[];
difficult: FocusChainEntry[];
avoid: FocusChainEntry[];
}
export type EquipmentKind =
| 'DUMBBELL'
| 'KETTLEBELL'
| 'BARBELL'
| 'CABLE'
| 'MACHINE'
| 'BENCH'
| 'CARDIO'
| 'BODYWEIGHT'
| 'OTHER';
/** Type-specific spec payload: DUMBBELL/KETTLEBELL/CABLE/MACHINE → { minKg, maxKg }, BARBELL/BENCH → { maxLoadKg }, CARDIO → { maxSpeedKmh?, maxInclinePct? }. */
export interface EquipmentSpec {
minKg?: number;
maxKg?: number;
maxLoadKg?: number;
maxSpeedKmh?: number;
maxInclinePct?: number;
}
export interface Equipment {
id: string;
name: string;
kind: EquipmentKind;
spec: EquipmentSpec | null;
description: string | null;
createdAt: string;
updatedAt: string;
}
/** A gym's equipment instance: how many units of a catalog item the gym has. */
export interface GymEquipment {
id: string;
gymId: string;
equipmentId: string;
quantity: number;
equipment: Equipment;
}
export interface Exercise {
id: string;
slug: string;
name: string;
primaryMuscle: string;
secondaryMuscles: string[];
equipment: Equipment[];
hasReps: boolean;
hasLoad: boolean;
hasRest: boolean;
hasSets: boolean;
hasRir: boolean;
hasDifficulty: boolean;
hasCardio: boolean;
hasTime: boolean;
hasSpeed: boolean;
description: string | null;
howTo: string | null;
commonMistakes: string | null;
difficulty: number;
source: string;
}
export type GymKind = 'VIRTUAL' | 'REAL';
export interface GymPhoto {
id: string;
url: string;
order: number;
createdAt: string;
}
export interface Gym {
id: string;
name: string;
location: string | null;
availability: Availability | null;
capacity: number | null;
kind: GymKind;
isPrivate: boolean;
equipment: GymEquipment[];
coverPhoto: string | null;
photos?: GymPhoto[];
_count?: { memberships: number };
}
export type ClaimStatus = 'PENDING' | 'APPROVED' | 'REJECTED';
export interface GymClaimDocument {
id: string;
originalName: string;
mimeType: string;
sizeBytes: number;
createdAt: string;
}
/** Wniosek o siłownię (admin): `gymId` null = wniosek o NOWĄ realną (dane w `gymName`/`gymLocation`). */
export interface GymClaim {
id: string;
gymId: string | null;
type: 'verification' | 'new';
gym: { id: string; name: string; kind: GymKind; isPrivate: boolean } | null;
gymName: string | null;
gymLocation: string | null;
gymAvailability: Availability | null;
gymCapacity: number | null;
description: string;
companyName: string | null;
nip: string | null;
phone: string | null;
email: string | null;
address: string | null;
status: ClaimStatus;
rejectReason: string | null;
decidedAt: string | null;
createdAt: string;
user: { id: string; firstName: string | null; lastName: string | null; email: string; phone?: string | null };
documentCount?: number;
documents: GymClaimDocument[];
}
export interface GymException {
id: string;
gymId: string;
date: string;
availability: DayAvailability | null;
createdAt: string;
}
export interface ActivityLogActor {
id: string;
email: string;
firstName: string | null;
lastName: string | null;
}
export interface ActivityLog {
id: string;
action: string;
entityType: string;
entityId: string | null;
details: Record<string, unknown> | null;
createdAt: string;
actor: ActivityLogActor;
}
export interface ActivityLogPage {
logs: ActivityLog[];
total: number;
}
export interface ApiErrorBody {
error: { code: string; message: string; details?: unknown };
}

View File

@@ -0,0 +1,70 @@
import { DAY_NAMES, TIME_SLOTS } from '../lib/availability';
import { Select } from './ui';
import type { Availability, DayAvailability } from '../api/types';
const DEFAULT_START = '18:00';
const DEFAULT_END = '20:00';
export function AvailabilityEditor({
value,
onChange,
}: {
value: Availability;
onChange: (value: Availability) => void;
}) {
const setDay = (i: number, day: DayAvailability | null) => {
const next = [...value];
next[i] = day;
onChange(next);
};
return (
<div className="space-y-2">
{DAY_NAMES.map((name, i) => {
const day = value[i];
const enabled = day != null;
const start = day?.start ?? DEFAULT_START;
const end = day?.end ?? DEFAULT_END;
return (
<div key={name} className="flex items-center gap-2">
<span className="w-12 shrink-0 text-dim text-[0.875rem]">{name}</span>
<input
type="checkbox"
aria-label={`${name}: dostępny`}
checked={enabled}
onChange={(e) => setDay(i, e.target.checked ? { start, end } : null)}
className="size-4 accent-[var(--accent)]"
/>
<Select
aria-label={`${name}: od`}
value={start}
disabled={!enabled}
onChange={(e) => setDay(i, { start: e.target.value, end })}
className="flex-1"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
<span className="text-dim">–</span>
<Select
aria-label={`${name}: do`}
value={end}
disabled={!enabled}
onChange={(e) => setDay(i, { start, end: e.target.value })}
className="flex-1"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,46 @@
import { cn } from '../lib/utils';
const VARIANTS = [
'bg-[linear-gradient(150deg,#e0704f,#a63c22)]',
'bg-[linear-gradient(150deg,#c9a24d,#8a651f)]',
'bg-[linear-gradient(150deg,#5f93b8,#37617f)]',
'bg-[linear-gradient(150deg,#7fa06a,#4c6a3a)]',
];
function hash(s: string): number {
let h = 0;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
return Math.abs(h);
}
/** Awatar z inicjałami (4 gradientowe warianty dobierane stabilnie po nazwie). */
export function Avatar({
name,
size = 32,
className = '',
}: {
name: string;
size?: number;
className?: string;
}) {
const initials = name
.trim()
.split(/\s+/)
.slice(0, 2)
.map((p) => p[0]?.toUpperCase() ?? '')
.join('');
return (
<span
aria-hidden="true"
className={cn(
'grid flex-none place-items-center rounded-full font-extrabold tracking-[0.02em] text-white',
'shadow-[inset_0_1px_0_rgb(255_255_255/0.25),0_1px_4px_rgb(0_0_0/0.25)]',
VARIANTS[hash(name || '?') % VARIANTS.length],
className,
)}
style={{ width: size, height: size, fontSize: size * 0.375 }}
>
{initials || '?'}
</span>
);
}

View File

@@ -0,0 +1,26 @@
import { cn } from '../lib/utils';
/** Geometryczny znak marki (sztanga-monogram) w koralowym gradiencie. */
export function Brandmark({ size = 30, className = '' }: { size?: number; className?: string }) {
return (
<span
aria-hidden="true"
className={cn(
'grid flex-none place-items-center rounded-[8px] bg-(image:--mark-grad) text-accent-ink shadow-(--mark-shadow)',
className,
)}
style={{ width: size, height: size }}
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2.4}
strokeLinecap="round"
style={{ width: size * 0.57, height: size * 0.57 }}
>
<path d="M6.5 6.5v11M17.5 6.5v11M3 9.5v5M21 9.5v5M6.5 12h11" />
</svg>
</span>
);
}

View File

@@ -0,0 +1,186 @@
import { useState } from 'react';
import { NavLink, Outlet, useNavigate } from 'react-router-dom';
import {
Building2,
Dumbbell,
LogOut,
ScrollText,
ShieldCheck,
Target,
Users,
Wrench,
X,
type LucideIcon,
} from 'lucide-react';
import { useAuth } from '../store/auth';
import { Button, ThemeToggle } from './ui';
import { Topbar } from '../topbar';
import { Brandmark } from './Brandmark';
import { Avatar } from './Avatar';
import { cn } from '../lib/utils';
interface NavItem {
to: string;
label: string;
icon: LucideIcon;
end: boolean;
}
interface NavSection {
label: string;
items: NavItem[];
}
const SECTIONS: NavSection[] = [
{
label: 'Zarządzanie',
items: [
{ to: '/gyms', label: 'Siłownie', icon: Building2, end: false },
{ to: '/verifications', label: 'Weryfikacje', icon: ShieldCheck, end: false },
{ to: '/users', label: 'Użytkownicy', icon: Users, end: false },
],
},
{
label: 'Słowniki',
items: [
{ to: '/focus-areas', label: 'Obszary treningowe', icon: Target, end: false },
{ to: '/exercises', label: 'Rodzaje ćwiczeń', icon: Dumbbell, end: false },
{ to: '/equipment', label: 'Urządzenia', icon: Wrench, end: false },
],
},
{
label: 'System',
items: [{ to: '/logs', label: 'Logi', icon: ScrollText, end: true }],
},
];
/* Wiersze nawigacji wg Ember: aktywny = tint akcentu + pionowy pasek przy krawędzi. */
function NavLinks({ items, onNavigate }: { items: NavItem[]; onNavigate?: () => void }) {
return (
<nav className="flex flex-col gap-0.5 px-3" aria-label="Nawigacja główna">
{items.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.end}
onClick={onNavigate}
className={({ isActive }) =>
cn(
'relative flex h-[38px] items-center gap-2.5 rounded-[10px] px-3 text-[13.5px] font-semibold transition-colors duration-150',
isActive ? 'bg-accent/11 text-accent-text' : 'text-dim hover:bg-line/30 hover:text-ink',
)
}
>
{({ isActive }) => (
<>
{isActive && (
<span
aria-hidden="true"
className="absolute -left-3 bottom-[9px] top-[9px] w-[3px] rounded-full bg-(image:--nav-bar-grad)"
/>
)}
<item.icon className="h-[17px] w-[17px] shrink-0" strokeWidth={1.9} />
<span className="min-w-0 truncate">{item.label}</span>
</>
)}
</NavLink>
))}
</nav>
);
}
function NavSections({ onNavigate }: { onNavigate?: () => void }) {
return (
<div className="flex flex-col gap-4">
{SECTIONS.map((section) => (
<div key={section.label}>
<div className="mb-1 px-6 text-[10.5px] font-bold uppercase tracking-[0.13em] text-dim/80">
{section.label}
</div>
<NavLinks items={section.items} onNavigate={onNavigate} />
</div>
))}
</div>
);
}
export default function Layout() {
const { user, logout } = useAuth();
const navigate = useNavigate();
const [drawerOpen, setDrawerOpen] = useState(false);
const fullName = user?.email ?? 'Admin';
const doLogout = async () => {
await logout();
navigate('/login');
};
const footer = (
<div className="mt-auto border-t border-line px-4 pb-4 pt-3">
<div className="mb-3 flex items-center gap-2.5">
<Avatar name={fullName} size={32} />
<div className="min-w-0">
<div className="truncate text-[13px] font-bold">{user?.email}</div>
<div className="text-[11.5px] text-dim">Administrator</div>
</div>
</div>
<div className="flex items-center gap-2">
<ThemeToggle />
<Button variant="secondary" size="sm" className="flex-1" onClick={doLogout}>
<LogOut className="w-4 h-4" />
Wyloguj
</Button>
</div>
</div>
);
return (
<div className="min-h-screen md:flex">
{/* Mobile drawer (telefon): ten sam zestaw pozycji co sidebar */}
{drawerOpen && (
<div className="fixed inset-0 z-50 md:hidden">
<div
className="absolute inset-0 animate-in fade-in-0 bg-black/60 duration-150"
onClick={() => setDrawerOpen(false)}
/>
<aside className="absolute left-0 top-0 flex h-full w-72 animate-in slide-in-from-left flex-col border-r border-line bg-card duration-200">
<div className="flex items-center justify-between px-4 py-4">
<div className="flex items-center gap-2.5">
<Brandmark size={26} />
<span className="font-display text-[1.05rem] font-bold tracking-[-0.02em]">FitOS Admin</span>
</div>
<button
type="button"
onClick={() => setDrawerOpen(false)}
aria-label="Zamknij menu"
className="-m-2 cursor-pointer p-2 text-dim hover:text-ink"
>
<X className="h-5 w-5" />
</button>
</div>
<NavSections onNavigate={() => setDrawerOpen(false)} />
{footer}
</aside>
</div>
)}
{/* Desktop/tablet sidebar z sekcjami */}
<aside className="hidden h-screen flex-col border-r border-line bg-card md:sticky md:top-0 md:flex md:w-64">
<div className="flex items-center gap-2.5 px-4 py-4">
<Brandmark size={26} />
<span className="font-display text-[1.05rem] font-bold tracking-[-0.02em]">FitOS Admin</span>
</div>
<NavSections />
{footer}
</aside>
<main className="min-w-0 flex-1">
<Topbar onMenuOpen={() => setDrawerOpen(true)} />
<div className="mx-auto max-w-5xl px-4 pb-24 pt-6 md:px-8 md:pb-10 md:pt-8">
<Outlet />
</div>
</main>
</div>
);
}

452
admin/src/components/ui.tsx Normal file
View File

@@ -0,0 +1,452 @@
import type {
ButtonHTMLAttributes,
InputHTMLAttributes,
ReactNode,
SelectHTMLAttributes,
TextareaHTMLAttributes,
} from 'react';
import { Link } from 'react-router-dom';
import { ArrowLeft, Moon, Sun, X } from 'lucide-react';
import { cva } from 'class-variance-authority';
import { useTheme } from '../store/theme';
import { cn } from '../lib/utils';
import { Button as UIButton, buttonVariants } from './ui/button';
import { Card as UICard } from './ui/card';
import { Badge as UIBadge } from './ui/badge';
import { Input as UIInput } from './ui/input';
import { Textarea as UITextarea } from './ui/textarea';
import { Label as UILabel } from './ui/label';
import { Field as UIField } from './ui/field';
import { Skeleton as UISkeleton } from './ui/skeleton';
import { Progress as UIProgress } from './ui/progress';
import { ErrorText as UIErrorText, SuccessText as UISuccessText } from './ui/alert';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from './ui/dialog';
/* Button */
export type ButtonVariant = 'primary' | 'secondary' | 'danger' | 'ghost';
export type ButtonSize = 'md' | 'sm';
export function Button({
variant,
size,
className,
...props
}: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: ButtonVariant; size?: ButtonSize }) {
return <UIButton variant={variant} size={size} className={className} {...props} />;
}
/* Card */
export function Card({ className, children }: { className?: string; children: ReactNode }) {
return <UICard className={className}>{children}</UICard>;
}
/* Badge */
export type BadgeColor = 'green' | 'gray' | 'red' | 'yellow' | 'blue';
export function Badge({
color,
className,
children,
}: {
color?: BadgeColor;
className?: string;
children: ReactNode;
}) {
return <UIBadge color={color} className={className}>{children}</UIBadge>;
}
/* Form fields */
export type FieldSize = 'md' | 'sm';
const FIELD_BASE =
'w-full bg-input border border-line rounded-[10px] text-ink font-[inherit] shadow-(--inset-shadow) transition-shadow duration-150 focus:outline-none focus:border-accent-text focus:ring-[3px] focus:ring-accent/18 disabled:cursor-not-allowed disabled:opacity-50';
const FIELD_SIZES: Record<FieldSize, string> = {
md: 'h-10 px-3 text-[0.95rem]',
// matches the height of <Button size="sm"> (header / context menu)
sm: 'h-8 px-3 text-[0.875rem]',
};
export function Input({
size = 'md',
className,
...props
}: Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> & { size?: FieldSize }) {
return <UIInput size={size} className={className} {...props} />;
}
const selectVariants = cva(FIELD_BASE, {
variants: { size: FIELD_SIZES },
defaultVariants: { size: 'md' },
});
export function Select({
size = 'md',
className,
children,
...props
}: Omit<SelectHTMLAttributes<HTMLSelectElement>, 'size'> & { size?: FieldSize }) {
return (
<select data-slot="select" className={cn(selectVariants({ size }), className)} {...props}>
{children}
</select>
);
}
export function Textarea({
size = 'md',
className,
...props
}: TextareaHTMLAttributes<HTMLTextAreaElement> & { size?: FieldSize }) {
return <UITextarea size={size} className={className} {...props} />;
}
export function Label({ children, className }: { children: ReactNode; className?: string }) {
return <UILabel className={className}>{children}</UILabel>;
}
export function Field({
label,
children,
className,
}: {
label: string;
children: ReactNode;
className?: string;
}) {
return (
<UIField label={label} className={className}>
{children}
</UIField>
);
}
/* Headings */
export function H1({ className = '', children }: { className?: string; children: ReactNode }) {
return <h1 className={`text-[1.45rem] sm:text-[1.6rem] font-bold tracking-[-0.02em] mb-4 ${className}`.trim()}>{children}</h1>;
}
export function H2({ className = '', children }: { className?: string; children: ReactNode }) {
return <h2 className={`text-[1.15rem] sm:text-[1.25rem] font-bold tracking-[-0.01em] mb-3 ${className}`.trim()}>{children}</h2>;
}
export function H3({ className = '', children }: { className?: string; children: ReactNode }) {
return <h3 className={`text-[1.05rem] font-semibold mb-2 ${className}`.trim()}>{children}</h3>;
}
/* Page header: title + optional badge, actions on the right (stacks on mobile) */
export function PageHeader({
title,
badge,
actions,
}: {
title: string;
badge?: ReactNode;
actions?: ReactNode;
}) {
return (
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
<div className="flex items-center gap-3 flex-wrap">
<H1 className="mb-0">{title}</H1>
{badge}
</div>
{actions}
</div>
);
}
/* Back button — ghost, small; `to` renders a Link, `onClick` a plain button */
export function BackButton({
to,
onClick,
children = 'Wstecz',
className = '',
}: {
to?: string;
onClick?: () => void;
children?: ReactNode;
className?: string;
}) {
const cls = cn(buttonVariants({ variant: 'ghost', size: 'sm' }), className);
if (to) {
return (
<Link to={to} className={cls}>
<ArrowLeft className="w-4 h-4" />
{children}
</Link>
);
}
return (
<button type="button" onClick={onClick} className={cls}>
<ArrowLeft className="w-4 h-4" />
{children}
</button>
);
}
/* Section header: H2 + muted description + optional actions (right) */
export function SectionHeader({
title,
description,
actions,
className = '',
}: {
title: ReactNode;
description?: ReactNode;
actions?: ReactNode;
className?: string;
}) {
return (
<div className={`flex flex-wrap items-start justify-between gap-3 mb-3 ${className}`.trim()}>
<div className="min-w-0">
<H2 className="mb-0.5">{title}</H2>
{description && <Muted className="text-[0.875rem]">{description}</Muted>}
</div>
{actions && <div className="flex items-center gap-2 shrink-0">{actions}</div>}
</div>
);
}
/* Meta item: small icon + muted text */
export function MetaItem({
icon: Icon,
children,
className = '',
}: {
icon: React.ComponentType<{ className?: string }>;
children: ReactNode;
className?: string;
}) {
return (
<span className={`inline-flex items-center gap-1.5 text-dim text-[0.875rem] ${className}`.trim()}>
<Icon className="w-4 h-4 shrink-0" />
<span className="min-w-0 truncate">{children}</span>
</span>
);
}
/* List row: płaski wiersz (tytuł + meta lewo, akcje prawo); w listach w karcie
rodzic używa `divide-y divide-line` (dłuższe) albo `space-y-1` (krótkie). */
export function ListRow({
title,
meta,
actions,
children,
className = '',
}: {
title: ReactNode;
meta?: ReactNode;
actions?: ReactNode;
children?: ReactNode;
className?: string;
}) {
return (
<div
data-slot="list-row"
className={`flex flex-wrap items-center justify-between gap-3 px-2 py-3 rounded-lg transition-colors hover:bg-line/20 ${className}`.trim()}
>
<div className="min-w-0 flex-1">
<div className="text-[0.95rem] font-semibold min-w-0 truncate">{title}</div>
{meta && <Muted className="text-[0.875rem]">{meta}</Muted>}
</div>
{actions && <div className="flex items-center gap-2 shrink-0">{actions}</div>}
{children}
</div>
);
}
/* Chip: small pill (+ optional remove button) */
export function Chip({
children,
onRemove,
removeLabel = 'Usuń',
className = '',
}: {
children: ReactNode;
onRemove?: () => void;
removeLabel?: string;
className?: string;
}) {
return (
<span
data-slot="chip"
className={`inline-flex items-center gap-1.5 bg-card border border-line rounded-full px-3 py-1 text-[0.8125rem] font-semibold text-dim ${className}`.trim()}
>
{children}
{onRemove && (
<button type="button" onClick={onRemove} aria-label={removeLabel} className="text-dim hover:text-danger cursor-pointer">
<X className="w-3.5 h-3.5" />
</button>
)}
</span>
);
}
/* Text helpers */
export function Muted({ className = '', children }: { className?: string; children: ReactNode }) {
return <span className={`text-dim ${className}`.trim()}>{children}</span>;
}
export function ErrorText({ children }: { children: ReactNode }) {
return <UIErrorText>{children}</UIErrorText>;
}
export function SuccessText({ children }: { children: ReactNode }) {
return <UISuccessText>{children}</UISuccessText>;
}
export function Loading({ children = 'Ładowanie…' }: { children?: ReactNode }) {
return <div className="text-dim">{children}</div>;
}
/* Skeleton */
export function Skeleton({ className = '' }: { className?: string }) {
return <UISkeleton className={className} />;
}
/* Empty state */
export function EmptyState({
icon: Icon,
title,
description,
action,
}: {
icon: React.ComponentType<{ className?: string }>;
title: string;
description?: string;
action?: ReactNode;
}) {
return (
<div className="flex flex-col items-center justify-center text-center py-10 px-4">
<div className="w-14 h-14 rounded-full bg-accent/10 border border-accent/25 text-accent-text flex items-center justify-center mb-4">
<Icon className="w-7 h-7" />
</div>
<H3 className="mb-1">{title}</H3>
{description && <p className="text-dim text-[0.9rem] max-w-sm">{description}</p>}
{action && <div className="mt-4">{action}</div>}
</div>
);
}
/* Progress bar */
export function ProgressBar({ percent, className = '' }: { percent: number; className?: string }) {
return <UIProgress percent={percent} className={className} />;
}
/* Tabs */
export function Tabs({
tabs,
active,
onChange,
}: {
tabs: { id: string; label: string }[];
active: string;
onChange: (id: string) => void;
}) {
return (
<div className="flex gap-1 p-1 bg-input rounded-[10px] border border-line overflow-x-auto">
{tabs.map((t) => (
<button
key={t.id}
type="button"
onClick={() => onChange(t.id)}
className={`px-3.5 py-2 rounded-lg text-[0.9rem] font-semibold whitespace-nowrap cursor-pointer transition-all duration-150 ${
active === t.id ? 'bg-card text-ink border border-line shadow-card' : 'border border-transparent text-dim hover:text-ink'
}`}
>
{t.label}
</button>
))}
</div>
);
}
/* Modal — Radix Dialog: focus trap, Esc, scroll-lock, aria; bottom-sheet na mobile */
export function Modal({
open,
onClose,
title,
children,
}: {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
}) {
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle asChild>
<h3 className="text-[1.05rem] font-semibold">{title}</h3>
</DialogTitle>
<DialogClose asChild>
<button aria-label="Zamknij" className="p-1.5 -m-1.5 text-dim hover:text-ink cursor-pointer">
<X className="w-5 h-5" />
</button>
</DialogClose>
</DialogHeader>
<DialogDescription asChild>
<span className="sr-only" />
</DialogDescription>
{children}
</DialogContent>
</Dialog>
);
}
/* Confirm dialog */
export function ConfirmDialog({
open,
onClose,
onConfirm,
title,
description,
confirmLabel = 'Potwierdź',
danger,
busy,
}: {
open: boolean;
onClose: () => void;
onConfirm: () => void;
title: string;
description: string;
confirmLabel?: string;
danger?: boolean;
busy?: boolean;
}) {
return (
<Modal open={open} onClose={onClose} title={title}>
<p className="text-dim text-[0.95rem]">{description}</p>
<div className="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3 mt-5">
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
Anuluj
</Button>
<Button variant={danger ? 'danger' : 'primary'} onClick={onConfirm} disabled={busy} className="w-full sm:w-auto">
{confirmLabel}
</Button>
</div>
</Modal>
);
}
/* Theme toggle */
export function ThemeToggle({ className = '' }: { className?: string }) {
const { theme, toggle } = useTheme();
return (
<button
onClick={toggle}
aria-label="Przełącz motyw"
title="Przełącz motyw"
className={`p-2.5 rounded-full bg-card border border-line text-dim shadow-card hover:text-ink hover:border-accent/45 cursor-pointer transition-all duration-150 ${className}`.trim()}
>
{theme === 'dark' ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
</button>
);
}

View File

@@ -0,0 +1,12 @@
import type { ReactNode } from 'react';
import { cn } from '../../lib/utils';
function ErrorText({ children, className }: { children: ReactNode; className?: string }) {
return <div data-slot="alert" className={cn('mt-2 text-[0.9rem] text-danger', className)}>{children}</div>;
}
function SuccessText({ children, className }: { children: ReactNode; className?: string }) {
return <div data-slot="alert" className={cn('mt-2 text-[0.9rem] text-accent-text', className)}>{children}</div>;
}
export { ErrorText, SuccessText };

View File

@@ -0,0 +1,31 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/utils';
const badgeVariants = cva(
'inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[0.75rem] font-bold whitespace-nowrap',
{
variants: {
color: {
green: 'bg-accent/14 text-accent-text',
gray: 'bg-dim/13 text-dim',
red: 'bg-danger/12 text-danger',
yellow: 'bg-warn/13 text-warn',
blue: 'bg-info/13 text-info',
},
},
defaultVariants: {
color: 'gray',
},
},
);
export interface BadgeProps
extends Omit<React.HTMLAttributes<HTMLSpanElement>, 'color'>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, color, ...props }: BadgeProps) {
return <span data-slot="badge" className={cn(badgeVariants({ color }), className)} {...props} />;
}
export { Badge, badgeVariants };

View File

@@ -0,0 +1,47 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/utils';
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 rounded-[10px] font-bold whitespace-nowrap cursor-pointer transition-all duration-150 disabled:cursor-not-allowed disabled:opacity-50 active:scale-[.985] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 focus-visible:ring-offset-2 focus-visible:ring-offset-bg',
{
variants: {
variant: {
primary: 'bg-(image:--btn-grad) text-accent-ink shadow-(--btn-shadow) hover:brightness-105',
secondary:
'bg-card/60 text-ink border border-line shadow-card hover:border-accent/55 hover:text-accent-text',
danger: 'bg-transparent text-danger border border-danger/45 hover:bg-danger/10',
ghost: 'bg-transparent text-dim hover:text-ink hover:bg-line/30',
},
size: {
md: 'h-10 px-[18px] text-[0.875rem]',
sm: 'h-8 px-3 text-[0.8125rem] rounded-lg',
},
},
defaultVariants: {
variant: 'primary',
size: 'md',
},
},
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
Omit<VariantProps<typeof buttonVariants>, 'size'> {
size?: 'md' | 'sm';
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, type = 'button', ...props }, ref) => (
<button
type={type}
data-slot="button"
className={cn(buttonVariants({ variant, size }), className)}
ref={ref}
{...props}
/>
),
);
Button.displayName = 'Button';
export { Button, buttonVariants };

View File

@@ -0,0 +1,16 @@
import * as React from 'react';
import { cn } from '../../lib/utils';
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
data-slot="card"
className={cn('bg-(image:--card-grad) border border-line rounded-lg shadow-card p-5 sm:p-6 mb-4', className)}
{...props}
/>
),
);
Card.displayName = 'Card';
export { Card };

View File

@@ -0,0 +1,101 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { cn } from '../../lib/utils';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 z-50 bg-black/60 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=open]:fade-in-0 duration-200',
className,
)}
ref={ref}
{...props}
/>
));
DialogOverlay.displayName = 'DialogOverlay';
/**
* Content: bottom-sheet na mobile (przylega do dołu, zaokrąglone góra),
* wyśrodkowany panel na desktopie. max-h 85vh ze scrollowaniem.
*/
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
ref={ref}
className={cn(
'fixed inset-x-0 bottom-0 z-50 max-h-[85vh] w-full overflow-y-auto rounded-t-2xl border border-line bg-card p-5 shadow-card',
'sm:bottom-auto sm:left-1/2 sm:right-auto sm:top-1/2 sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2 sm:rounded-2xl',
'duration-200 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:slide-in-from-bottom-2',
'data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',
className,
)}
{...props}
>
{children}
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = 'DialogContent';
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div data-slot="dialog-header" className={cn('mb-4 flex items-center justify-between gap-3', className)} {...props} />
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div data-slot="dialog-footer" className={cn('mt-5 flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-end', className)} {...props} />
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
data-slot="dialog-title"
ref={ref}
className={cn('text-[1.05rem] font-semibold', className)}
{...props}
/>
));
DialogTitle.displayName = 'DialogTitle';
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
data-slot="dialog-description"
ref={ref}
className={cn('text-dim text-[0.95rem]', className)}
{...props}
/>
));
DialogDescription.displayName = 'DialogDescription';
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
};

View File

@@ -0,0 +1,18 @@
import * as React from 'react';
import { Label } from './label';
import { cn } from '../../lib/utils';
interface FieldProps extends React.HTMLAttributes<HTMLDivElement> {
label: string;
}
function Field({ className, label, children, ...props }: FieldProps) {
return (
<div data-slot="field" className={cn('mb-3.5', className)} {...props}>
<Label>{label}</Label>
{children}
</div>
);
}
export { Field };

View File

@@ -0,0 +1,31 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/utils';
const inputVariants = cva(
'w-full bg-input border border-line rounded-[10px] text-ink font-[inherit] placeholder:text-dim/70 shadow-(--inset-shadow) transition-shadow duration-150 focus:outline-none focus:border-accent-text focus:ring-[3px] focus:ring-accent/18 disabled:cursor-not-allowed disabled:opacity-50',
{
variants: {
size: {
md: 'h-10 px-3 text-[0.95rem]',
sm: 'h-8 px-3 text-[0.875rem]',
},
},
defaultVariants: {
size: 'md',
},
},
);
export interface InputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'>,
VariantProps<typeof inputVariants> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, size, type, ...props }, ref) => (
<input type={type} data-slot="input" className={cn(inputVariants({ size }), className)} ref={ref} {...props} />
),
);
Input.displayName = 'Input';
export { Input, inputVariants };

View File

@@ -0,0 +1,16 @@
import * as React from 'react';
import { cn } from '../../lib/utils';
const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLLabelElement>>(
({ className, ...props }, ref) => (
<label
ref={ref}
data-slot="label"
className={cn('block mb-1.5 text-dim text-[11px] font-bold uppercase tracking-[0.1em]', className)}
{...props}
/>
),
);
Label.displayName = 'Label';
export { Label };

View File

@@ -0,0 +1,14 @@
import { cn } from '../../lib/utils';
function Progress({ percent, className }: { percent: number; className?: string }) {
return (
<div data-slot="progress" className={cn('h-2 overflow-hidden rounded-full bg-input', className)}>
<div
className="h-full rounded-full bg-(image:--progress-grad) transition-[width] duration-300"
style={{ width: `${Math.max(0, Math.min(100, percent))}%` }}
/>
</div>
);
}
export { Progress };

View File

@@ -0,0 +1,23 @@
import * as React from 'react';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from '../../lib/utils';
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => (
<SeparatorPrimitive.Root
ref={ref}
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-line data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px',
className,
)}
{...props}
/>
));
Separator.displayName = 'Separator';
export { Separator };

View File

@@ -0,0 +1,8 @@
import * as React from 'react';
import { cn } from '../../lib/utils';
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div data-slot="skeleton" className={cn('skeleton-shimmer rounded-lg', className)} {...props} />;
}
export { Skeleton };

View File

@@ -0,0 +1,31 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../lib/utils';
const textareaVariants = cva(
'w-full bg-input border border-line rounded-[10px] text-ink font-[inherit] placeholder:text-dim/70 shadow-(--inset-shadow) transition-shadow duration-150 focus:outline-none focus:border-accent-text focus:ring-[3px] focus:ring-accent/18 disabled:cursor-not-allowed disabled:opacity-50',
{
variants: {
size: {
md: 'px-3 py-2.5 text-[0.95rem]',
sm: 'px-3 py-1.5 text-[0.875rem]',
},
},
defaultVariants: {
size: 'md',
},
},
);
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement>,
VariantProps<typeof textareaVariants> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, size, ...props }, ref) => (
<textarea data-slot="textarea" className={cn(textareaVariants({ size }), className)} ref={ref} {...props} />
),
);
Textarea.displayName = 'Textarea';
export { Textarea, textareaVariants };

14
admin/src/config.ts Normal file
View File

@@ -0,0 +1,14 @@
/// <reference types="vite/client" />
declare global {
interface Window {
__FITOS_CONFIG__?: { apiUrl?: string };
}
}
export const API_URL: string =
window.__FITOS_CONFIG__?.apiUrl ||
(import.meta.env.VITE_API_URL as string | undefined) ||
window.location.origin;
export const API_BASE = `${API_URL}/api/v1`;

View File

@@ -0,0 +1,40 @@
import type { Availability, DayAvailability } from '../api/types.js';
export const DAY_NAMES = ['Pon', 'Wt', 'Śr', 'Czw', 'Pt', 'Sob', 'Niedz'] as const;
/** 30-minute slots from 05:00 to 23:00. */
export const TIME_SLOTS: string[] = (() => {
const slots: string[] = [];
for (let h = 5; h <= 23; h++) {
slots.push(`${String(h).padStart(2, '0')}:00`);
if (h < 23) slots.push(`${String(h).padStart(2, '0')}:30`);
}
return slots;
})();
export function emptyAvailability(): Availability {
return [null, null, null, null, null, null, null];
}
/** Coerce any stored value into a 7-element Availability (index 0=Mon ... 6=Sun). */
export function normalizeAvailability(value: unknown): Availability {
if (Array.isArray(value)) {
const arr: Availability = [];
for (let i = 0; i < 7; i++) {
const item = value[i];
arr.push(item && typeof item === 'object' ? (item as DayAvailability) : null);
}
return arr;
}
return emptyAvailability();
}
/** Human-readable summary, e.g. "Pon 18:00–20:00, Wt 18:00–20:00". Empty string if none. */
export function formatAvailability(value: unknown): string {
const arr = normalizeAvailability(value);
const parts: string[] = [];
arr.forEach((day, i) => {
if (day) parts.push(`${DAY_NAMES[i]} ${day.start}–${day.end}`);
});
return parts.join(', ');
}

View File

@@ -0,0 +1,45 @@
import type { Equipment, EquipmentKind, EquipmentSpec } from '../api/types';
export const EQUIPMENT_KIND_LABELS: Record<EquipmentKind, string> = {
DUMBBELL: 'Hantle',
KETTLEBELL: 'Kettlebell',
BARBELL: 'Sztanga',
CABLE: 'Wyciąg',
MACHINE: 'Maszyna',
BENCH: 'Ławka',
CARDIO: 'Cardio',
BODYWEIGHT: 'Masa ciała',
OTHER: 'Inne',
};
function fmtKg(value: number): string {
return Number.isInteger(value) ? String(value) : value.toFixed(1).replace(/\.0$/, '');
}
/**
* Human-readable summary of a type-specific spec payload:
* DUMBBELL/KETTLEBELL/CABLE/MACHINE → "2.5–25 kg"
* BARBELL/BENCH → "do 100 kg"
* CARDIO → "do 16 km/h" (+ "nachylenie do 15%")
* BODYWEIGHT/OTHER or no spec → null
*/
export function formatEquipmentSpec(spec: EquipmentSpec | null | undefined): string | null {
if (!spec) return null;
const parts: string[] = [];
if (spec.minKg != null || spec.maxKg != null) {
if (spec.minKg != null && spec.maxKg != null) parts.push(`${fmtKg(spec.minKg)}–${fmtKg(spec.maxKg)} kg`);
else if (spec.maxKg != null) parts.push(`do ${fmtKg(spec.maxKg)} kg`);
else parts.push(`od ${fmtKg(spec.minKg!)} kg`);
}
if (spec.maxLoadKg != null) parts.push(`do ${fmtKg(spec.maxLoadKg)} kg`);
if (spec.maxSpeedKmh != null) parts.push(`do ${fmtKg(spec.maxSpeedKmh)} km/h`);
if (spec.maxInclinePct != null) parts.push(`nachylenie do ${fmtKg(spec.maxInclinePct)}%`);
return parts.length ? parts.join(', ') : null;
}
/** Chip label for a gym equipment instance: "Hantle ×2 · 2.5–25 kg". */
export function formatGymEquipment(item: { quantity: number; equipment: Equipment }): string {
const spec = formatEquipmentSpec(item.equipment.spec);
const qty = item.quantity > 1 ? ` ×${item.quantity}` : '';
return spec ? `${item.equipment.name}${qty} · ${spec}` : `${item.equipment.name}${qty}`;
}

6
admin/src/lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

30
admin/src/main.tsx Normal file
View File

@@ -0,0 +1,30 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import '@fontsource/manrope/400.css';
import '@fontsource/manrope/500.css';
import '@fontsource/manrope/600.css';
import '@fontsource/manrope/700.css';
import '@fontsource/manrope/800.css';
import '@fontsource/space-grotesk/500.css';
import '@fontsource/space-grotesk/600.css';
import '@fontsource/space-grotesk/700.css';
import App from './App';
import './styles.css';
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: 1, refetchOnWindowFocus: false },
},
});
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<App />
</BrowserRouter>
</QueryClientProvider>
</React.StrictMode>,
);

View File

@@ -0,0 +1,366 @@
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Pencil, Plus, Trash2, Wrench } from 'lucide-react';
import { api } from '../api/client';
import type { Equipment, EquipmentKind } from '../api/types';
import { EQUIPMENT_KIND_LABELS, formatEquipmentSpec } from '../lib/equipment';
import { useTopbar } from '../topbar';
import { useListSearch } from '../store/list-search';
import {
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
Input,
Loading,
Modal,
Muted,
Select,
Textarea,
} from '../components/ui';
interface FormState {
name: string;
description: string;
kind: EquipmentKind;
minKg: string;
maxKg: string;
maxLoadKg: string;
maxSpeedKmh: string;
maxInclinePct: string;
}
const EMPTY: FormState = {
name: '',
description: '',
kind: 'OTHER',
minKg: '',
maxKg: '',
maxLoadKg: '',
maxSpeedKmh: '',
maxInclinePct: '',
};
/** Kinds with a { minKg, maxKg } load range spec. */
const LOAD_RANGE_KINDS: EquipmentKind[] = ['DUMBBELL', 'KETTLEBELL', 'CABLE', 'MACHINE'];
/** Kinds with a { maxLoadKg } spec. */
const MAX_LOAD_KINDS: EquipmentKind[] = ['BARBELL', 'BENCH'];
function toFormState(item: Equipment): FormState {
const spec = item.spec ?? {};
return {
name: item.name,
description: item.description ?? '',
kind: item.kind,
minKg: spec.minKg != null ? String(spec.minKg) : '',
maxKg: spec.maxKg != null ? String(spec.maxKg) : '',
maxLoadKg: spec.maxLoadKg != null ? String(spec.maxLoadKg) : '',
maxSpeedKmh: spec.maxSpeedKmh != null ? String(spec.maxSpeedKmh) : '',
maxInclinePct: spec.maxInclinePct != null ? String(spec.maxInclinePct) : '',
};
}
function parseNum(value: string): number | undefined {
if (value.trim() === '') return undefined;
const n = Number(value);
return Number.isFinite(n) ? n : undefined;
}
export default function EquipmentCatalog() {
const qc = useQueryClient();
const { data, isLoading, error } = useQuery({
queryKey: ['equipment'],
queryFn: () => api<{ equipment: Equipment[] }>('/admin/equipment'),
});
const items = data?.equipment ?? [];
const query = useListSearch((s) => s.queries.equipment);
const setQuery = useListSearch((s) => s.setQuery);
const filtered = query
? items.filter((e) =>
[e.name, e.description]
.filter(Boolean)
.some((s) => s!.toLowerCase().includes(query.toLowerCase())),
)
: items;
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('equipment', ''), [setQuery]);
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<Equipment | null>(null);
const [form, setForm] = useState<FormState>(EMPTY);
const [formError, setFormError] = useState<string | null>(null);
const [deleting, setDeleting] = useState<Equipment | null>(null);
const invalidate = () => qc.invalidateQueries({ queryKey: ['equipment'] });
const save = useMutation({
mutationFn: async () => {
const kind = form.kind;
let spec: Record<string, number> | null = null;
if (LOAD_RANGE_KINDS.includes(kind)) {
const minKg = parseNum(form.minKg);
const maxKg = parseNum(form.maxKg);
if (minKg == null || maxKg == null) throw new Error('Podaj zakres obciążeń (min i max w kg).');
spec = { minKg, maxKg };
} else if (MAX_LOAD_KINDS.includes(kind)) {
const maxLoadKg = parseNum(form.maxLoadKg);
if (maxLoadKg == null) throw new Error('Podaj maksymalne obciążenie (kg).');
spec = { maxLoadKg };
} else if (kind === 'CARDIO') {
const maxSpeedKmh = parseNum(form.maxSpeedKmh);
const maxInclinePct = parseNum(form.maxInclinePct);
if (maxSpeedKmh != null || maxInclinePct != null) {
spec = {
...(maxSpeedKmh != null ? { maxSpeedKmh } : {}),
...(maxInclinePct != null ? { maxInclinePct } : {}),
};
}
}
const body = {
name: form.name,
description: form.description || null,
kind,
spec,
};
if (editing) {
await api(`/admin/equipment/${editing.id}`, { method: 'PATCH', body });
} else {
await api('/admin/equipment', { method: 'POST', body });
}
},
onSuccess: () => {
invalidate();
setFormOpen(false);
setEditing(null);
setForm(EMPTY);
setFormError(null);
},
onError: (e) => setFormError((e as Error).message),
});
const remove = useMutation({
mutationFn: (id: string) => api(`/admin/equipment/${id}`, { method: 'DELETE' }),
onSuccess: () => {
invalidate();
setDeleting(null);
},
});
function openCreate() {
setEditing(null);
setForm(EMPTY);
setFormError(null);
setFormOpen(true);
}
// menu top: akcja „Nowe urządzenie” otwiera modal w treści strony
useTopbar({
title: 'Urządzenia',
search: 'equipment',
actions: [{ label: 'Nowe urządzenie', onClick: openCreate, icon: Plus }],
});
function openEdit(item: Equipment) {
setEditing(item);
setForm(toFormState(item));
setFormError(null);
setFormOpen(true);
}
const specFields = (
kind: EquipmentKind,
set: <K extends keyof FormState>(key: K, value: FormState[K]) => void,
) => {
if (LOAD_RANGE_KINDS.includes(kind)) {
return (
<div className="grid grid-cols-2 gap-3">
<Field label="Obciążenie min (kg)">
<Input
type="number"
step="0.5"
min="0"
value={form.minKg}
onChange={(e) => set('minKg', e.target.value)}
placeholder="np. 2.5"
/>
</Field>
<Field label="Obciążenie max (kg)">
<Input
type="number"
step="0.5"
min="0"
value={form.maxKg}
onChange={(e) => set('maxKg', e.target.value)}
placeholder="np. 25"
/>
</Field>
</div>
);
}
if (MAX_LOAD_KINDS.includes(kind)) {
return (
<Field label="Maksymalne obciążenie (kg)">
<Input
type="number"
step="0.5"
min="0"
value={form.maxLoadKg}
onChange={(e) => set('maxLoadKg', e.target.value)}
placeholder="np. 100"
/>
</Field>
);
}
if (kind === 'CARDIO') {
return (
<div className="grid grid-cols-2 gap-3">
<Field label="Maks. prędkość (km/h, opcjonalnie)">
<Input
type="number"
step="0.1"
min="0"
value={form.maxSpeedKmh}
onChange={(e) => set('maxSpeedKmh', e.target.value)}
placeholder="np. 16"
/>
</Field>
<Field label="Maks. nachylenie (% opcjonalnie)">
<Input
type="number"
step="1"
min="0"
max="40"
value={form.maxInclinePct}
onChange={(e) => set('maxInclinePct', e.target.value)}
placeholder="np. 15"
/>
</Field>
</div>
);
}
return null;
};
return (
<>
<Muted className="mb-4 block">
Katalog maszyn i urządzeń. Przypisuj je do rodzajów ćwiczeń i siłowni.
</Muted>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{filtered.map((item) => (
<Card key={item.id} className="mb-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-[1.05rem] font-semibold">
{item.name}
<span className="ml-2 text-[0.875rem] text-dim font-normal">
{EQUIPMENT_KIND_LABELS[item.kind]}
</span>
</div>
{formatEquipmentSpec(item.spec) && (
<div className="mt-0.5 text-[0.875rem] text-dim">{formatEquipmentSpec(item.spec)}</div>
)}
{item.description && (
<p className="mt-1 text-dim text-[0.875rem]">{item.description}</p>
)}
</div>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" onClick={() => openEdit(item)} aria-label={`Edytuj ${item.name}`}>
<Pencil className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="text-danger hover:text-danger"
onClick={() => setDeleting(item)}
aria-label={`Usuń ${item.name}`}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</Card>
))}
</div>
{!isLoading && !error && filtered.length === 0 && (
<Card>
<EmptyState
icon={Wrench}
title="Brak urządzeń"
description={
query
? 'Brak wyników dla podanego zapytania.'
: 'Brak urządzeń. Dodaj pierwsze przyciskiem „Nowe urządzenie” w menu kontekstowym.'
}
/>
</Card>
)}
<Modal
open={formOpen}
onClose={() => setFormOpen(false)}
title={editing ? 'Edytuj urządzenie' : 'Nowe urządzenie'}
>
<div className="flex flex-col gap-3.5">
<Field label="Nazwa">
<Input
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
placeholder="np. Sztanga"
/>
</Field>
<Field label="Rodzaj">
<Select
value={form.kind}
onChange={(e) => setForm((f) => ({ ...f, kind: e.target.value as EquipmentKind }))}
>
{(Object.keys(EQUIPMENT_KIND_LABELS) as EquipmentKind[]).map((k) => (
<option key={k} value={k}>
{EQUIPMENT_KIND_LABELS[k]}
</option>
))}
</Select>
</Field>
{specFields(form.kind, (key, value) => setForm((f) => ({ ...f, [key]: value })))}
<Field label="Opis (opcjonalnie)">
<Textarea
value={form.description}
onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
placeholder="np. Sztanga z talerzami."
rows={3}
/>
</Field>
{formError && <ErrorText>{formError}</ErrorText>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={() => setFormOpen(false)}>
Anuluj
</Button>
<Button onClick={() => save.mutate()} disabled={save.isPending || !form.name}>
{editing ? 'Zapisz' : 'Dodaj'}
</Button>
</div>
</div>
</Modal>
<ConfirmDialog
open={deleting != null}
onClose={() => setDeleting(null)}
onConfirm={() => deleting && remove.mutate(deleting.id)}
title="Usuń urządzenie"
description={`Na pewno usunąć „${deleting?.name}”? Zostanie odczepione od ćwiczeń i siłowni.`}
confirmLabel="Usuń"
danger
busy={remove.isPending}
/>
</>
);
}

View File

@@ -0,0 +1,262 @@
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Pencil, Plus, Trash2, Dumbbell } from 'lucide-react';
import { api } from '../api/client';
import type { Equipment, Exercise } from '../api/types';
import { useTopbar } from '../topbar';
import { useListSearch } from '../store/list-search';
import {
Badge,
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
Input,
Loading,
Modal,
Muted,
} from '../components/ui';
interface FormState {
name: string;
primaryMuscle: string;
equipmentIds: string[];
}
const EMPTY: FormState = { name: '', primaryMuscle: '', equipmentIds: [] };
export default function Exercises() {
const qc = useQueryClient();
const { data, isLoading, error } = useQuery({
queryKey: ['exercises'],
queryFn: () => api<{ exercises: Exercise[] }>('/admin/exercises'),
});
const { data: eqData } = useQuery({
queryKey: ['equipment'],
queryFn: () => api<{ equipment: Equipment[] }>('/admin/equipment'),
});
const exercises = data?.exercises ?? [];
const equipment = eqData?.equipment ?? [];
const query = useListSearch((s) => s.queries.exercises);
const setQuery = useListSearch((s) => s.setQuery);
const filtered = query
? exercises.filter((ex) =>
[ex.name, ex.primaryMuscle]
.filter(Boolean)
.some((s) => s!.toLowerCase().includes(query.toLowerCase())),
)
: exercises;
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('exercises', ''), [setQuery]);
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<Exercise | null>(null);
const [form, setForm] = useState<FormState>(EMPTY);
const [formError, setFormError] = useState<string | null>(null);
const [deleting, setDeleting] = useState<Exercise | null>(null);
const invalidate = () => {
qc.invalidateQueries({ queryKey: ['exercises'] });
};
const save = useMutation({
mutationFn: async () => {
const body = {
name: form.name,
primaryMuscle: form.primaryMuscle,
equipmentIds: form.equipmentIds,
};
if (editing) {
await api(`/admin/exercises/${editing.id}`, { method: 'PATCH', body });
} else {
await api('/admin/exercises', { method: 'POST', body });
}
},
onSuccess: () => {
invalidate();
setFormOpen(false);
setEditing(null);
setForm(EMPTY);
setFormError(null);
},
onError: (e) => setFormError((e as Error).message),
});
const remove = useMutation({
mutationFn: (id: string) => api(`/admin/exercises/${id}`, { method: 'DELETE' }),
onSuccess: () => {
invalidate();
setDeleting(null);
},
onError: (e) => alert((e as Error).message),
});
function openCreate() {
setEditing(null);
setForm(EMPTY);
setFormError(null);
setFormOpen(true);
}
// menu top: akcja „Nowe ćwiczenie” otwiera modal w treści strony
useTopbar({
title: 'Rodzaje ćwiczeń',
search: 'exercises',
actions: [{ label: 'Nowe ćwiczenie', onClick: openCreate, icon: Plus }],
});
function openEdit(ex: Exercise) {
setEditing(ex);
setForm({
name: ex.name,
primaryMuscle: ex.primaryMuscle,
equipmentIds: ex.equipment.map((e) => e.id),
});
setFormError(null);
setFormOpen(true);
}
function toggleEquipment(id: string) {
setForm((f) => ({
...f,
equipmentIds: f.equipmentIds.includes(id)
? f.equipmentIds.filter((x) => x !== id)
: [...f.equipmentIds, id],
}));
}
return (
<>
<Muted className="mb-4 block">Rodzaje ćwiczeń i przypisane do nich maszyny/urządzenia.</Muted>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{filtered.map((ex) => (
<Card key={ex.id} className="mb-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-[1.05rem] font-semibold">{ex.name}</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5">
<Badge color="blue">{ex.primaryMuscle}</Badge>
{ex.equipment.length === 0 && (
<span className="text-dim text-[0.875rem]">brak maszyn</span>
)}
{ex.equipment.map((e) => (
<Badge key={e.id} color="gray">
{e.name}
</Badge>
))}
</div>
</div>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" onClick={() => openEdit(ex)} aria-label={`Edytuj ${ex.name}`}>
<Pencil className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="text-danger hover:text-danger"
onClick={() => setDeleting(ex)}
aria-label={`Usuń ${ex.name}`}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
</Card>
))}
</div>
{!isLoading && !error && filtered.length === 0 && (
<Card>
<EmptyState
icon={Dumbbell}
title="Brak ćwiczeń"
description={
query
? 'Brak wyników dla podanego zapytania.'
: 'Brak ćwiczeń. Dodaj pierwsze przyciskiem „Nowe ćwiczenie” w menu kontekstowym.'
}
/>
</Card>
)}
<Modal
open={formOpen}
onClose={() => setFormOpen(false)}
title={editing ? 'Edytuj ćwiczenie' : 'Nowe ćwiczenie'}
>
<div className="flex flex-col gap-3.5">
<Field label="Nazwa">
<Input
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
placeholder="np. Wyciskanie sztangi leżąc"
/>
</Field>
<Field label="Główny mięsień">
<Input
value={form.primaryMuscle}
onChange={(e) => setForm((f) => ({ ...f, primaryMuscle: e.target.value }))}
placeholder="np. chest"
/>
</Field>
<Field label="Maszyny / urządzenia">
{equipment.length === 0 ? (
<p className="text-dim text-[0.875rem]">
Brak urządzeń w katalogu. Dodaj je w sekcji „Urządzenia”.
</p>
) : (
<div className="max-h-56 overflow-y-auto rounded-xl border border-line bg-input p-2">
{equipment.map((e) => (
<label
key={e.id}
className="flex items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-card cursor-pointer"
>
<input
type="checkbox"
checked={form.equipmentIds.includes(e.id)}
onChange={() => toggleEquipment(e.id)}
className="accent-[var(--accent)]"
/>
<span className="text-[0.875rem]">{e.name}</span>
</label>
))}
</div>
)}
</Field>
{formError && <ErrorText>{formError}</ErrorText>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={() => setFormOpen(false)}>
Anuluj
</Button>
<Button
onClick={() => save.mutate()}
disabled={save.isPending || !form.name || !form.primaryMuscle}
>
{editing ? 'Zapisz' : 'Dodaj'}
</Button>
</div>
</div>
</Modal>
<ConfirmDialog
open={deleting != null}
onClose={() => setDeleting(null)}
onConfirm={() => deleting && remove.mutate(deleting.id)}
title="Usuń ćwiczenie"
description={`Na pewno usunąć „${deleting?.name}”? Nie można usunąć ćwiczenia używanego w planach.`}
confirmLabel="Usuń"
danger
busy={remove.isPending}
/>
</>
);
}

View File

@@ -0,0 +1,244 @@
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Pencil, Plus, Trash2, Target } from 'lucide-react';
import { api } from '../api/client';
import type { FocusArea } from '../api/types';
import { useTopbar } from '../topbar';
import { useListSearch } from '../store/list-search';
import {
Badge,
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
Input,
Loading,
Modal,
Muted,
Textarea,
} from '../components/ui';
interface FormState {
name: string;
muscle: string;
description: string;
setsMin: string;
setsMax: string;
}
const EMPTY: FormState = { name: '', muscle: '', description: '', setsMin: '', setsMax: '' };
export default function FocusAreas() {
const qc = useQueryClient();
const { data, isLoading, error } = useQuery({
queryKey: ['focus-areas'],
queryFn: () => api<{ focusAreas: FocusArea[] }>('/admin/focus-areas'),
});
const areas = data?.focusAreas ?? [];
const query = useListSearch((s) => s.queries['focus-areas']);
const setQuery = useListSearch((s) => s.setQuery);
const filtered = query
? areas.filter((a) =>
[a.name, a.muscle, a.description]
.filter(Boolean)
.some((s) => s!.toLowerCase().includes(query.toLowerCase())),
)
: areas;
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('focus-areas', ''), [setQuery]);
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<FocusArea | null>(null);
const [form, setForm] = useState<FormState>(EMPTY);
const [formError, setFormError] = useState<string | null>(null);
const [deleting, setDeleting] = useState<FocusArea | null>(null);
const invalidate = () => qc.invalidateQueries({ queryKey: ['focus-areas'] });
const save = useMutation({
mutationFn: async () => {
const body = {
name: form.name,
muscle: form.muscle,
description: form.description || null,
setsMin: form.setsMin ? parseInt(form.setsMin) : null,
setsMax: form.setsMax ? parseInt(form.setsMax) : null,
};
if (editing) {
await api(`/admin/focus-areas/${editing.id}`, { method: 'PATCH', body });
} else {
await api('/admin/focus-areas', { method: 'POST', body });
}
},
onSuccess: () => {
invalidate();
setFormOpen(false);
setEditing(null);
setForm(EMPTY);
setFormError(null);
},
onError: (e) => setFormError((e as Error).message),
});
const remove = useMutation({
mutationFn: (id: string) => api(`/admin/focus-areas/${id}`, { method: 'DELETE' }),
onSuccess: () => {
invalidate();
setDeleting(null);
},
});
function openCreate() {
setEditing(null);
setForm(EMPTY);
setFormError(null);
setFormOpen(true);
}
// menu top: akcja „Nowy obszar” otwiera modal w treści strony
useTopbar({
title: 'Obszary treningowe',
search: 'focus-areas',
actions: [{ label: 'Nowy obszar', onClick: openCreate, icon: Plus }],
});
function openEdit(area: FocusArea) {
setEditing(area);
setForm({
name: area.name,
muscle: area.muscle,
description: area.description ?? '',
setsMin: area.setsMin != null ? String(area.setsMin) : '',
setsMax: area.setsMax != null ? String(area.setsMax) : '',
});
setFormError(null);
setFormOpen(true);
}
return (
<>
<Muted className="mb-4 block">
Katalog obszarów treningowych — z niego użytkownicy i trenerzy wybierają priorytety i wykluczenia.
</Muted>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{filtered.map((a) => (
<Card key={a.id} className="mb-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="text-[1.05rem] font-semibold">{a.name}</div>
<div className="mt-0.5 flex items-center gap-1.5">
<Badge color="blue">{a.muscle}</Badge>
{a.setsMin != null && a.setsMax != null && (
<Badge color="gray">{a.setsMin}–{a.setsMax} serii/tydz.</Badge>
)}
</div>
</div>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" onClick={() => openEdit(a)} aria-label={`Edytuj ${a.name}`}>
<Pencil className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="text-danger hover:text-danger"
onClick={() => setDeleting(a)}
aria-label={`Usuń ${a.name}`}
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
{a.description && <p className="mt-2 text-dim text-[0.875rem]">{a.description}</p>}
</Card>
))}
</div>
{!isLoading && !error && filtered.length === 0 && (
<Card>
<EmptyState
icon={Target}
title="Brak obszarów"
description={
query
? 'Brak wyników dla podanego zapytania.'
: 'Brak obszarów. Dodaj pierwszy przyciskiem „Nowy obszar” w menu kontekstowym.'
}
/>
</Card>
)}
<Modal open={formOpen} onClose={() => setFormOpen(false)} title={editing ? 'Edytuj obszar' : 'Nowy obszar'}>
<div className="flex flex-col gap-3.5">
<Field label="Nazwa">
<Input
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
placeholder="np. Klatka piersiowa"
/>
</Field>
<Field label="Klucz mięśnia">
<Input
value={form.muscle}
onChange={(e) => setForm((f) => ({ ...f, muscle: e.target.value }))}
placeholder="np. chest"
/>
</Field>
<Field label="Opis (opcjonalnie)">
<Textarea
value={form.description}
onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
placeholder="np. Wyciskanie, rozpiętki, pompki"
rows={3}
/>
</Field>
<div className="grid grid-cols-2 gap-3">
<Field label="Zalecane serie min./tydz.">
<Input
type="number"
value={form.setsMin}
onChange={(e) => setForm((f) => ({ ...f, setsMin: e.target.value }))}
placeholder="np. 10"
/>
</Field>
<Field label="Zalecane serie max./tydz.">
<Input
type="number"
value={form.setsMax}
onChange={(e) => setForm((f) => ({ ...f, setsMax: e.target.value }))}
placeholder="np. 20"
/>
</Field>
</div>
{formError && <ErrorText>{formError}</ErrorText>}
<div className="flex justify-end gap-2">
<Button variant="secondary" onClick={() => setFormOpen(false)}>
Anuluj
</Button>
<Button onClick={() => save.mutate()} disabled={save.isPending || !form.name || !form.muscle}>
{editing ? 'Zapisz' : 'Dodaj'}
</Button>
</div>
</div>
</Modal>
<ConfirmDialog
open={deleting != null}
onClose={() => setDeleting(null)}
onConfirm={() => deleting && remove.mutate(deleting.id)}
title="Usuń obszar"
description={`Na pewno usunąć „${deleting?.name}”? Użytkownicy nie będą mogli go wybierać.`}
confirmLabel="Usuń"
danger
busy={remove.isPending}
/>
</>
);
}

View File

@@ -0,0 +1,636 @@
import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ImagePlus, Star, X } from 'lucide-react';
import { useTopbar } from '../topbar';
import { api, getAccessToken } from '../api/client';
import { API_BASE } from '../config';
import type { Equipment, Gym, GymException, GymPhoto } from '../api/types';
import { formatEquipmentSpec, formatGymEquipment } from '../lib/equipment';
import {
BackButton,
Badge,
Button,
Card,
Chip,
ErrorText,
Field,
Input,
ListRow,
Loading,
PageHeader,
SectionHeader,
Select,
SuccessText,
} from '../components/ui';
import { AvailabilityEditor } from '../components/AvailabilityEditor';
import { formatAvailability, normalizeAvailability, TIME_SLOTS } from '../lib/availability';
function InfoItem({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div>
<div className="text-[11px] font-bold uppercase tracking-[0.1em] text-dim">{label}</div>
<div className="mt-0.5">{children}</div>
</div>
);
}
export function gymPhotoSrc(url: string): string {
return `${API_BASE}${url}`;
}
const PHOTO_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
const MAX_PHOTO_FILES = 10;
const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024;
async function uploadGymPhotos(gymId: string, files: File[]): Promise<unknown> {
const form = new FormData();
for (const file of files) form.append('photos', file);
const res = await fetch(`${API_BASE}/gyms/${gymId}/photos`, {
method: 'POST',
credentials: 'include',
headers: { Authorization: `Bearer ${getAccessToken()}` },
body: form,
});
const text = await res.text();
let json: unknown = null;
if (text) {
try {
json = JSON.parse(text);
} catch {
// nie-JSON
}
}
if (!res.ok) throw new Error((json as { error?: { message?: string } })?.error?.message ?? `HTTP ${res.status}`);
return json;
}
function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void }) {
const [form, setForm] = useState({
name: gym.name,
location: gym.location ?? '',
availability: normalizeAvailability(gym.availability),
capacity: gym.capacity?.toString() ?? '',
});
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [saved, setSaved] = useState(false);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setBusy(true);
try {
await api(`/admin/gyms/${gym.id}`, {
method: 'PATCH',
body: {
name: form.name,
location: form.location || null,
availability: form.availability.some((d) => d != null) ? form.availability : null,
capacity: form.capacity ? parseInt(form.capacity) : null,
},
});
setSaved(true);
onSaved();
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
return (
<form onSubmit={submit}>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="Nazwa">
<Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
</Field>
<Field label="Lokalizacja">
<Input value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} />
</Field>
<Field label="Ilość miejsc">
<Input type="number" value={form.capacity} onChange={(e) => setForm({ ...form, capacity: e.target.value })} />
</Field>
</div>
<Field label="Dostępność (dzień tygodnia + przedział godzin)">
<AvailabilityEditor
value={form.availability}
onChange={(availability) => setForm({ ...form, availability })}
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
{saved && !error && <SuccessText>Zapisano zmiany.</SuccessText>}
<Button type="submit" disabled={busy}>
{busy ? 'Zapisywanie…' : 'Zapisz'}
</Button>
</form>
);
}
export default function GymDetail() {
const { id } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { data: gym, isLoading, error } = useQuery({
queryKey: ['gym', id],
queryFn: () => api<Gym>(`/admin/gyms/${id}`),
enabled: !!id,
});
const remove = async () => {
if (!gym) return;
if (!confirm('Usunąć siłownię? Członkostwa zostaną usunięte, plany użytkowników zachowane.')) return;
try {
await api(`/admin/gyms/${gym.id}`, { method: 'DELETE' });
await queryClient.invalidateQueries({ queryKey: ['gyms'] });
navigate('/gyms');
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
// operacje stronicowe w menu kontekstowym (standard topmenu)
useTopbar({
title: 'Siłownie',
actions: [{ label: 'Usuń siłownię', variant: 'danger', onClick: remove }],
});
if (isLoading) return <Loading />;
if (error) return <ErrorText>Błąd: {(error as Error).message}</ErrorText>;
if (!gym) {
return (
<>
<BackButton to="/gyms" className="mb-4" />
<ErrorText>Nie znaleziono siłowni.</ErrorText>
</>
);
}
return (
<>
<PageHeader
title={gym.name}
badge={
<>
<Badge color={gym.kind === 'VIRTUAL' ? 'blue' : 'gray'}>
{gym.kind === 'VIRTUAL' ? 'Wirtualna' : 'Realna'}
</Badge>
{gym.isPrivate && <Badge color="gray">Prywatna</Badge>}
<Badge color="gray">{gym._count?.memberships ?? 0} członk.</Badge>
</>
}
actions={<BackButton to="/gyms" />}
/>
{gym.coverPhoto && (
<div className="relative mb-4 overflow-hidden rounded-lg border border-line shadow-card">
<img src={gymPhotoSrc(gym.coverPhoto)} alt={gym.name} className="h-44 w-full object-cover sm:h-56" />
<div
aria-hidden="true"
className="absolute inset-0 bg-[linear-gradient(180deg,transparent_45%,rgb(0_0_0/0.55))]"
/>
<div className="absolute bottom-3 left-4 right-4 flex flex-wrap items-center gap-2">
<span className="font-display text-[1.25rem] font-bold tracking-[-0.01em] text-white drop-shadow">
{gym.name}
</span>
<span className="rounded-full bg-white/15 px-2.5 py-0.5 text-[0.7rem] font-bold text-white backdrop-blur-sm">
{gym._count?.memberships ?? 0} członków
</span>
</div>
</div>
)}
{gym.kind === 'REAL' && (
<Card>
<GallerySection gym={gym} onChanged={() => {}} />
</Card>
)}
<Card>
<SectionHeader title="Dane" />
<div className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
<InfoItem label="Nazwa">{gym.name}</InfoItem>
<InfoItem label="Lokalizacja">{gym.location || '—'}</InfoItem>
<InfoItem label="Dostępność">{formatAvailability(gym.availability) || '—'}</InfoItem>
<InfoItem label="Ilość miejsc">{gym.capacity ?? '—'}</InfoItem>
</div>
</Card>
<Card>
<SectionHeader title="Edycja" />
<GymEditForm
key={gym.id}
gym={gym}
onSaved={() => {
void queryClient.invalidateQueries({ queryKey: ['gyms'] });
void queryClient.invalidateQueries({ queryKey: ['gym', gym.id] });
}}
/>
</Card>
<Card>
<EquipmentSection key={gym.id} gym={gym} />
</Card>
<Card>
<ExceptionsSection gymId={gym.id} />
</Card>
</>
);
}
function EquipmentSection({ gym }: { gym: Gym }) {
const queryClient = useQueryClient();
const { data: eqData, isLoading } = useQuery({
queryKey: ['equipment'],
queryFn: () => api<{ equipment: Equipment[] }>('/admin/equipment'),
});
const catalog = eqData?.equipment ?? [];
const quantities = new Map(gym.equipment.map((e) => [e.equipmentId, e.quantity]));
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [addId, setAddId] = useState('');
const [addQty, setAddQty] = useState('1');
const invalidate = () =>
Promise.all([
queryClient.invalidateQueries({ queryKey: ['gyms'] }),
queryClient.invalidateQueries({ queryKey: ['gym', gym.id] }),
]);
const add = async () => {
if (!addId) return;
const quantity = parseInt(addQty, 10) || 1;
setError('');
setBusy(true);
try {
const existing = quantities.get(addId);
if (existing != null) {
await api(`/admin/gyms/${gym.id}/equipment/${addId}`, {
method: 'PATCH',
body: { quantity: existing + quantity },
});
} else {
await api(`/admin/gyms/${gym.id}/equipment`, {
method: 'POST',
body: { equipmentId: addId, quantity },
});
}
setAddId('');
setAddQty('1');
await invalidate();
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
const changeQty = async (equipmentId: string, quantity: number) => {
try {
await api(`/admin/gyms/${gym.id}/equipment/${equipmentId}`, {
method: 'PATCH',
body: { quantity },
});
await invalidate();
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
const remove = async (equipmentId: string) => {
try {
await api(`/admin/gyms/${gym.id}/equipment/${equipmentId}`, { method: 'DELETE' });
await invalidate();
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
return (
<>
<SectionHeader
title="Urządzenia"
description="Maszyny i urządzenia dostępne w tej siłowni (z katalogu). Ilość = liczba sztuk danego sprzętu; ponowne dodanie zwiększa ilość."
/>
<div className="flex flex-wrap gap-2">
{gym.equipment.length === 0 && (
<span className="text-[0.875rem] text-dim">Brak urządzeń.</span>
)}
{gym.equipment.map((e) => (
<Chip
key={e.id}
onRemove={() => remove(e.equipmentId)}
removeLabel={`Usuń ${e.equipment.name}`}
>
{formatGymEquipment(e)}
<input
type="number"
min={1}
max={10000}
defaultValue={e.quantity}
aria-label={`Ilość: ${e.equipment.name}`}
className="w-14 border border-line bg-card rounded-md px-1.5 py-0.5 text-center text-[0.875rem]"
onBlur={(ev) => {
const value = parseInt(ev.target.value, 10);
if (Number.isFinite(value) && value >= 1 && value !== e.quantity) {
void changeQty(e.equipmentId, value);
} else {
ev.target.value = String(e.quantity);
}
}}
onKeyDown={(ev) => {
if (ev.key === 'Enter') (ev.target as HTMLInputElement).blur();
}}
/>
</Chip>
))}
</div>
<div className="mt-4 flex flex-wrap items-center gap-2">
<Select
value={addId}
onChange={(e) => setAddId(e.target.value)}
className="max-w-xs"
aria-label="Dodaj urządzenie"
>
<option value="">+ dodaj urządzenie…</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>
<Input
type="number"
min={1}
max={10000}
value={addQty}
onChange={(e) => setAddQty(e.target.value)}
className="w-20"
aria-label="Ilość"
/>
<Button size="sm" onClick={add} disabled={!addId || busy}>
{busy ? 'Dodawanie…' : 'Dodaj'}
</Button>
</div>
{error && <ErrorText>{error}</ErrorText>}
{isLoading && <Loading />}
</>
);
}
function ExceptionsSection({ gymId }: { gymId: string }) {
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ['gym-exceptions', gymId],
queryFn: () => api<{ exceptions: GymException[] }>(`/admin/gyms/${gymId}/exceptions`),
});
const exceptions = data?.exceptions ?? [];
const [date, setDate] = useState('');
const [closed, setClosed] = useState(true);
const [start, setStart] = useState('18:00');
const [end, setEnd] = useState('20:00');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const add = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setBusy(true);
try {
await api(`/admin/gyms/${gymId}/exceptions`, {
method: 'POST',
body: { date, availability: closed ? null : { start, end } },
});
setDate('');
await queryClient.invalidateQueries({ queryKey: ['gym-exceptions', gymId] });
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
const remove = async (exceptionId: string) => {
try {
await api(`/admin/gyms/${gymId}/exceptions/${exceptionId}`, { method: 'DELETE' });
await queryClient.invalidateQueries({ queryKey: ['gym-exceptions', gymId] });
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
return (
<>
<SectionHeader
title="Wyjątki w harmonogramie"
description="Jednorazowe zmiany na konkretny dzień (zamknięcie lub inne godziny). Wyjątek znika, gdy dzień minie."
/>
{isLoading ? (
<Loading />
) : (
<div className="divide-y divide-line">
{exceptions.length === 0 && <span className="block text-[0.875rem] text-dim">Brak wyjątków.</span>}
{exceptions.map((ex) => (
<ListRow
key={ex.id}
title={`${new Date(ex.date).toLocaleDateString('pl-PL')} — ${
ex.availability ? `${ex.availability.start}–${ex.availability.end}` : 'zamknięte'
}`}
actions={
<Button variant="danger" size="sm" type="button" onClick={() => remove(ex.id)}>
Usuń
</Button>
}
/>
))}
</div>
)}
<form onSubmit={add} className="mt-4">
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="Data">
<Input type="date" value={date} onChange={(e) => setDate(e.target.value)} required />
</Field>
<Field label="Tryb">
<div className="inline-flex gap-1.5 rounded-xl border border-line bg-input p-1">
<button
type="button"
aria-pressed={closed}
onClick={() => setClosed(true)}
className={`rounded-lg px-3 py-1.5 text-[0.9rem] font-semibold transition-colors ${
closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
Zamknięte
</button>
<button
type="button"
aria-pressed={!closed}
onClick={() => setClosed(false)}
className={`rounded-lg px-3 py-1.5 text-[0.9rem] font-semibold transition-colors ${
!closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
Inne godziny
</button>
</div>
</Field>
{!closed && (
<>
<Field label="Od">
<Select value={start} onChange={(e) => setStart(e.target.value)}>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
</Field>
<Field label="Do">
<Select value={end} onChange={(e) => setEnd(e.target.value)}>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
</Field>
</>
)}
</div>
{error && <ErrorText>{error}</ErrorText>}
<div className="mt-1">
<Button type="submit" disabled={busy || !date}>
{busy ? 'Dodawanie…' : 'Dodaj wyjątek'}
</Button>
</div>
</form>
</>
);
}
function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) {
const queryClient = useQueryClient();
const photos = gym.photos ?? [];
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const invalidate = () => {
void queryClient.invalidateQueries({ queryKey: ['gyms'] });
void queryClient.invalidateQueries({ queryKey: ['gym', gym.id] });
};
const onPick = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files ?? []);
e.target.value = '';
if (files.length === 0) return;
const valid = files.filter(
(f) => PHOTO_MIME_TYPES.includes(f.type) && f.size <= MAX_PHOTO_FILE_SIZE,
);
if (valid.length === 0) {
setError('Dozwolone pliki: JPEG, PNG, WEBP (max 5 MB).');
return;
}
if (valid.length > MAX_PHOTO_FILES) {
setError(`Maksymalnie ${MAX_PHOTO_FILES} plików naraz.`);
return;
}
setError('');
setBusy(true);
try {
await uploadGymPhotos(gym.id, valid);
onChanged();
await invalidate();
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
const remove = async (photo: GymPhoto) => {
if (!confirm('Usunąć to zdjęcie?')) return;
try {
await api(`/gyms/${gym.id}/photos/${photo.id}`, { method: 'DELETE' });
onChanged();
await invalidate();
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
const setCover = async (photo: GymPhoto) => {
try {
await api(`/gyms/${gym.id}/photos/${photo.id}/cover`, { method: 'PATCH' });
onChanged();
await invalidate();
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
return (
<>
<SectionHeader
title="Galeria zdjęć"
description="Zdjęcia tej siłowni. Pierwsza pozycja to okładka (widoczna na liście)."
/>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
{photos.length === 0 && (
<span className="col-span-full text-[0.875rem] text-dim">Brak zdjęć.</span>
)}
{photos.map((photo, i) => (
<div key={photo.id} className="relative overflow-hidden rounded-xl border border-line">
<img src={gymPhotoSrc(photo.url)} alt={`Zdjęcie ${i + 1}`} className="h-32 w-full object-cover" />
{i === 0 && (
<span className="absolute left-1.5 top-1.5 rounded-md bg-black/70 px-1.5 py-0.5 text-[0.7rem] font-semibold text-white">
Okładka
</span>
)}
<div className="flex items-center justify-between gap-1 bg-card p-1.5">
{i === 0 ? (
<span className="inline-flex items-center gap-1 text-[0.75rem] text-dim">
<Star className="w-3.5 h-3.5 fill-accent text-accent-text" />
okładka
</span>
) : (
<button
type="button"
onClick={() => setCover(photo)}
className="inline-flex items-center gap-1 text-[0.75rem] text-dim hover:text-accent-text cursor-pointer"
>
<Star className="w-3.5 h-3.5" />
Ustaw jako okładkę
</button>
)}
<button
type="button"
onClick={() => remove(photo)}
aria-label="Usuń zdjęcie"
className="text-dim hover:text-danger cursor-pointer"
>
<X className="w-4 h-4" />
</button>
</div>
</div>
))}
</div>
<div className="mt-4 flex items-center gap-2">
<label className="inline-flex cursor-pointer items-center gap-1.5 rounded-xl border border-line px-3 py-1.5 text-[0.85rem] font-semibold text-dim hover:text-accent-text hover:border-accent">
<ImagePlus className="w-4 h-4" />
{busy ? 'Wgrywanie…' : 'Dodaj zdjęcia'}
<input type="file" accept={PHOTO_MIME_TYPES.join(',')} multiple hidden onChange={onPick} disabled={busy} />
</label>
</div>
{error && <ErrorText>{error}</ErrorText>}
</>
);
}

View File

@@ -0,0 +1,78 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../api/client';
import { BackButton, Button, Card, ErrorText, Field, H1, Input } from '../components/ui';
import { AvailabilityEditor } from '../components/AvailabilityEditor';
import { emptyAvailability } from '../lib/availability';
import type { Availability } from '../api/types';
import { useTopbar } from '../topbar';
export default function GymForm() {
useTopbar({ title: 'Siłownie' });
const navigate = useNavigate();
const [form, setForm] = useState({
name: '',
location: '',
availability: emptyAvailability(),
capacity: '',
});
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setBusy(true);
try {
const availability: Availability | null = form.availability.some((d) => d != null)
? form.availability
: null;
const data = await api<{ gym: { id: string } }>('/admin/gyms', {
method: 'POST',
body: {
name: form.name,
location: form.location || null,
availability,
capacity: form.capacity ? parseInt(form.capacity) : null,
},
});
navigate(`/gyms/${data.gym.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
return (
<>
<BackButton to="/gyms" className="mb-4" />
<H1>Nowa siłownia</H1>
<Card>
<form onSubmit={submit}>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="Nazwa">
<Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
</Field>
<Field label="Lokalizacja">
<Input value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} />
</Field>
<Field label="Ilość miejsc">
<Input type="number" value={form.capacity} onChange={(e) => setForm({ ...form, capacity: e.target.value })} />
</Field>
</div>
<Field label="Dostępność (dzień tygodnia + przedział godzin)">
<AvailabilityEditor
value={form.availability}
onChange={(availability) => setForm({ ...form, availability })}
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<Button type="submit" disabled={busy}>
{busy ? 'Zapisywanie…' : 'Utwórz siłownię'}
</Button>
</form>
</Card>
</>
);
}

View File

@@ -0,0 +1,119 @@
import { useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Clock, MapPin, Plus, Users, Building2, Dumbbell } from 'lucide-react';
import { api } from '../api/client';
import type { Gym } from '../api/types';
import { Badge, Card, EmptyState, ErrorText, Loading, MetaItem } from '../components/ui';
import { formatAvailability } from '../lib/availability';
import { useListSearch } from '../store/list-search';
import { useTopbar } from '../topbar';
import { gymPhotoSrc } from './GymDetail';
export default function GymsList() {
useTopbar({
title: 'Siłownie',
search: 'gyms',
actions: [{ label: 'Nowa siłownia', to: '/gyms/new', icon: Plus }],
});
const navigate = useNavigate();
const { data, isLoading, error } = useQuery({
queryKey: ['gyms'],
queryFn: () => api<{ gyms: Gym[] }>('/admin/gyms'),
});
const query = useListSearch((s) => s.queries.gyms);
const setQuery = useListSearch((s) => s.setQuery);
const gyms = data?.gyms ?? [];
const filtered = query
? gyms.filter((g) =>
[g.name, g.location]
.filter(Boolean)
.some((s) => s!.toLowerCase().includes(query.toLowerCase())),
)
: gyms;
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('gyms', ''), [setQuery]);
return (
<>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{filtered.map((g) => (
<div
key={g.id}
className="cursor-pointer overflow-hidden rounded-lg border border-line bg-(image:--card-grad) shadow-card transition-all hover:border-accent/55"
onClick={() => navigate(`/gyms/${g.id}`)}
>
{g.coverPhoto ? (
<img
src={gymPhotoSrc(g.coverPhoto)}
alt={g.name}
className="h-28 w-full object-cover sm:h-32"
/>
) : (
<div
aria-hidden="true"
className="relative grid h-20 place-items-center overflow-hidden sm:h-24"
style={{
background:
'linear-gradient(140deg, color-mix(in srgb, var(--accent) 22%, var(--bg-input)), color-mix(in srgb, var(--line) 55%, var(--bg-input)) 55%, var(--bg-input))',
}}
>
<div
className="absolute inset-0 opacity-60"
style={{
background:
'repeating-linear-gradient(45deg, color-mix(in srgb, var(--text) 4%, transparent) 0 2px, transparent 2px 14px)',
}}
/>
<Dumbbell className="relative h-7 w-7 text-ink/25" />
</div>
)}
<div className="p-5 sm:p-6">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<Link to={`/gyms/${g.id}`} className="text-[1.05rem] font-semibold hover:text-accent-text">
{g.name}
</Link>
<Badge color={g.kind === 'VIRTUAL' ? 'blue' : 'gray'}>
{g.kind === 'VIRTUAL' ? 'Wirtualna' : 'Realna'}
</Badge>
{g.isPrivate && <Badge color="gray">Prywatna</Badge>}
</div>
<div className="mt-1">
<MetaItem icon={MapPin}>{g.location || '—'}</MetaItem>
</div>
</div>
<Badge color="gray">{g._count?.memberships ?? 0} członk.</Badge>
</div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1">
<MetaItem icon={Clock}>{formatAvailability(g.availability) || '—'}</MetaItem>
<MetaItem icon={Users}>{g.capacity != null ? `${g.capacity} miejsc` : '—'}</MetaItem>
</div>
</div>
</div>
))}
</div>
{!isLoading && !error && filtered.length === 0 && (
<Card>
<EmptyState
icon={Building2}
title="Brak siłowni"
description={
query
? 'Brak wyników dla podanego zapytania.'
: 'Brak siłowni. Dodaj pierwszą przyciskiem „Nowa siłownia” w menu kontekstowym.'
}
/>
</Card>
)}
</>
);
}

112
admin/src/pages/Login.tsx Normal file
View File

@@ -0,0 +1,112 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../store/auth';
import { Button, Card, ErrorText, Field, H1, Input, ThemeToggle } from '../components/ui';
import { Brandmark } from '../components/Brandmark';
const REMEMBER_KEY = 'fitos-remembered-email';
export default function Login() {
const { login } = useAuth();
const navigate = useNavigate();
const [email, setEmail] = useState(() => localStorage.getItem(REMEMBER_KEY) ?? '');
const [password, setPassword] = useState('');
const [remember, setRemember] = useState(() => Boolean(localStorage.getItem(REMEMBER_KEY)));
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
await login(email, password);
if (remember) localStorage.setItem(REMEMBER_KEY, email);
else localStorage.removeItem(REMEMBER_KEY);
navigate('/');
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd logowania');
} finally {
setLoading(false);
}
};
return (
<div className="relative flex min-h-screen items-center justify-center p-4">
<ThemeToggle className="fixed right-4 top-4 z-10" />
<div className="grid w-full max-w-3xl overflow-hidden rounded-[18px] border border-line bg-card shadow-card md:grid-cols-2">
<div
className="relative flex flex-col gap-3.5 overflow-hidden border-b border-line p-7 md:border-b-0 md:border-r md:p-8"
style={{
background:
'radial-gradient(130% 90% at 12% 8%, color-mix(in srgb, var(--accent) 24%, transparent), transparent 52%),' +
'radial-gradient(80% 60% at 95% 100%, color-mix(in srgb, var(--warn) 10%, transparent), transparent 60%),' +
'var(--bg-card)',
}}
>
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 opacity-50"
style={{
background:
'repeating-linear-gradient(90deg, color-mix(in srgb, var(--line) 35%, transparent) 0 1px, transparent 1px 72px)',
}}
/>
<div className="relative flex items-center gap-2.5">
<Brandmark size={30} />
<span className="font-display text-[1.25rem] font-bold tracking-[-0.02em]">FitOS Admin</span>
</div>
<div className="relative font-display text-[1.7rem] font-bold leading-[1.14] tracking-[-0.025em] md:text-[1.95rem]">
Pełna kontrola
<br />
nad systemem.
</div>
<p className="relative m-0 max-w-[34ch] text-[0.875rem] leading-relaxed text-dim">
Użytkownicy, siłownie, weryfikacje i słowniki — wszystko w jednym panelu.
</p>
<div className="relative mt-auto flex gap-6 pt-4">
<div>
<div className="font-display text-[1.4rem] font-bold tabular-nums">24/7</div>
<div className="text-[10.5px] font-bold uppercase tracking-[0.13em] text-dim">monitoring</div>
</div>
<div>
<div className="font-display text-[1.4rem] font-bold tabular-nums">100%</div>
<div className="text-[10.5px] font-bold uppercase tracking-[0.13em] text-dim">audyt zdarzeń</div>
</div>
<div>
<div className="font-display text-[1.4rem] font-bold tabular-nums">1</div>
<div className="text-[10.5px] font-bold uppercase tracking-[0.13em] text-dim">panel</div>
</div>
</div>
</div>
<Card className="m-0 rounded-none border-0 p-7 shadow-none md:p-8">
<div className="mb-5">
<H1 className="mb-1">FitOS Admin</H1>
<p className="text-dim">Panel administracyjny (tylko admin)</p>
</div>
<form onSubmit={submit}>
<Field label="E-mail">
<Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required autoComplete="email" />
</Field>
<Field label="Hasło">
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required autoComplete="current-password" />
</Field>
<label className="flex items-center gap-2 mb-3.5 text-[0.875rem] text-dim cursor-pointer select-none">
<input
type="checkbox"
checked={remember}
onChange={(e) => setRemember(e.target.checked)}
className="size-4 accent-[var(--accent)]"
/>
Zapamiętaj mnie
</label>
{error && <ErrorText>{error}</ErrorText>}
<Button type="submit" disabled={loading} className="w-full">
{loading ? 'Logowanie…' : 'Zaloguj'}
</Button>
</form>
</Card>
</div>
</div>
);
}

275
admin/src/pages/Logs.tsx Normal file
View File

@@ -0,0 +1,275 @@
import { useEffect, useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ScrollText } from 'lucide-react';
import { useTopbar } from '../topbar';
import { MonthPicker } from '../topbar/MonthPicker';
import { api } from '../api/client';
import type { ActivityLog, ActivityLogPage } from '../api/types';
import { Badge, EmptyState, ErrorText, Loading, Select, type BadgeColor } from '../components/ui';
import { useListSearch } from '../store/list-search';
export const ACTION_LABELS: Record<string, string> = {
'user.registered': 'Rejestracja',
'profile.updated': 'Zmiana profilu',
'weight.added': 'Waga dodana',
'weight.removed': 'Waga usunięta',
'circumference.added': 'Obwód dodany',
'circumference.removed': 'Obwód usunięty',
'plan.created': 'Plan utworzony',
'plan.updated': 'Plan zaktualizowany',
'plan.deleted': 'Plan usunięty',
'plan.activated': 'Plan aktywowany',
'plan.abandoned': 'Plan porzucony',
'plan.completed': 'Plan ukończony',
'session.started': 'Sesja rozpoczęta',
'session.completed': 'Sesja zakończona',
'session.abandoned': 'Sesja porzucona',
'gym.created': 'Siłownia utworzona',
'gym.updated': 'Siłownia zaktualizowana',
'gym.deleted': 'Siłownia usunięta',
'gym.joined': 'Dołączono do siłowni',
'coaching.invited': 'Zaproszenie wysłane',
'coaching.accepted': 'Zaproszenie przyjęte',
'coaching.declined': 'Zaproszenie odrzucone',
'coaching.withdrawn': 'Zaproszenie wycofane',
'coaching.archived': 'Relacja zarchiwizowana',
};
const ENTITY_LABELS: Record<string, string> = {
user: 'Użytkownik',
plan: 'Plan',
session: 'Sesja',
gym: 'Siłownia',
coaching: 'Coaching',
};
export function actionLabel(action: string) {
return ACTION_LABELS[action] ?? action;
}
function actionColor(action: string): BadgeColor {
if (action.startsWith('plan.')) return 'blue';
if (action.startsWith('session.')) return 'green';
if (action.startsWith('gym.')) return 'gray';
if (action.startsWith('coaching.')) return 'red';
return 'yellow';
}
const DATE_FORMAT = new Intl.DateTimeFormat('pl-PL', { dateStyle: 'medium', timeStyle: 'short' });
export function formatLogDate(iso: string) {
return DATE_FORMAT.format(new Date(iso));
}
function actorName(log: ActivityLog) {
const { firstName, lastName, email } = log.actor;
return [firstName, lastName].filter(Boolean).join(' ') || email;
}
/** Nazwa obiektu z szczegółów wpisu (tytuł planu, nazwa siłowni, nazwa obwodu). */
function entityName(log: ActivityLog) {
const d = log.details;
if (!d) return null;
return (d.title ?? d.name ?? d.gymName ?? null) as string | null;
}
/** Polskie etykiety dla znanych kluczy szczegółów. */
const DETAIL_LABELS: Record<string, string> = {
email: 'e-mail',
fields: 'pola',
value: 'wartość',
name: 'nazwa',
title: 'tytuł',
startDate: 'start',
targetEmail: 'zaproszono',
traineeId: 'podopieczny',
};
/** Klucze pokazywane w innych kolumnach (aktor w „Użytkownik", nazwa w „Obiekt"). */
const HIDDEN_DETAIL_KEYS = new Set(['actorId', 'title', 'name', 'gymName']);
function formatDetailValue(log: ActivityLog, key: string, value: unknown): string {
if (Array.isArray(value)) return value.map((v) => String(v)).join(', ');
if (value && typeof value === 'object') {
return Object.entries(value)
.map(([k, v]) => `${k}: ${formatDetailValue(log, k, v)}`)
.join(', ');
}
let text = String(value);
if (key === 'value' && typeof value === 'number') {
const unit =
log.action === 'weight.added' || log.action === 'weight.removed'
? ' kg'
: log.action === 'circumference.added' || log.action === 'circumference.removed'
? ' cm'
: '';
text += unit;
}
return text;
}
/** Szczegóły wpisu jako naturalny tekst: `start: 2026-08-24 · wartość: 82.5 kg`. */
function detailsText(log: ActivityLog) {
const d = log.details;
if (!d) return null;
const parts = Object.entries(d)
.filter(([k]) => !HIDDEN_DETAIL_KEYS.has(k))
.map(([k, v]) => `${DETAIL_LABELS[k] ?? k}: ${formatDetailValue(log, k, v)}`);
return parts.length > 0 ? parts.join(' · ') : null;
}
const PAGE_SIZE = 100;
export default function Logs() {
const [action, setAction] = useState('');
const [month, setMonth] = useState('');
const [limit, setLimit] = useState(PAGE_SIZE);
const query = useListSearch((s) => s.queries.logs);
const setQuery = useListSearch((s) => s.setQuery);
const hasFilters = action !== '' || month !== '';
const { data, isLoading, error } = useQuery({
queryKey: ['admin-logs', action, month, limit],
queryFn: () => {
const params = new URLSearchParams();
if (action) params.set('action', action);
if (month) {
const [y, m] = month.split('-').map(Number);
params.set('from', `${month}-01`);
params.set('to', `${month}-${String(new Date(y, m, 0).getDate()).padStart(2, '0')}`);
}
params.set('limit', String(limit));
return api<ActivityLogPage>(`/admin/logs?${params.toString()}`);
},
});
// lata do panelu selektora: z załadowanych logów + bieżący rok (nowe → stare)
const years = useMemo(() => {
const set = new Set((data?.logs ?? []).map((l) => l.createdAt.slice(0, 4)));
set.add(String(new Date().getFullYear()));
return [...set].sort().reverse();
}, [data?.logs]);
useTopbar({
title: 'Logi',
search: 'logs',
dateFilter: (
<MonthPicker
value={month}
onChange={(m) => {
setMonth(m);
setLimit(PAGE_SIZE);
}}
years={years}
/>
),
filters: [
<div key="action" className="w-48">
<Select
size="sm"
className="h-9"
aria-label="Filtruj po akcji"
value={action}
onChange={(e) => {
setAction(e.target.value);
setLimit(PAGE_SIZE);
}}
>
<option value="">Wszystkie akcje</option>
{Object.entries(ACTION_LABELS).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</Select>
</div>,
],
filterActive: hasFilters,
});
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('logs', ''), [setQuery]);
const logs = data?.logs ?? [];
const total = data?.total ?? 0;
const filtered = query
? logs.filter((l) => {
const q = query.toLowerCase();
const name = `${l.actor.firstName ?? ''} ${l.actor.lastName ?? ''}`.toLowerCase();
return l.actor.email.toLowerCase().includes(q) || (name.trim() && name.includes(q));
})
: logs;
return (
<>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
{!isLoading && !error && filtered.length === 0 && (
<EmptyState
icon={ScrollText}
title="Brak zdarzeń"
description={
query
? 'Brak wyników dla podanego zapytania.'
: hasFilters
? 'Brak zdarzeń dla wybranych filtrów.'
: 'Zmiany wprowadzane przez użytkowników pojawią się tutaj.'
}
/>
)}
{!isLoading && !error && filtered.length > 0 && (
<div className="overflow-x-auto rounded-lg border border-line bg-(image:--card-grad) shadow-card">
<table className="w-full text-[0.95rem]">
<thead>
<tr className="border-b border-line text-left text-dim">
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Data</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Użytkownik</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Akcja</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Obiekt</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Szczegóły</th>
</tr>
</thead>
<tbody>
{filtered.map((log) => (
<tr key={log.id} className="border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20">
<td className="whitespace-nowrap px-4 py-3 font-display text-dim tabular-nums">{formatLogDate(log.createdAt)}</td>
<td className="px-4 py-3">
<div className="font-semibold">{actorName(log)}</div>
<div className="text-[0.875rem] text-dim">{log.actor.email}</div>
<div className="font-mono text-[0.75rem] text-dim/70" title={log.actor.id}>
{log.actor.id}
</div>
</td>
<td className="px-4 py-3">
<Badge color={actionColor(log.action)}>{actionLabel(log.action)}</Badge>
</td>
<td className="px-4 py-3">
<div>{ENTITY_LABELS[log.entityType] ?? log.entityType}</div>
{entityName(log) && <div className="text-[0.875rem] text-dim">{entityName(log)}</div>}
</td>
<td className="px-4 py-3 text-dim">{detailsText(log) ?? '—'}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{!isLoading && !error && logs.length < total && (
<div className="mt-4 text-center">
<button
type="button"
onClick={() => setLimit((l) => l + PAGE_SIZE)}
className="text-[0.9rem] font-semibold text-accent-text hover:underline cursor-pointer"
>
Pokaż więcej ({total - logs.length} pozostało)
</button>
</div>
)}
</>
);
}

View File

@@ -0,0 +1,706 @@
import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Check, Search, X } from 'lucide-react';
import { useTopbar } from '../topbar';
import { api } from '../api/client';
import type { FocusArea, FocusChain, Gym, GymRole, User } from '../api/types';
import {
BackButton,
Badge,
Button,
Card,
ErrorText,
Field,
H3,
Input,
Label,
ListRow,
Loading,
Muted,
PageHeader,
SectionHeader,
Select,
SuccessText,
} from '../components/ui';
import { userName } from './UsersList';
import { AvailabilityEditor } from '../components/AvailabilityEditor';
import { Avatar } from '../components/Avatar';
import { formatAvailability, normalizeAvailability } from '../lib/availability';
const ROLE_LABELS: Record<string, string> = {
OWNER: 'Właściciel',
TRAINER: 'Trener',
MEMBER: 'Ćwiczący',
};
const ROLE_COLORS: Record<string, 'green' | 'blue' | 'gray'> = {
OWNER: 'green',
TRAINER: 'blue',
MEMBER: 'gray',
};
const ROLE_OPTIONS: Array<{ value: 'OWNER' | 'TRAINER' | 'MEMBER'; label: string }> = [
{ value: 'MEMBER', label: 'Ćwiczący' },
{ value: 'TRAINER', label: 'Trener' },
{ value: 'OWNER', label: 'Właściciel' },
];
const ROLE_PILL_ACTIVE: Record<string, string> = {
OWNER: 'bg-accent/15 text-accent-text border-accent/40',
TRAINER: 'bg-info/15 text-info border-info/40',
MEMBER: 'bg-dim/20 text-ink border-dim/50',
};
const ROLE_PILL_INACTIVE = 'bg-transparent text-dim border-line hover:text-ink hover:border-dim';
function RolePill({
value,
active,
onToggle,
ariaLabel,
className = '',
disabled = false,
title,
}: {
value: GymRole;
active: boolean;
onToggle: () => void;
ariaLabel: string;
className?: string;
disabled?: boolean;
title?: string;
}) {
return (
<button
type="button"
role="checkbox"
aria-checked={active}
aria-label={ariaLabel}
disabled={disabled}
title={title}
onClick={onToggle}
className={`inline-flex items-center justify-center gap-2 rounded-xl border px-3 py-2 text-[0.95rem] font-semibold cursor-pointer transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
active ? ROLE_PILL_ACTIVE[value] : ROLE_PILL_INACTIVE
} ${className}`.trim()}
>
<Check className={`h-4 w-4 ${active ? '' : 'opacity-0'}`} />
{ROLE_LABELS[value]}
</button>
);
}
function GymPicker({
gyms,
value,
onChange,
}: {
gyms: Gym[];
value: string;
onChange: (id: string) => void;
}) {
const [query, setQuery] = useState('');
const [open, setOpen] = useState(false);
const selected = gyms.find((g) => g.id === value);
const filtered = gyms.filter((g) => g.name.toLowerCase().includes(query.trim().toLowerCase()));
const close = () => {
setOpen(false);
setQuery('');
};
const handleBlur = (e: React.FocusEvent<HTMLDivElement>) => {
if (e.currentTarget.contains(e.relatedTarget as Node)) return;
close();
};
return (
<div className="relative" onBlur={handleBlur}>
<div className="flex items-center gap-2 rounded-xl border border-line bg-input px-3 focus-within:border-accent">
<Search className="h-4 w-4 shrink-0 text-dim" />
<input
role="combobox"
aria-expanded={open}
aria-label="Szukaj siłowni"
className="w-full bg-transparent py-2.5 text-[0.95rem] focus:outline-none"
placeholder={selected && !open ? '' : 'Szukaj siłowni…'}
value={open ? query : selected?.name ?? ''}
onChange={(e) => {
setQuery(e.target.value);
setOpen(true);
}}
onFocus={() => setOpen(true)}
/>
{selected && !open && (
<button
type="button"
aria-label="Wyczyść wybór siłowni"
onClick={() => onChange('')}
className="shrink-0 cursor-pointer text-dim hover:text-ink"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{open && (
<div
role="listbox"
aria-label="Lista siłowni"
className="absolute z-20 mt-1.5 max-h-56 w-full overflow-y-auto rounded-xl border border-line bg-card shadow-xl"
>
{filtered.length === 0 ? (
<div className="px-3.5 py-3 text-[0.875rem] text-dim">
{query.trim()
? `Brak siłowni o nazwie „${query.trim()}”`
: 'Użytkownik należy już do wszystkich siłowni'}
</div>
) : (
filtered.map((g) => (
<button
key={g.id}
type="button"
role="option"
aria-selected={g.id === value}
onClick={() => {
onChange(g.id);
close();
}}
className={`flex w-full cursor-pointer items-center justify-between gap-3 px-3.5 py-2.5 text-left text-[0.95rem] hover:bg-line/40 ${
g.id === value ? 'font-semibold text-accent-text' : ''
}`}
>
<span className="min-w-0 truncate">{g.name}</span>
{g.location && <span className="shrink-0 text-[0.875rem] text-dim">{g.location}</span>}
</button>
))
)}
</div>
)}
</div>
);
}
function InfoItem({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div>
<div className="text-[11px] font-bold uppercase tracking-[0.1em] text-dim">{label}</div>
<div className="mt-0.5">{children}</div>
</div>
);
}
type MuscleField = 'developMuscles' | 'canDoMuscles' | 'difficultMuscles' | 'avoidMuscles';
/* 4 niezależne grupy mięśni. Ton = kolor chipa + etykieta sekcji. */
const MUSCLE_TONES = {
develop: { active: 'bg-accent/15 text-accent-text border-accent/40', text: 'text-accent-text', label: 'Co rozwija', chainPrefix: 'do rozwoju: ' },
canDo: { active: 'bg-info/15 text-info border-info/40', text: 'text-info', label: 'Co potrafi', chainPrefix: '' },
difficult: { active: 'bg-warn/15 text-warn border-warn/40', text: 'text-warn', label: 'Co trudne', chainPrefix: '' },
avoid: { active: 'bg-danger/15 text-danger border-danger/40', text: 'text-danger', label: 'Co unikać', chainPrefix: 'unikamy: ' },
} as const;
type MuscleTone = keyof typeof MUSCLE_TONES;
/* Pary wzajemnie wykluczające się: ten sam mięsień nie może być w obu. */
const MUSCLE_CONFLICTS: Record<MuscleField, MuscleField> = {
developMuscles: 'avoidMuscles',
avoidMuscles: 'developMuscles',
canDoMuscles: 'difficultMuscles',
difficultMuscles: 'canDoMuscles',
};
function MuscleChips({
areas,
selected,
onToggle,
tone,
}: {
areas: FocusArea[];
selected: string[];
onToggle: (muscle: string) => void;
tone: MuscleTone;
}) {
const activeCls = MUSCLE_TONES[tone].active;
const inactiveCls = 'bg-transparent text-dim border-line hover:text-ink hover:border-dim';
return (
<div className="flex flex-wrap gap-2">
{areas.map((a) => {
const active = selected.includes(a.muscle);
return (
<button
key={a.muscle}
type="button"
role="checkbox"
aria-checked={active}
aria-label={`${a.name} (${MUSCLE_TONES[tone].label.toLowerCase()})`}
title={a.description ?? undefined}
onClick={() => onToggle(a.muscle)}
className={`inline-flex items-center gap-1.5 rounded-xl border px-3 py-1.5 text-[0.9rem] font-semibold cursor-pointer transition-colors ${
active ? activeCls : inactiveCls
}`}
>
{active && <Check className="h-3.5 w-3.5" />}
{a.name}
</button>
);
})}
</div>
);
}
function FocusChainView({ chain }: { chain: FocusChain }) {
const hasData = (Object.keys(MUSCLE_TONES) as MuscleTone[]).some(
(tone) => (chain[tone] ?? []).length > 0,
);
if (!hasData) return <Muted>Brak wybranych grup mięśni.</Muted>;
return (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-5">
{(Object.keys(MUSCLE_TONES) as MuscleTone[]).map((tone) => {
const entries = chain[tone] ?? [];
return (
<div key={tone}>
<H3 className={`mb-2 ${MUSCLE_TONES[tone].text}`}>{MUSCLE_TONES[tone].label}</H3>
{entries.length === 0 ? (
<span className="text-[0.875rem] text-dim">—</span>
) : (
<div className="flex flex-col gap-2.5">
{entries.map((e) => (
<div key={e.muscle}>
<div className="text-[0.95rem] font-semibold">{e.name}</div>
<div className="mt-0.5 text-[0.875rem] text-dim">
{(e.exercises ?? []).length > 0
? `${MUSCLE_TONES[tone].chainPrefix}${(e.exercises ?? [])
.map((x) => x.name)
.join(', ')}`
: 'brak w aktywnym planie'}
</div>
</div>
))}
</div>
)}
</div>
);
})}
</div>
);
}
function UserEditForm({ user, onSaved }: { user: User; onSaved: () => void }) {
const [form, setForm] = useState({
email: user.email,
firstName: user.firstName ?? '',
lastName: user.lastName ?? '',
age: user.age?.toString() ?? '',
heightCm: user.heightCm?.toString() ?? '',
phone: user.phone ?? '',
isAdmin: user.isAdmin,
password: '',
availability: normalizeAvailability(user.availability),
developMuscles: user.developMuscles ?? [],
canDoMuscles: user.canDoMuscles ?? [],
difficultMuscles: user.difficultMuscles ?? [],
avoidMuscles: user.avoidMuscles ?? [],
});
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [saved, setSaved] = useState(false);
const { data: areasData } = useQuery({
queryKey: ['focus-areas'],
queryFn: () => api<{ focusAreas: FocusArea[] }>('/admin/focus-areas'),
});
const areas = areasData?.focusAreas ?? [];
const toggleMuscle = (key: MuscleField) => (muscle: string) =>
setForm((f) => {
const list = f[key];
const adding = !list.includes(muscle);
const conflict = MUSCLE_CONFLICTS[key];
return {
...f,
[key]: adding ? [...list, muscle] : list.filter((m) => m !== muscle),
// a muscle cannot be both developed and avoided, nor both can-do and difficult
...(adding ? { [conflict]: f[conflict].filter((m) => m !== muscle) } : {}),
};
});
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setBusy(true);
try {
await api(`/admin/users/${user.id}`, {
method: 'PATCH',
body: {
email: form.email,
firstName: form.firstName || null,
lastName: form.lastName || null,
age: form.age ? parseInt(form.age) : null,
heightCm: form.heightCm ? parseFloat(form.heightCm) : null,
phone: form.phone || null,
isAdmin: form.isAdmin,
password: form.password || undefined,
availability: form.availability.some((d) => d != null) ? form.availability : null,
developMuscles: form.developMuscles,
canDoMuscles: form.canDoMuscles,
difficultMuscles: form.difficultMuscles,
avoidMuscles: form.avoidMuscles,
},
});
setSaved(true);
onSaved();
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
return (
<form onSubmit={submit}>
<section>
<H3>Konto</H3>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="E-mail">
<Input
type="email"
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
required
/>
</Field>
<Field label="Administrator">
<Select
value={form.isAdmin ? '1' : '0'}
onChange={(e) => setForm({ ...form, isAdmin: e.target.value === '1' })}
>
<option value="0">Nie</option>
<option value="1">Tak</option>
</Select>
</Field>
<Field label="Nowe hasło (opcjonalnie)">
<Input
type="password"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
placeholder="••••••••"
/>
</Field>
</div>
</section>
<div className="my-5 border-t border-line" />
<section>
<H3>Dane osobowe</H3>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="Imię">
<Input value={form.firstName} onChange={(e) => setForm({ ...form, firstName: e.target.value })} />
</Field>
<Field label="Nazwisko">
<Input value={form.lastName} onChange={(e) => setForm({ ...form, lastName: e.target.value })} />
</Field>
<Field label="Wiek">
<Input type="number" value={form.age} onChange={(e) => setForm({ ...form, age: e.target.value })} />
</Field>
<Field label="Wzrost (cm)">
<Input type="number" value={form.heightCm} onChange={(e) => setForm({ ...form, heightCm: e.target.value })} />
</Field>
<Field label="Telefon">
<Input value={form.phone} placeholder="+48 600 000 000" onChange={(e) => setForm({ ...form, phone: e.target.value })} />
</Field>
</div>
</section>
<div className="my-5 border-t border-line" />
<section>
<H3>Profil treningowy</H3>
<Field label="Dostępność (dzień tygodnia + przedział godzin)">
<AvailabilityEditor
value={form.availability}
onChange={(availability) => setForm({ ...form, availability })}
/>
</Field>
<Field label={MUSCLE_TONES.develop.label}>
<MuscleChips
areas={areas}
selected={form.developMuscles}
onToggle={toggleMuscle('developMuscles')}
tone="develop"
/>
</Field>
<Field label={MUSCLE_TONES.canDo.label}>
<MuscleChips
areas={areas}
selected={form.canDoMuscles}
onToggle={toggleMuscle('canDoMuscles')}
tone="canDo"
/>
</Field>
<Field label={MUSCLE_TONES.difficult.label}>
<MuscleChips
areas={areas}
selected={form.difficultMuscles}
onToggle={toggleMuscle('difficultMuscles')}
tone="difficult"
/>
</Field>
<Field label={MUSCLE_TONES.avoid.label}>
<MuscleChips
areas={areas}
selected={form.avoidMuscles}
onToggle={toggleMuscle('avoidMuscles')}
tone="avoid"
/>
</Field>
</section>
{error && <ErrorText>{error}</ErrorText>}
{saved && !error && <SuccessText>Zapisano zmiany.</SuccessText>}
<div className="mt-5 flex justify-end">
<Button type="submit" disabled={busy}>
{busy ? 'Zapisywanie…' : 'Zapisz'}
</Button>
</div>
</form>
);
}
export default function UserDetail() {
useTopbar({ title: 'Użytkownicy' });
const { id } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { data, isLoading, error } = useQuery({
queryKey: ['admin-users'],
queryFn: () => api<{ users: User[] }>('/admin/users'),
});
const { data: gymsData } = useQuery({
queryKey: ['gyms'],
queryFn: () => api<{ gyms: Gym[] }>('/admin/gyms'),
});
const { data: chainData } = useQuery({
queryKey: ['focus-chain', id],
queryFn: () => api<FocusChain>(`/admin/users/${id}/focus-chain`),
enabled: !!id,
});
const chain = chainData;
const user = data?.users.find((u) => u.id === id);
const gyms = gymsData?.gyms ?? [];
const [memGym, setMemGym] = useState('');
const [memRoles, setMemRoles] = useState<GymRole[]>(['MEMBER']);
const refresh = () => queryClient.invalidateQueries({ queryKey: ['admin-users'] });
const remove = async () => {
if (!user) return;
if (!confirm('Usunąć użytkownika? Jego plany i sesje zostaną usunięte.')) return;
try {
await api(`/admin/users/${user.id}`, { method: 'DELETE' });
await refresh();
navigate('/users');
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
const addMembership = async () => {
if (!user || !memGym || memRoles.length === 0) return;
try {
await api(`/admin/users/${user.id}/memberships`, {
method: 'POST',
body: { gymId: memGym, roles: memRoles },
});
setMemRoles(['MEMBER']);
await refresh();
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
const toggleAddRole = (role: GymRole) => {
setMemRoles((prev) => (prev.includes(role) ? prev.filter((r) => r !== role) : [...prev, role]));
};
const removeMembership = async (gymId: string) => {
if (!user) return;
try {
await api(`/admin/users/${user.id}/memberships/${gymId}`, { method: 'DELETE' });
await refresh();
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
const toggleMembershipRole = async (gymId: string, role: GymRole) => {
if (!user) return;
const current = user.memberships?.find((m) => m.gymId === gymId)?.roles ?? [];
const next = current.includes(role) ? current.filter((r) => r !== role) : [...current, role];
if (next.length === 0) return;
try {
await api(`/admin/users/${user.id}/memberships/${gymId}`, {
method: 'PATCH',
body: { roles: next },
});
await refresh();
} catch (err) {
alert(err instanceof Error ? err.message : 'Błąd');
}
};
if (isLoading) return <Loading />;
if (error) return <ErrorText>Błąd: {(error as Error).message}</ErrorText>;
if (!user) {
return (
<>
<BackButton to="/users" className="mb-4" />
<ErrorText>Nie znaleziono użytkownika.</ErrorText>
</>
);
}
const memberships = user.memberships ?? [];
const availableGyms = gyms.filter((g) => !memberships.some((m) => m.gymId === g.id));
return (
<>
<PageHeader
title={userName(user)}
badge={
<span className="flex flex-wrap items-center gap-1.5">
<Avatar name={userName(user)} size={26} />
{user.isAdmin && <Badge color="blue">Admin</Badge>}
{memberships.flatMap((m) =>
m.roles.map((r) => (
<Badge key={`${m.gymId}-${r}`} color={ROLE_COLORS[r]}>
{ROLE_LABELS[r]}: {m.gym.name}
</Badge>
)),
)}
</span>
}
actions={
<>
<Button variant="danger" onClick={remove}>
Usuń użytkownika
</Button>
<BackButton to="/users" />
</>
}
/>
<Card>
<SectionHeader title="Dane" />
<div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
<InfoItem label="E-mail">{user.email}</InfoItem>
<InfoItem label="Utworzony">{new Date(user.createdAt).toLocaleDateString('pl-PL')}</InfoItem>
<InfoItem label="Wiek">{user.age ?? '—'}</InfoItem>
<InfoItem label="Wzrost (cm)">{user.heightCm ?? '—'}</InfoItem>
<InfoItem label="Telefon">{user.phone ?? '—'}</InfoItem>
</div>
{formatAvailability(user.availability) && (
<div className="mt-4 border-t border-line pt-4">
<InfoItem label="Dostępność">{formatAvailability(user.availability)}</InfoItem>
</div>
)}
</Card>
<Card>
<SectionHeader
title="Ciąg przyczynowo-skutkowy"
description="Ćwiczenia z aktywnego planu w kontekście priorytetów i wykluczeń."
/>
{chain ? <FocusChainView chain={chain} /> : <Loading />}
</Card>
<Card>
<SectionHeader title="Edycja" />
<UserEditForm
key={user.id}
user={user}
onSaved={() => {
void refresh();
}}
/>
</Card>
<Card>
<SectionHeader
title="Członkostwa w siłowniach"
actions={memberships.length > 0 ? <Badge>{memberships.length}</Badge> : undefined}
/>
{memberships.length > 0 ? (
<div className="divide-y divide-line">
{memberships.map((m) => (
<ListRow
key={m.gymId}
title={m.gym.name}
meta={m.gym.location || undefined}
actions={
<Button variant="danger" size="sm" onClick={() => removeMembership(m.gymId)}>
Usuń
</Button>
}
>
<div className="flex w-full flex-wrap gap-2 pt-1">
{ROLE_OPTIONS.map((r) => (
<RolePill
key={r.value}
value={r.value}
active={m.roles.includes(r.value)}
onToggle={() => toggleMembershipRole(m.gymId, r.value)}
ariaLabel={`${r.label} w ${m.gym.name}`}
className="min-w-0 flex-1"
disabled={m.roles.length === 1 && m.roles.includes(r.value)}
title={
m.roles.length === 1 && m.roles.includes(r.value)
? 'Aby usunąć członkostwo użyj przycisku „Usuń”'
: undefined
}
/>
))}
</div>
</ListRow>
))}
</div>
) : (
<Muted>Brak członkostw.</Muted>
)}
<div className="mt-4 border-t border-line pt-4">
<H3>Dodaj członkostwo</H3>
<div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
<div>
<Label>Siłownia</Label>
<GymPicker gyms={availableGyms} value={memGym} onChange={setMemGym} />
</div>
<div>
<Label>Role</Label>
<div className="flex flex-wrap gap-2">
{ROLE_OPTIONS.map((r) => (
<RolePill
key={r.value}
value={r.value}
active={memRoles.includes(r.value)}
onToggle={() => toggleAddRole(r.value)}
ariaLabel={`Dodaj: ${r.label}`}
className="min-w-0 flex-1"
/>
))}
</div>
</div>
</div>
<Button
variant="secondary"
onClick={addMembership}
disabled={!memGym || memRoles.length === 0}
className="mt-3"
>
Dodaj członkostwo
</Button>
</div>
</Card>
</>
);
}

View File

@@ -0,0 +1,91 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../api/client';
import { BackButton, Button, Card, ErrorText, Field, H1, Input, Select } from '../components/ui';
import { useTopbar } from '../topbar';
export default function UserForm() {
useTopbar({ title: 'Użytkownicy' });
const navigate = useNavigate();
const [form, setForm] = useState({
email: '',
password: '',
firstName: '',
lastName: '',
age: '',
isAdmin: false,
});
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setBusy(true);
try {
const data = await api<{ user: { id: string } }>('/admin/users', {
method: 'POST',
body: {
email: form.email,
password: form.password,
firstName: form.firstName || undefined,
lastName: form.lastName || undefined,
age: form.age ? parseInt(form.age) : undefined,
isAdmin: form.isAdmin,
},
});
navigate(`/users/${data.user.id}`);
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd');
} finally {
setBusy(false);
}
};
return (
<>
<BackButton to="/users" className="mb-4" />
<H1>Nowy użytkownik</H1>
<Card>
<form onSubmit={submit}>
<div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
<Field label="E-mail">
<Input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required />
</Field>
<Field label="Hasło (min. 8)">
<Input
type="password"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
minLength={8}
required
/>
</Field>
<Field label="Imię">
<Input value={form.firstName} onChange={(e) => setForm({ ...form, firstName: e.target.value })} />
</Field>
<Field label="Nazwisko">
<Input value={form.lastName} onChange={(e) => setForm({ ...form, lastName: e.target.value })} />
</Field>
<Field label="Wiek">
<Input type="number" value={form.age} onChange={(e) => setForm({ ...form, age: e.target.value })} />
</Field>
<Field label="Administrator">
<Select
value={form.isAdmin ? '1' : '0'}
onChange={(e) => setForm({ ...form, isAdmin: e.target.value === '1' })}
>
<option value="0">Nie</option>
<option value="1">Tak</option>
</Select>
</Field>
</div>
{error && <ErrorText>{error}</ErrorText>}
<Button type="submit" disabled={busy}>
{busy ? 'Tworzenie…' : 'Utwórz użytkownika'}
</Button>
</form>
</Card>
</>
);
}

View File

@@ -0,0 +1,94 @@
import { useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Plus, Users as UsersIcon } from 'lucide-react';
import { api } from '../api/client';
import type { User } from '../api/types';
import { Badge, Card, EmptyState, ErrorText, ListRow, Loading } from '../components/ui';
import { Avatar } from '../components/Avatar';
import { useListSearch } from '../store/list-search';
import { useTopbar } from '../topbar';
export function userName(u: User) {
return u.firstName || u.lastName ? `${u.firstName ?? ''} ${u.lastName ?? ''}`.trim() : u.email;
}
export default function UsersList() {
useTopbar({
title: 'Użytkownicy',
search: 'users',
actions: [{ label: 'Nowy użytkownik', to: '/users/new', icon: Plus }],
});
const navigate = useNavigate();
const { data, isLoading, error } = useQuery({
queryKey: ['admin-users'],
queryFn: () => api<{ users: User[] }>('/admin/users'),
});
const query = useListSearch((s) => s.queries.users);
const setQuery = useListSearch((s) => s.setQuery);
const users = data?.users ?? [];
const filtered = query
? users.filter((u) =>
[u.email, u.firstName, u.lastName]
.filter(Boolean)
.some((s) => s!.toLowerCase().includes(query.toLowerCase())),
)
: users;
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('users', ''), [setQuery]);
return (
<>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
<Card>
<div className="divide-y divide-line">
{filtered.map((u) => (
<div
key={u.id}
className="cursor-pointer transition-colors hover:bg-line/20"
onClick={() => navigate(`/users/${u.id}`)}
>
<ListRow
title={
<span className="flex items-center gap-2.5">
<Avatar name={userName(u)} size={28} />
<Link to={`/users/${u.id}`} className="hover:text-accent-text">
{userName(u)}
</Link>
</span>
}
meta={
<>
{u.email}
{u.age != null ? ` · wiek: ${u.age}` : ''}
</>
}
actions={
<>
{u.isAdmin && <Badge color="blue">Admin</Badge>}
<Badge color="gray">{u.memberships?.length ?? 0} sił.</Badge>
</>
}
/>
</div>
))}
</div>
</Card>
{!isLoading && !error && filtered.length === 0 && (
<Card>
<EmptyState
icon={UsersIcon}
title="Brak użytkowników"
description={query ? 'Brak wyników dla podanego zapytania.' : 'Brak użytkowników.'}
/>
</Card>
)}
</>
);
}

View File

@@ -0,0 +1,343 @@
import { useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Download, ShieldCheck } from 'lucide-react';
import { api, getAccessToken } from '../api/client';
import { API_BASE } from '../config';
import type { ClaimStatus, GymClaim } from '../api/types';
import {
BackButton,
Badge,
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
ListRow,
Loading,
Muted,
PageHeader,
SectionHeader,
Textarea,
} from '../components/ui';
import type { BadgeColor } from '../components/ui';
import { Avatar } from '../components/Avatar';
import { formatAvailability } from '../lib/availability';
import { useTopbar } from '../topbar';
const STATUS_META: Record<ClaimStatus, { label: string; color: BadgeColor }> = {
PENDING: { label: 'Oczekuje', color: 'yellow' },
APPROVED: { label: 'Zatwierdzony', color: 'green' },
REJECTED: { label: 'Odrzucony', color: 'red' },
};
function claimTitle(claim: GymClaim) {
return claim.gym?.name ?? claim.gymName ?? '—';
}
function claimTypeLabel(claim: GymClaim) {
return claim.type === 'verification' ? 'Weryfikacja' : 'Nowa siłownia';
}
function applicantName(claim: GymClaim) {
const { firstName, lastName, email } = claim.user;
return [firstName, lastName].filter(Boolean).join(' ') || email;
}
/** Pobranie pliku po tokenie (nie po cookie): fetch + Bearer → blob → tymczasowy <a download>. */
async function downloadFile(path: string, filename: string) {
const token = getAccessToken();
const res = await fetch(`${API_BASE}${path}`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
function InfoItem({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div>
<div className="text-[11px] font-bold uppercase tracking-[0.1em] text-dim">{label}</div>
<div className="mt-0.5">{children}</div>
</div>
);
}
export default function VerificationsList() {
useTopbar({ title: 'Weryfikacje' });
const navigate = useNavigate();
const { data, isLoading, error } = useQuery({
queryKey: ['gyms-claims'],
queryFn: () => api<{ claims: GymClaim[] }>('/admin/gyms/claims'),
});
const claims = data?.claims ?? [];
return (
<>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
<Card>
<div className="divide-y divide-line">
{claims.map((c) => (
<div
key={c.id}
className="cursor-pointer transition-colors hover:bg-line/20"
onClick={() => navigate(`/verifications/${c.id}`)}
>
<ListRow
title={
<span className="flex items-center gap-2.5">
<Avatar name={applicantName(c)} size={28} />
<Link
to={`/verifications/${c.id}`}
className="hover:text-accent-text"
onClick={(e) => e.stopPropagation()}
>
{claimTitle(c)}
</Link>
</span>
}
meta={`${applicantName(c)} · ${new Date(c.createdAt).toLocaleDateString('pl-PL')}`}
actions={
<>
<Badge color={c.type === 'verification' ? 'blue' : 'gray'}>{claimTypeLabel(c)}</Badge>
{c.documentCount ? <Badge color="gray">{c.documentCount} dok.</Badge> : null}
<Badge color={STATUS_META[c.status].color}>{STATUS_META[c.status].label}</Badge>
</>
}
/>
</div>
))}
</div>
</Card>
{!isLoading && !error && claims.length === 0 && (
<Card>
<EmptyState icon={ShieldCheck} title="Brak wniosków" description="Brak wniosków o siłownie." />
</Card>
)}
</>
);
}
export function VerificationDetail() {
useTopbar({ title: 'Weryfikacje' });
const { id } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { data, isLoading, error } = useQuery({
queryKey: ['gyms-claims', id],
queryFn: () => api<{ claim: GymClaim }>(`/admin/gyms/claims/${id}`),
});
const [confirmOpen, setConfirmOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [reason, setReason] = useState('');
const [actionError, setActionError] = useState('');
const claim = data?.claim;
const invalidate = () =>
Promise.all([
queryClient.invalidateQueries({ queryKey: ['gyms-claims'] }),
queryClient.invalidateQueries({ queryKey: ['gyms'] }),
]);
const approve = async () => {
if (!claim) return;
setBusy(true);
setActionError('');
try {
await api(`/admin/gyms/claims/${claim.id}/approve`, { method: 'POST' });
setConfirmOpen(false);
await invalidate();
navigate('/verifications');
} catch (e) {
setActionError(e instanceof Error ? e.message : 'Błąd');
} finally {
setBusy(false);
}
};
const reject = async () => {
if (!claim) return;
setBusy(true);
setActionError('');
try {
await api(`/admin/gyms/claims/${claim.id}/reject`, {
method: 'POST',
body: { reason: reason || undefined },
});
await invalidate();
navigate('/verifications');
} catch (e) {
setActionError(e instanceof Error ? e.message : 'Błąd');
} finally {
setBusy(false);
}
};
const download = async (docId: string, name: string) => {
if (!claim) return;
try {
await downloadFile(`/admin/gyms/claims/${claim.id}/documents/${docId}`, name);
} catch (e) {
alert(e instanceof Error ? e.message : 'Błąd pobierania');
}
};
if (isLoading) return <Loading />;
if (error) return <ErrorText>Błąd: {(error as Error).message}</ErrorText>;
if (!claim) {
return (
<>
<BackButton to="/verifications" className="mb-4" />
<ErrorText>Nie znaleziono wniosku.</ErrorText>
</>
);
}
const isPending = claim.status === 'PENDING';
return (
<>
<PageHeader
title={claimTitle(claim)}
badge={
<>
<Badge color={claim.type === 'verification' ? 'blue' : 'gray'}>{claimTypeLabel(claim)}</Badge>
<Badge color={STATUS_META[claim.status].color}>{STATUS_META[claim.status].label}</Badge>
</>
}
actions={<BackButton to="/verifications" />}
/>
<Card>
<SectionHeader title="Dane wniosku" />
<div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
{claim.type === 'verification' ? (
<>
<InfoItem label="Siłownia">
{claim.gym?.name ?? '—'}
{claim.gym && (
<span className="ml-2 inline-flex gap-1.5">
<Badge color={claim.gym.kind === 'VIRTUAL' ? 'blue' : 'gray'}>
{claim.gym.kind === 'VIRTUAL' ? 'Wirtualna' : 'Realna'}
</Badge>
{claim.gym.isPrivate && <Badge color="gray">Prywatna</Badge>}
</span>
)}
</InfoItem>
<InfoItem label="Adres (nadpisuje lokalizację)">{claim.address || '—'}</InfoItem>
</>
) : (
<>
<InfoItem label="Nazwa siłowni">{claim.gymName || '—'}</InfoItem>
<InfoItem label="Lokalizacja">{claim.gymLocation || '—'}</InfoItem>
<InfoItem label="Dostępność">{formatAvailability(claim.gymAvailability) || '—'}</InfoItem>
<InfoItem label="Pojemność">{claim.gymCapacity ?? '—'}</InfoItem>
</>
)}
<InfoItem label="Opis">{claim.description || '—'}</InfoItem>
<InfoItem label="Nazwa firmy">{claim.companyName || '—'}</InfoItem>
<InfoItem label="NIP">{claim.nip || '—'}</InfoItem>
<InfoItem label="Telefon">{claim.phone || '—'}</InfoItem>
<InfoItem label="E-mail">{claim.email || '—'}</InfoItem>
</div>
</Card>
<Card>
<SectionHeader title="Wnioskodawca" />
<div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
<InfoItem label="Imię i nazwisko">
<span className="flex items-center gap-2.5">
<Avatar name={applicantName(claim)} size={28} />
{applicantName(claim)}
</span>
</InfoItem>
<InfoItem label="E-mail">{claim.user.email}</InfoItem>
{claim.user.phone != null && <InfoItem label="Telefon">{claim.user.phone}</InfoItem>}
</div>
</Card>
<Card>
<SectionHeader title="Dokumenty" />
{claim.documents.length === 0 ? (
<Muted className="text-[0.875rem]">Brak załączonych dokumentów.</Muted>
) : (
<div className="divide-y divide-line">
{claim.documents.map((d) => (
<ListRow
key={d.id}
title={d.originalName}
actions={
<Button size="sm" variant="secondary" onClick={() => void download(d.id, d.originalName)}>
<Download className="h-4 w-4" />
Pobierz
</Button>
}
/>
))}
</div>
)}
</Card>
{claim.status === 'REJECTED' && claim.rejectReason && (
<Card>
<SectionHeader title="Powód odrzucenia" />
<p className="text-[0.95rem]">{claim.rejectReason}</p>
</Card>
)}
{isPending && (
<Card>
<SectionHeader title="Rozstrzygnięcie" />
<div className="flex flex-wrap items-center gap-3">
<Button onClick={() => setConfirmOpen(true)} disabled={busy}>
<ShieldCheck className="h-4 w-4" />
Zatwierdź
</Button>
<Button variant="danger" onClick={reject} disabled={busy}>
{busy ? 'Odrzucanie…' : 'Odrzuć'}
</Button>
</div>
<div className="mt-4">
<Field label="Powód odrzucenia (opcjonalny)">
<Textarea
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="np. Brak potwierdzenia adresu prowadzenia siłowni"
/>
</Field>
</div>
{actionError && <ErrorText>{actionError}</ErrorText>}
</Card>
)}
<ConfirmDialog
open={confirmOpen}
onClose={() => setConfirmOpen(false)}
onConfirm={() => void approve()}
title="Zatwierdzić wniosek?"
description={
claim.type === 'verification'
? 'Siłownia stanie się realną (REAL) i publiczną, a wnioskodawca otrzyma rolę właściciela.'
: 'Zostanie utworzona nowa realna siłownia, a wnioskodawca otrzyma rolę właściciela.'
}
confirmLabel="Zatwierdź"
busy={busy}
/>
</>
);
}

65
admin/src/store/auth.ts Normal file
View File

@@ -0,0 +1,65 @@
import { create } from 'zustand';
import { API_BASE } from '../config';
import { api, setAccessToken } from '../api/client';
import type { User } from '../api/types';
interface AuthState {
user: User | null;
ready: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
init: () => Promise<void>;
}
export const useAuth = create<AuthState>((set) => ({
user: null,
ready: false,
login: async (email, password) => {
const data = await api<{ user: User; accessToken: string }>('/auth/login', {
method: 'POST',
body: { email, password },
});
if (!data.user.isAdmin) {
setAccessToken(null);
throw new Error('Dostęp tylko dla administratorów');
}
setAccessToken(data.accessToken);
set({ user: data.user });
},
logout: async () => {
try {
await api('/auth/logout', { method: 'POST' });
} catch {
// ignore
}
setAccessToken(null);
set({ user: null });
},
init: async () => {
try {
const refreshRes = await fetch(`${API_BASE}/auth/refresh`, {
method: 'POST',
credentials: 'include',
});
if (refreshRes.ok) {
const data = await refreshRes.json();
setAccessToken(data.accessToken);
const me = await api<{ user: User }>('/me');
if (me.user.isAdmin) {
set({ user: me.user, ready: true });
return;
}
}
} catch {
// no session
}
set({ user: null, ready: true });
},
}));
window.addEventListener('fitos:logout', () => {
useAuth.setState({ user: null });
});

View File

@@ -0,0 +1,26 @@
import { create } from 'zustand';
export type SearchableSection = 'gyms' | 'users' | 'focus-areas' | 'exercises' | 'equipment' | 'logs';
const EMPTY_QUERIES: Record<SearchableSection, string> = {
gyms: '',
users: '',
'focus-areas': '',
exercises: '',
equipment: '',
logs: '',
};
interface ListSearchState {
queries: Record<SearchableSection, string>;
setQuery: (section: SearchableSection, query: string) => void;
}
/**
* Zapytania wyszukiwarki per sekcja (każda podstrona listy ma własne).
* Inputy żyją w menu kontekstowym (Layout), a aktywne strony list filtrują po nich.
*/
export const useListSearch = create<ListSearchState>((set) => ({
queries: EMPTY_QUERIES,
setQuery: (section, query) => set((s) => ({ queries: { ...s.queries, [section]: query } })),
}));

43
admin/src/store/theme.ts Normal file
View File

@@ -0,0 +1,43 @@
import { create } from 'zustand';
export type Theme = 'dark' | 'light';
const STORAGE_KEY = 'fitos-theme';
function currentTheme(): Theme {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved === 'light' || saved === 'dark') return saved;
} catch {
// ignore
}
return 'dark';
}
function apply(theme: Theme) {
document.documentElement.classList.toggle('light', theme === 'light');
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.setAttribute('content', theme === 'light' ? '#f7f4f0' : '#141210');
}
interface ThemeState {
theme: Theme;
toggle: () => void;
}
const initial = currentTheme();
apply(initial);
export const useTheme = create<ThemeState>((set, get) => ({
theme: initial,
toggle: () => {
const next: Theme = get().theme === 'dark' ? 'light' : 'dark';
try {
localStorage.setItem(STORAGE_KEY, next);
} catch {
// ignore
}
apply(next);
set({ theme: next });
},
}));

276
admin/src/styles.css Normal file
View File

@@ -0,0 +1,276 @@
@import 'tailwindcss';
@import 'tw-animate-css';
/* ===== FitOS „Ember” — ciepły grafit + koral. Dark (domyślny). ===== */
:root {
color-scheme: dark;
--bg: #141210;
--bg-card: #1c1917;
--bg-input: #0f0d0b;
--line: #2b2620;
--text: #f2ede6;
--text-dim: #a1968a;
--accent: #ff6b4a;
--accent-dark: #f0542f;
--accent-ink: #1c0d06;
--accent-text: #ff7e61;
--danger: #e5484d;
--warn: #e8b04a;
--info: #63b3e4;
/* wykończenie powierzchni */
--shadow: 0 1px 0 color-mix(in srgb, var(--text) 4%, transparent) inset;
--card-grad: linear-gradient(180deg, color-mix(in srgb, var(--text) 2.5%, var(--bg-card)), var(--bg-card) 60%);
--glow: 0 8px 40px -16px color-mix(in srgb, var(--accent) 40%, transparent);
--ambient: radial-gradient(720px 340px at 50% -80px, color-mix(in srgb, var(--accent) 8%, transparent), transparent 70%);
--grain-opacity: 0.028;
/* ruch */
--dur-1: 120ms;
--dur-2: 180ms;
--dur-3: 240ms;
--ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1);
/* komponenty */
--btn-grad: linear-gradient(180deg, color-mix(in srgb, var(--accent) 88%, #fff), var(--accent-dark));
--btn-shadow:
0 3px 14px -6px color-mix(in srgb, var(--accent) 65%, transparent),
inset 0 1px 0 color-mix(in srgb, #fff 28%, transparent);
--inset-shadow: inset 0 1px 3px rgb(0 0 0 / 0.12);
--progress-grad: linear-gradient(90deg, color-mix(in srgb, var(--accent) 65%, transparent), var(--accent));
--mark-grad: linear-gradient(160deg, color-mix(in srgb, var(--accent) 82%, #fff), var(--accent-dark));
--mark-shadow: 0 2px 10px -3px color-mix(in srgb, var(--accent) 60%, transparent);
--nav-bar-grad: linear-gradient(180deg, var(--accent), var(--accent-dark));
/* shadcn tokens — mapped onto the palette above */
--background: var(--bg);
--foreground: var(--text);
--card: var(--bg-card);
--card-foreground: var(--text);
--primary: var(--accent);
--primary-foreground: var(--accent-ink);
--secondary: var(--bg-input);
--secondary-foreground: var(--text);
--muted: var(--bg-input);
--muted-foreground: var(--text-dim);
--destructive: var(--danger);
--border: var(--line);
--input: var(--line);
--ring: var(--accent);
--radius: 0.875rem;
}
/* Light theme — enabled by .light on <html> */
.light {
color-scheme: light;
--bg: #f7f4f0;
--bg-card: #ffffff;
--bg-input: #efe9e2;
--line: #e0d7cb;
--text: #211b15;
--text-dim: #6f6558;
--accent: #f4572e;
--accent-dark: #dd4620;
--accent-ink: #1c0d06;
--accent-text: #c43a15;
--danger: #d92d20;
--warn: #b45309;
--info: #0369a1;
--shadow: 0 1px 2px rgb(33 27 21 / 0.05), 0 12px 32px -18px rgb(33 27 21 / 0.18);
--card-grad: linear-gradient(180deg, #ffffff, color-mix(in srgb, var(--bg) 45%, #ffffff) 140%);
--glow: 0 8px 36px -18px color-mix(in srgb, var(--accent) 32%, transparent);
--ambient: radial-gradient(720px 340px at 50% -80px, color-mix(in srgb, var(--accent) 6%, transparent), transparent 70%);
--grain-opacity: 0.05;
}
/* Map design tokens to Tailwind utilities (bg-card, text-dim, border-line, font-display, shadow-card, ...) */
@theme inline {
--font-sans: 'Manrope', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--font-display: 'Space Grotesk', 'Manrope', system-ui, sans-serif;
--color-bg: var(--bg);
--color-card: var(--bg-card);
--color-input: var(--bg-input);
--color-line: var(--line);
--color-ink: var(--text);
--color-dim: var(--text-dim);
--color-accent: var(--accent);
--color-accent-dark: var(--accent-dark);
--color-accent-ink: var(--accent-ink);
--color-accent-text: var(--accent-text);
--color-danger: var(--danger);
--color-warn: var(--warn);
--color-info: var(--info);
/* shadcn color utilities (bg-background, text-foreground, border-border, ...) */
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-ring: var(--ring);
--shadow-card: var(--shadow);
--shadow-glow: var(--glow);
--radius-lg: var(--radius);
--radius-md: calc(var(--radius) - 4px);
--radius-sm: calc(var(--radius) - 6px);
}
/* Top menu: zawartość grupy rozwijana od ikonki w lewo, w jednej linii */
@keyframes topbar-expand {
from {
opacity: 0;
transform: translateX(10px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.topbar-expand {
animation: topbar-expand 150ms ease-out;
}
/* Pulsujący wskaźnik „na żywo” (live-dot) */
@keyframes live-ping {
0% {
transform: scale(0.5);
opacity: 0.8;
}
80%,
100% {
transform: scale(1.5);
opacity: 0;
}
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 99px;
background: var(--accent);
position: relative;
display: inline-block;
flex: none;
}
.live-dot::after {
content: '';
position: absolute;
inset: -4px;
border-radius: 99px;
border: 1.5px solid var(--accent);
opacity: 0.7;
animation: live-ping 1.8s cubic-bezier(0, 0, 0.2, 1) infinite;
}
/* Skeleton shimmer */
@keyframes shimmer {
from {
background-position: 200% 0;
}
to {
background-position: -200% 0;
}
}
.skeleton-shimmer {
background: linear-gradient(
90deg,
var(--bg-input) 25%,
color-mix(in srgb, var(--text) 7%, var(--bg-input)) 50%,
var(--bg-input) 75%
);
background-size: 200% 100%;
animation: shimmer 1.6s linear infinite;
}
@layer base {
html {
background-color: var(--bg);
}
body {
margin: 0;
font-family: var(--font-sans);
background: transparent;
color: var(--text);
font-size: 15px;
-webkit-font-smoothing: antialiased;
transition: color var(--dur-3) ease;
}
/* ciepła poświata u góry widoku */
body::before {
content: '';
position: fixed;
top: 0;
left: 0;
right: 0;
height: 420px;
background: var(--ambient);
pointer-events: none;
z-index: -1;
}
/* ziarno — przełamuje płaskie powierzchnie */
body::after {
content: '';
position: fixed;
inset: 0;
pointer-events: none;
z-index: 60;
opacity: var(--grain-opacity);
mix-blend-mode: overlay;
background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='140' height='140' filter='url(%23n)'/%3E%3C/svg%3E");
}
h1,
h2,
h3 {
font-family: var(--font-display);
}
a {
color: var(--accent-text);
text-decoration: none;
}
::selection {
background: color-mix(in srgb, var(--accent) 32%, transparent);
}
:focus-visible {
outline: 2px solid color-mix(in srgb, var(--accent) 60%, transparent);
outline-offset: 2px;
}
* {
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-thumb {
background: var(--line);
border-radius: 99px;
border: 2px solid var(--bg);
}
::-webkit-scrollbar-track {
background: transparent;
}
}

View File

@@ -0,0 +1,75 @@
import { useEffect, useRef } from 'react';
import type { ReactNode } from 'react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '../lib/utils';
interface GroupButtonProps {
icon: LucideIcon;
/** aria-label ikony (stabilny selektor e2e). */
label: string;
/** Znacznik aktywności (kropka przy ikonie). */
active?: boolean;
open: boolean;
onToggle: () => void;
children: ReactNode;
}
/**
* Grupa menu kontekstowego: ikona-guzik (+ opcjonalna kropka aktywności).
* Panel: <lg — rozwijany od ikonki w lewo (akordeon, jedna grupa naraz);
* na telefonie absolutny nad paskiem (w górę); lg+ — treść zawsze inline
* (przycisk grupy ukryty).
* Zamykanie: Escape, klik poza grupą (klik w inną grupę ją przełącza).
*/
export function GroupButton({ icon: Icon, label, active, open, onToggle, children }: GroupButtonProps) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onToggle();
};
const onClickOutside = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) onToggle();
};
document.addEventListener('keydown', onKey);
document.addEventListener('mousedown', onClickOutside);
return () => {
document.removeEventListener('keydown', onKey);
document.removeEventListener('mousedown', onClickOutside);
};
}, [open, onToggle]);
return (
<div ref={ref} className="relative flex items-center gap-2">
{/* lg+ treść grupy zawsze inline; <lg — akordeon (widać tylko po otwarciu) */}
<div
className={cn(
'topbar-expand items-center gap-2',
open ? 'flex' : 'hidden',
'lg:flex',
'max-md:absolute max-md:bottom-[calc(100%+12px)] max-md:right-0 max-md:z-50 max-md:min-w-48 max-md:flex-col max-md:items-stretch max-md:rounded-xl max-md:border max-md:border-line max-md:bg-card max-md:p-2.5 max-md:shadow-card',
)}
>
{children}
</div>
<button
type="button"
onClick={onToggle}
aria-label={label}
aria-haspopup="true"
aria-expanded={open}
className={cn(
'relative grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border shadow-card transition-all duration-150 lg:hidden',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60',
open
? 'border-accent/55 bg-accent/10 text-accent-text'
: 'border-line bg-card text-dim hover:border-accent/45 hover:text-ink',
)}
>
<Icon className="h-4 w-4" />
{active && <span className="absolute right-0.5 top-0.5 h-1.5 w-1.5 rounded-full bg-accent" />}
</button>
</div>
);
}

View File

@@ -0,0 +1,142 @@
import { useState } from 'react';
import { Calendar, ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '../components/ui';
export const MONTH_NAMES = [
'Styczeń',
'Luty',
'Marzec',
'Kwiecień',
'Maj',
'Czerwiec',
'Lipiec',
'Sierpień',
'Wrzesień',
'Październik',
'Listopad',
'Grudzień',
];
/** Krótkie nazwy do siatki miesięcy w panelu selektora. */
export const MONTH_SHORT = ['Sty', 'Lut', 'Mar', 'Kwi', 'Maj', 'Cze', 'Lip', 'Sie', 'Wrz', 'Paź', 'Lis', 'Gru'];
/** `2026-08` → `Sierpień 2026`. */
export function formatMonth(month: string): string {
const [y, m] = month.split('-').map(Number);
return `${MONTH_NAMES[m - 1]} ${y}`;
}
function shiftMonth(month: string, delta: number): string {
const [y, m] = month.split('-').map(Number);
const d = new Date(y, m - 1 + delta, 1);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}
interface MonthPickerProps {
/** `YYYY-MM` albo `''` (brak filtra). */
value: string;
onChange: (month: string) => void;
/** Lata pokazywane w panelu (nowe → stare). */
years: string[];
}
/**
* Selektor miesiąca (YYYY-MM) — widget top menu.
* ◀/▶ przeklikują do poprzedniego/następnego miesiąca, panel: lata + siatka 12 miesięcy.
*/
export function MonthPicker({ value, onChange, years }: MonthPickerProps) {
const [open, setOpen] = useState(false);
const [panelYear, setPanelYear] = useState<number | null>(null);
const now = new Date();
const base = value || `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
const prevMonth = shiftMonth(base, -1);
const nextMonth = shiftMonth(base, 1);
return (
<div className="relative">
<div className="flex items-center gap-1">
<Button
size="sm"
variant="ghost"
onClick={() => onChange(prevMonth)}
aria-label="Poprzedni miesiąc"
>
<ChevronLeft className="w-4 h-4" />
</Button>
<Button
size="sm"
variant="secondary"
className="whitespace-nowrap h-9"
onClick={() => {
if (open) setOpen(false);
else {
setPanelYear(Number(base.slice(0, 4)));
setOpen(true);
}
}}
aria-haspopup="true"
aria-expanded={open}
>
<Calendar className="w-4 h-4" />
{value ? formatMonth(value) : 'Miesiąc'}
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => onChange(nextMonth)}
aria-label="Następny miesiąc"
>
<ChevronRight className="w-4 h-4" />
</Button>
</div>
{open && (
<>
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
<div className="absolute right-0 top-full z-50 mt-2 w-72 bg-card border border-line rounded-2xl p-3 shadow-lg">
{/* filtr po roku */}
<div className="flex flex-wrap gap-1.5 mb-3">
{years.map((y) => (
<button
key={y}
type="button"
onClick={() => setPanelYear(Number(y))}
className={`px-2.5 py-1.5 rounded-lg text-[0.85rem] font-semibold cursor-pointer ${
panelYear === Number(y)
? 'bg-accent/15 text-accent-text'
: 'text-dim hover:text-ink hover:bg-line/30'
}`}
>
{y}
</button>
))}
</div>
{/* siatka 12 miesięcy wybranego roku */}
<div className="grid grid-cols-4 gap-1.5">
{Array.from({ length: 12 }, (_, i) => {
const m = `${panelYear ?? base.slice(0, 4)}-${String(i + 1).padStart(2, '0')}`;
const selected = m === value;
return (
<button
key={m}
type="button"
title={selected ? 'Odznacz (wszystkie miesiące)' : undefined}
onClick={() => {
// ponowne kliknięcie zaznaczonego miesiąca odznacza filtr
onChange(selected ? '' : m);
setOpen(false);
}}
className={`px-1 py-2 rounded-lg text-[0.85rem] font-semibold cursor-pointer ${
selected ? 'bg-accent/15 text-accent-text' : 'text-ink hover:bg-line/30'
}`}
>
{MONTH_SHORT[i]}
</button>
);
})}
</div>
</div>
</>
)}
</div>
);
}

148
admin/src/topbar/Topbar.tsx Normal file
View File

@@ -0,0 +1,148 @@
import { useNavigate } from 'react-router-dom';
import { Filter, Menu, MoreHorizontal, Plus, Search } from 'lucide-react';
import { useTopbarStore } from './store';
import { useListSearch, type SearchableSection } from '../store/list-search';
import { Button, Input } from '../components/ui';
import { cn } from '../lib/utils';
import { GroupButton } from './GroupButton';
import type { TopbarAction, TopbarGroup } from './types';
const SEARCH_LABELS: Record<SearchableSection, string> = {
gyms: 'Szukaj siłowni',
users: 'Szukaj użytkownika',
'focus-areas': 'Szukaj obszaru',
exercises: 'Szukaj ćwiczenia',
equipment: 'Szukaj urządzenia',
logs: 'Szukaj użytkownika',
};
function SectionSearchInput({ section }: { section: SearchableSection }) {
const query = useListSearch((s) => s.queries[section]);
const setQuery = useListSearch((s) => s.setQuery);
return (
<Input
type="search"
size="sm"
placeholder="Szukaj…"
value={query}
onChange={(e) => setQuery(section, e.target.value)}
aria-label={SEARCH_LABELS[section]}
/>
);
}
function ActionButton({ action, onNavigate }: { action: TopbarAction; onNavigate: (to: string) => void }) {
const Icon = action.icon;
return (
<Button
size="sm"
variant={action.variant ?? 'primary'}
disabled={action.disabled}
onClick={() => (action.to ? onNavigate(action.to) : action.onClick?.())}
>
{Icon && <Icon className="w-4 h-4" />}
{action.label}
</Button>
);
}
/**
* Menu kontekstowe otwartej zakładki (jedno menu, trzy zachowania responsywne):
* - PC (lg+): wszystkie opcje rozwinięte inline z automatu (bez akordeonu);
* - tablet (md–lg): pasek u góry, akordeon zwinięty do ikon (jedna grupa naraz);
* - telefon (<md): ten sam pasek na dole ekranu, panele rozwijają się w górę,
* a u góry zostaje tylko hamburger + tytuł.
* Konfigurację rejestruje aktywna strona (useTopbar).
*/
export function Topbar({ onMenuOpen }: { onMenuOpen?: () => void }) {
const config = useTopbarStore((s) => s.config);
const openGroup = useTopbarStore((s) => s.openGroup);
const setOpenGroup = useTopbarStore((s) => s.setOpenGroup);
const navigate = useNavigate();
const section = config?.search;
const searchQuery = useListSearch((s) => (section ? s.queries[section] : ''));
const actions = config?.actions ?? [];
// ikony lucide to komponenty forwardRef — nazwa w displayName (nie w name)
const plusActions = actions.filter((a) => a.icon?.displayName === 'Plus');
const otherActions = actions.filter((a) => a.icon?.displayName !== 'Plus');
const hasFilters = config?.dateFilter != null || (config?.filters?.length ?? 0) > 0;
const toggle = (group: TopbarGroup) => setOpenGroup(openGroup === group ? null : group);
return (
<header className="sticky top-0 z-30 border-b border-line md:bg-bg/80 md:backdrop-blur-[8px]">
<div className="mx-auto flex max-w-5xl items-center justify-between gap-3 px-4 py-2.5 md:px-8 md:py-3">
{onMenuOpen && (
<button
type="button"
onClick={onMenuOpen}
aria-label="Otwórz menu"
className="grid h-[34px] w-[34px] flex-none cursor-pointer place-items-center rounded-[10px] border border-line bg-card text-dim shadow-card transition-colors hover:text-ink md:hidden"
>
<Menu className="h-4 w-4" />
</button>
)}
<h1 className="min-w-0 flex-1 truncate text-[1.15rem] font-bold tracking-[-0.01em] md:flex-none">
{config?.title}
</h1>
{/* akcje kontekstowe: md+ inline w nagłówku; telefon = pasek na dole ekranu */}
<div
className={cn(
'flex shrink-0 items-center gap-2 md:flex-wrap md:justify-end',
'max-md:fixed max-md:inset-x-0 max-md:bottom-0 max-md:z-40 max-md:justify-around max-md:gap-1 max-md:border-t max-md:border-line max-md:bg-card max-md:px-3 max-md:py-2',
)}
>
{/* nawigacja (np. Kalendarz) zawsze widoczna, nie jest grupą */}
{config?.navWidget}
{hasFilters && (
<GroupButton
icon={Filter}
label="Filtry"
active={config?.filterActive}
open={openGroup === 'filters'}
onToggle={() => toggle('filters')}
>
{config?.dateFilter}
{config?.filters?.map((filter, i) => (
<div key={i}>{filter}</div>
))}
</GroupButton>
)}
{plusActions.length > 0 && (
<GroupButton icon={Plus} label="Dodawanie" open={openGroup === 'add'} onToggle={() => toggle('add')}>
{plusActions.map((action) => (
<ActionButton key={action.label} action={action} onNavigate={navigate} />
))}
</GroupButton>
)}
{otherActions.length > 0 && (
<GroupButton
icon={MoreHorizontal}
label="Akcje"
open={openGroup === 'actions'}
onToggle={() => toggle('actions')}
>
{otherActions.map((action) => (
<ActionButton key={action.label} action={action} onNavigate={navigate} />
))}
</GroupButton>
)}
{/* wyszukiwarka zawsze maksymalnie z prawej */}
{config?.search && (
<GroupButton
icon={Search}
label="Wyszukiwarka"
active={searchQuery !== ''}
open={openGroup === 'search'}
onToggle={() => toggle('search')}
>
<div className="w-56 max-md:w-full">
<SectionSearchInput section={config.search} />
</div>
</GroupButton>
)}
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,4 @@
export { Topbar } from './Topbar';
export { useTopbar } from './useTopbar';
export { useTopbarStore } from './store';
export type { TopbarAction, TopbarConfig, TopbarGroup } from './types';

23
admin/src/topbar/store.ts Normal file
View File

@@ -0,0 +1,23 @@
import { create } from 'zustand';
import type { TopbarConfig, TopbarGroup } from './types';
interface TopbarState {
/** Konfiguracja top menu zarejestrowana przez aktywną stronę (null = brak). */
config: TopbarConfig | null;
/** Otwarta grupa akordeonu (jedna naraz); null = wszystkie zwinięte. */
openGroup: TopbarGroup | null;
/** Odświeża konfigurację (re-render strony) — nie dotyka otwartej grupy. */
setConfig: (config: TopbarConfig | null) => void;
/** Rejestracja strony (mount): ustawia konfigurację i resetuje grupę (null = czyszczenie). */
registerPage: (config: TopbarConfig | null) => void;
setOpenGroup: (group: TopbarGroup | null) => void;
}
export const useTopbarStore = create<TopbarState>((set) => ({
config: null,
openGroup: null,
setConfig: (config) => set({ config }),
registerPage: (config) =>
set({ config, openGroup: config ? config.defaultOpenGroup ?? null : null }),
setOpenGroup: (group) => set({ openGroup: group }),
}));

42
admin/src/topbar/types.ts Normal file
View File

@@ -0,0 +1,42 @@
import type { ReactNode } from 'react';
import type { LucideIcon } from 'lucide-react';
import type { ButtonVariant } from '../components/ui';
import type { SearchableSection } from '../store/list-search';
/** Grupy akordeonu w top menu (jedna otwarta naraz). */
export type TopbarGroup = 'search' | 'filters' | 'add' | 'actions';
/** Przycisk menu: nawigacja (to) albo lokalny handler strony (onClick, np. otwarcie modala). */
export interface TopbarAction {
label: string;
/** Nawigacja (react-router). */
to?: string;
/** Handler zarejestrowany przez stronę (np. otwarcie modala w treści). */
onClick?: () => void;
variant?: ButtonVariant;
icon?: LucideIcon;
disabled?: boolean;
}
/**
* Konfiguracja top menu (nagłówka) dla aktywnej podstrony.
* Każda podstrona deklaruje ją sama (hook useTopbar) — brak centralnej mapy tras.
* Prawa strona = akordeon ikon: 🔍 wyszukiwarka, lejko filtry, ➕ dodawanie, ⋯ akcje.
*/
export interface TopbarConfig {
title: string;
/** Wyszukiwarka listy (store list-search) → grupa 🔍. */
search?: SearchableSection;
/** Filtr po dacie (np. selektor miesiąca) → grupa lejka. */
dateFilter?: ReactNode;
/** Dodatkowe filtry (np. select) → grupa lejka. */
filters?: ReactNode[];
/** Kropka na lejku — strona podaje stan (filtry jako ReactNode są nieprzezroczyste). */
filterActive?: boolean;
/** Zawsze-widoczny widget (nawigacja, np. Kalendarz) — nie grupa, nie filtr. */
navWidget?: ReactNode;
/** Akcje: `icon: Plus` → grupa ➕, reszta → grupa ⋯ (mechaniczna reguła). */
actions?: TopbarAction[];
/** Wyjątek od domyślnie-zwiniętego akordeonu: grupa otwarta na starcie strony. */
defaultOpenGroup?: 'actions';
}

View File

@@ -0,0 +1,22 @@
import { useEffect } from 'react';
import { useTopbarStore } from './store';
import type { TopbarConfig } from './types';
/**
* Strona rejestruje własną konfigurację top menu (tytuł, wyszukiwarkę, filtry, akcje).
* Konfiguracja jest odświeżana przy każdym renderze (strona tworzy obiekt na nowo)
* — otwarta grupa akordeonu jest przy tym zachowywana.
* Przy mount stronie jest rejestrowana (grupa resetowana do domyślnej), przy unmount czyszczona.
*/
export function useTopbar(config: TopbarConfig) {
const setConfig = useTopbarStore((s) => s.setConfig);
const registerPage = useTopbarStore((s) => s.registerPage);
useEffect(() => {
setConfig(config);
});
useEffect(() => {
registerPage(config);
return () => registerPage(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}

View File

@@ -0,0 +1,153 @@
import { render, screen, waitFor, within, act } 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 EquipmentCatalog from '../src/pages/Equipment';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import { useListSearch } from '../src/store/list-search';
const SEED = [
{ id: 'eq-1', name: 'Sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: 'Sztanga z talerzami.' },
{ id: 'eq-2', name: 'Dywan', kind: 'OTHER', spec: null, description: 'Dywan do ćwiczeń.' },
];
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
interface Recorded {
method: string;
url: string;
body: unknown;
}
/** Stateful mock: zmiany (POST/PATCH/DELETE) są widoczne po refetchu. */
function mockApi() {
const state = { items: SEED.map((e) => ({ ...e })) };
const requests: Recorded[] = [];
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method || 'GET';
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
requests.push({ method, url, body });
if (url.includes('/admin/equipment')) {
const id = url.match(/\/admin\/equipment\/([^/]+)$/)?.[1];
if (method === 'GET') return jsonResponse(200, { equipment: state.items });
if (method === 'POST') {
state.items.push({ id: `eq-${state.items.length + 1}`, ...body });
return jsonResponse(201, { equipment: state.items });
}
if (method === 'PATCH') {
state.items = state.items.map((e) => (e.id === id ? { ...e, ...body } : e));
return jsonResponse(200, { equipment: state.items });
}
if (method === 'DELETE') {
state.items = state.items.filter((e) => e.id !== id);
return jsonResponse(204, {});
}
}
return jsonResponse(404, { error: { message: 'not found' } });
}),
);
return { requests };
}
function renderEquipment() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
});
return render(
<MemoryRouter initialEntries={['/equipment']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/equipment" element={<EquipmentCatalog />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
useListSearch.getState().setQuery('equipment', '');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin Equipment page', () => {
it('renderuje katalog urządzeń z nazwami, opisami i specyfikacją', async () => {
mockApi();
renderEquipment();
expect(await screen.findByText('Sztanga z talerzami.')).toBeInTheDocument();
// type-specific spec summary (BARBELL → max load)
expect(screen.getByText('do 100 kg')).toBeInTheDocument();
expect(screen.getByText('Dywan do ćwiczeń.')).toBeInTheDocument();
// przycisk „Nowe urządzenie” jest w top menu (komponent Topbar), nie w treści strony
expect(screen.queryByRole('button', { name: 'Nowe urządzenie' })).not.toBeInTheDocument();
});
it('filters equipment by the search box', async () => {
mockApi();
renderEquipment();
await screen.findByText('Sztanga z talerzami.');
// wyszukiwarka jest w top menu (komponent Topbar) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('equipment', 'dywan'));
expect(screen.queryByText('Sztanga z talerzami.')).not.toBeInTheDocument();
expect(screen.getByText('Dywan do ćwiczeń.')).toBeInTheDocument();
});
it('dodawanie urządzenia z rodzajem i specyfikacją wysyła POST', async () => {
const { requests } = mockApi();
const user = userEvent.setup();
renderEquipment();
await screen.findByText('Sztanga z talerzami.');
// przycisk „Nowe urządzenie” jest w top menu — strona rejestruje akcję w store topbar
const topbar = useTopbarStore.getState().config;
const action = topbar?.actions?.find((a) => a.label === 'Nowe urządzenie');
expect(action?.onClick).toBeTypeOf('function');
action!.onClick!();
const dialog = await screen.findByRole('dialog');
await user.type(dialog.querySelector('input') as HTMLInputElement, 'Kettlebell');
await user.selectOptions(dialog.querySelector('select') as HTMLSelectElement, 'KETTLEBELL');
await user.type(dialog.querySelector('input[placeholder="np. 2.5"]') as HTMLInputElement, '4');
await user.type(dialog.querySelector('input[placeholder="np. 25"]') as HTMLInputElement, '32');
await user.click(within(dialog).getByRole('button', { name: 'Dodaj', exact: true }));
// the new card shows the kind label and the spec summary
await waitFor(() => expect(screen.getByText('4–32 kg')).toBeInTheDocument());
const post = requests.find((r) => r.method === 'POST' && r.url.includes('/admin/equipment'));
expect(post?.body).toMatchObject({
name: 'Kettlebell',
kind: 'KETTLEBELL',
spec: { minKg: 4, maxKg: 32 },
});
});
it('usuwanie urządzenia wysyła DELETE do API', async () => {
const { requests } = mockApi();
const user = userEvent.setup();
renderEquipment();
await screen.findByText('Sztanga z talerzami.');
await user.click(screen.getByRole('button', { name: 'Usuń Sztanga' }));
const dialog = await screen.findByRole('dialog');
await user.click(within(dialog).getByRole('button', { name: 'Usuń', exact: true }));
await waitFor(() => {
const del = requests.find(
(r) => r.method === 'DELETE' && r.url.includes('/admin/equipment/eq-1'),
);
expect(del).toBeDefined();
});
});
});

View File

@@ -0,0 +1,156 @@
import { render, screen, waitFor, within, act } 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 Exercises from '../src/pages/Exercises';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
const EQUIPMENT = [
{ id: 'eq-1', name: 'Sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: 'Sztanga z talerzami.' },
{ id: 'eq-2', name: 'Dywan', kind: 'OTHER', spec: null, description: 'Dywan do ćwiczeń.' },
];
const EXERCISE = {
id: 'ex-1',
slug: 'bench-press',
name: 'Wyciskanie sztangi leżąc',
primaryMuscle: 'chest',
secondaryMuscles: ['triceps'],
equipment: [EQUIPMENT[0]],
hasReps: true,
hasLoad: true,
hasRest: true,
hasSets: true,
hasRir: true,
hasDifficulty: true,
hasCardio: false,
hasTime: false,
hasSpeed: false,
description: 'Podstawowe ćwiczenie na klatkę.',
howTo: null,
commonMistakes: null,
difficulty: 4,
source: 'BUILTIN',
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
interface Recorded {
method: string;
url: string;
body: unknown;
}
/** Stateful mock: zmiany (POST/PATCH/DELETE) są widoczne po refetchu. */
function mockApi() {
const state = {
exercises: [{ ...EXERCISE, equipment: [{ ...EQUIPMENT[0] }] }],
equipment: EQUIPMENT.map((e) => ({ ...e })),
};
const requests: Recorded[] = [];
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method || 'GET';
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
requests.push({ method, url, body });
if (url.includes('/admin/exercises')) {
const id = url.match(/\/admin\/exercises\/([^/]+)$/)?.[1];
if (method === 'GET') return jsonResponse(200, { exercises: state.exercises });
if (method === 'POST') {
state.exercises.push({ id: `ex-${state.exercises.length + 1}`, ...body });
return jsonResponse(201, { exercises: state.exercises });
}
if (method === 'PATCH') {
state.exercises = state.exercises.map((e) => (e.id === id ? { ...e, ...body } : e));
return jsonResponse(200, { exercises: state.exercises });
}
if (method === 'DELETE') {
state.exercises = state.exercises.filter((e) => e.id !== id);
return jsonResponse(204, {});
}
}
if (url.includes('/admin/equipment')) {
if (method === 'GET') return jsonResponse(200, { equipment: state.equipment });
}
return jsonResponse(404, { error: { message: 'not found' } });
}),
);
return { requests };
}
function renderExercises() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
});
return render(
<MemoryRouter initialEntries={['/exercises']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/exercises" element={<Exercises />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
useListSearch.getState().setQuery('exercises', '');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin Exercises page', () => {
it('renderuje listę ćwiczeń z mięśniami i przypisanymi maszynami', async () => {
mockApi();
renderExercises();
expect(await screen.findByText('Wyciskanie sztangi leżąc')).toBeInTheDocument();
expect(screen.getByText('chest')).toBeInTheDocument();
expect(screen.getByText('Sztanga')).toBeInTheDocument();
});
it('edycja ćwiczenia pozwala przypisać urządzenia i wysyła PATCH', async () => {
const { requests } = mockApi();
const user = userEvent.setup();
renderExercises();
await screen.findByText('Wyciskanie sztangi leżąc');
await user.click(screen.getByRole('button', { name: 'Edytuj Wyciskanie sztangi leżąc' }));
const dialog = await screen.findByRole('dialog');
// Sztanga (eq-1) jest już przypisane, Dywan (eq-2) nie — oznaczamy Dywan
await user.click(within(dialog).getByRole('checkbox', { name: 'Dywan' }));
await user.click(within(dialog).getByRole('button', { name: 'Zapisz' }));
await waitFor(() => {
const patch = requests.find(
(r) => r.method === 'PATCH' && r.url.includes('/admin/exercises/ex-1'),
);
expect(patch?.body).toMatchObject({
name: 'Wyciskanie sztangi leżąc',
primaryMuscle: 'chest',
equipmentIds: ['eq-1', 'eq-2'],
});
});
});
it('filters exercises by the search box', async () => {
mockApi();
renderExercises();
expect(await screen.findByText('Wyciskanie sztangi leżąc')).toBeInTheDocument();
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('exercises', 'przysiad'));
expect(screen.queryByText('Wyciskanie sztangi leżąc')).not.toBeInTheDocument();
expect(screen.getByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,86 @@
import { render, screen, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import FocusAreas from '../src/pages/FocusAreas';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import type { FocusArea } from '../src/api/types';
const A1: FocusArea = {
id: 'fa-1',
name: 'Klatka piersiowa',
muscle: 'chest',
description: 'Wyciskanie, rozpiętki.',
setsMin: 10,
setsMax: 20,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};
const A2: FocusArea = {
id: 'fa-2',
name: 'Nogi',
muscle: 'legs',
description: 'Przysiady, wykroki.',
setsMin: null,
setsMax: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00: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 fetchMock = vi.fn(async () => {
const next = responses.shift();
if (!next) throw new Error('No more mocked responses');
return next;
});
vi.stubGlobal('fetch', fetchMock);
return fetchMock;
}
function renderFocusAreas() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/focus-areas']}>
<QueryClientProvider client={queryClient}>
<FocusAreas />
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
useListSearch.getState().setQuery('focus-areas', '');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin FocusAreas page', () => {
it('lists focus areas', async () => {
mockFetchSequence(jsonResponse(200, { focusAreas: [A1, A2] }));
renderFocusAreas();
expect(await screen.findByText('Klatka piersiowa')).toBeInTheDocument();
expect(screen.getByText('Nogi')).toBeInTheDocument();
});
it('filters focus areas by the search box', async () => {
mockFetchSequence(jsonResponse(200, { focusAreas: [A1, A2] }));
renderFocusAreas();
await screen.findByText('Klatka piersiowa');
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('focus-areas', 'nogi'));
expect(screen.queryByText('Klatka piersiowa')).not.toBeInTheDocument();
expect(screen.getByText('Nogi')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,117 @@
import { render, screen, fireEvent, waitFor } 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 GymDetail from '../src/pages/GymDetail';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import type { Equipment, Gym } from '../src/api/types';
const G1: Gym = {
id: 'g1',
name: 'Gym A',
location: 'Warszawa',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 50,
equipment: [],
_count: { memberships: 12 },
};
const EQ1: Equipment = {
id: 'eq-1',
name: 'sztanga',
kind: 'BARBELL',
spec: { maxLoadKg: 100 },
description: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};
const EQ2: Equipment = {
id: 'eq-2',
name: 'hantle',
kind: 'DUMBBELL',
spec: { minKg: 2.5, maxKg: 25 },
description: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};
const G1_EQ: Gym = {
...G1,
equipment: [{ id: 'ge-2', gymId: 'g1', equipmentId: 'eq-2', quantity: 2, equipment: EQ2 }],
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function renderGymDetail() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/gyms/g1']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/gyms/:id" element={<GymDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin GymDetail page', () => {
it('shows gym details and the edit form', async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] });
if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] });
if (url.includes('/admin/gyms/g1')) return jsonResponse(200, G1);
throw new Error(`Unexpected fetch: ${url}`);
});
vi.stubGlobal('fetch', fetchMock);
renderGymDetail();
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
expect(screen.getByText('Warszawa')).toBeInTheDocument();
expect(screen.getByText('12 członk.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Zapisz' })).toBeInTheDocument();
// „Usuń siłownię" jest w top menu (menu kontekstowe) — sprawdzamy zarejestrowaną konfigurację
expect(useTopbarStore.getState().config?.actions?.some((a) => a.label === 'Usuń siłownię')).toBe(true);
});
it('adding already-added equipment increases its quantity via PATCH', async () => {
let patchBody: unknown;
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] });
if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] });
if (url.includes('/admin/gyms/g1/equipment/eq-2') && init?.method === 'PATCH') {
patchBody = JSON.parse(String(init.body));
return jsonResponse(200, { gym: G1_EQ });
}
if (url.includes('/admin/gyms/g1')) return jsonResponse(200, G1_EQ);
throw new Error(`Unexpected fetch: ${url}`);
});
vi.stubGlobal('fetch', fetchMock);
renderGymDetail();
expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument();
// select pokazuje cały katalog ze specyfikacją — sprzęt już dodany jest oznaczony bieżącą ilością
expect(await screen.findByRole('option', { name: 'hantle · 2.5–25 kg (2 szt.)' })).toBeInTheDocument();
fireEvent.change(screen.getByRole('combobox', { name: 'Dodaj urządzenie' }), {
target: { value: 'eq-2' },
});
fireEvent.click(screen.getByRole('button', { name: 'Dodaj' }));
await waitFor(() => expect(patchBody).toEqual({ quantity: 3 }));
});
});

View File

@@ -0,0 +1,92 @@
import { render, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, useParams } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import GymsList from '../src/pages/GymsList';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import type { Gym } from '../src/api/types';
const G1: Gym = {
id: 'g1',
name: 'Gym A',
location: 'Warszawa',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 50,
equipment: [],
_count: { memberships: 12 },
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockFetchSequence(...responses: Response[]) {
const fetchMock = vi.fn(async () => {
const next = responses.shift();
if (!next) throw new Error('No more mocked responses');
return next;
});
vi.stubGlobal('fetch', fetchMock);
return fetchMock;
}
function DetailStub() {
const { id } = useParams();
return <div>GYM-DETAIL-{id}</div>;
}
function renderGyms() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/gyms']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/gyms" element={<GymsList />} />
<Route path="/gyms/:id" element={<DetailStub />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
useListSearch.getState().setQuery('gyms', '');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin GymsList page', () => {
it('lists gyms fetched from the API', async () => {
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
renderGyms();
expect(await screen.findByText('Gym A')).toBeInTheDocument();
expect(screen.getByText('Warszawa')).toBeInTheDocument();
expect(screen.getByText('12 członk.')).toBeInTheDocument();
});
it('clicking a gym opens the detail page', async () => {
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
const user = userEvent.setup();
renderGyms();
await user.click(await screen.findByRole('link', { name: 'Gym A' }));
expect(await screen.findByText('GYM-DETAIL-g1')).toBeInTheDocument();
});
it('filters gyms by the search box', async () => {
mockFetchSequence(jsonResponse(200, { gyms: [G1] }));
renderGyms();
expect(await screen.findByText('Gym A')).toBeInTheDocument();
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('gyms', 'kraków'));
expect(screen.queryByText('Gym A')).not.toBeInTheDocument();
expect(screen.getByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument();
});
});

151
admin/test/Login.test.tsx Normal file
View File

@@ -0,0 +1,151 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Login from '../src/pages/Login';
import { useAuth } from '../src/store/auth';
import { setAccessToken } from '../src/api/client';
import type { User } from '../src/api/types';
const ADMIN: User = {
id: 'u1',
email: 'admin@test.local',
firstName: 'Admin',
lastName: null,
age: null,
heightCm: null,
phone: null,
isAdmin: true,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
const NON_ADMIN: User = { ...ADMIN, id: 'u2', email: 'jan@test.local', isAdmin: false };
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function renderLogin() {
return render(
<MemoryRouter initialEntries={['/login']}>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={<div>HOME</div>} />
</Routes>
</MemoryRouter>,
);
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin Login page', () => {
it('renders the form', () => {
renderLogin();
expect(screen.getByRole('heading', { name: 'FitOS Admin' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Zaloguj' })).toBeInTheDocument();
});
it('logs in an admin and navigates home', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(200, { user: ADMIN, accessToken: 'tok-1' })),
);
const user = userEvent.setup();
const { container } = renderLogin();
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
const password = container.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(email, 'admin@test.local');
await user.type(password, 'Password123!');
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
expect(await screen.findByText('HOME')).toBeInTheDocument();
expect(useAuth.getState().user).toEqual(ADMIN);
});
it('rejects a non-admin login with a dedicated error and stays on the page', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(200, { user: NON_ADMIN, accessToken: 'tok-1' })),
);
const user = userEvent.setup();
const { container } = renderLogin();
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
const password = container.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.findByText('Dostęp tylko dla administratorów')).toBeInTheDocument();
expect(screen.queryByText('HOME')).not.toBeInTheDocument();
expect(useAuth.getState().user).toBeNull();
});
it('saves the email to localStorage when "Zapamiętaj mnie" is checked', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(200, { user: ADMIN, accessToken: 'tok-1' })),
);
const user = userEvent.setup();
const { container } = renderLogin();
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
const password = container.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(email, 'admin@test.local');
await user.type(password, 'Password123!');
await user.click(screen.getByRole('checkbox', { name: 'Zapamiętaj mnie' }));
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
expect(await screen.findByText('HOME')).toBeInTheDocument();
expect(localStorage.getItem('fitos-remembered-email')).toBe('admin@test.local');
});
it('pre-fills the email from localStorage and clears it when unchecked', async () => {
localStorage.setItem('fitos-remembered-email', 'admin@test.local');
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse(200, { user: ADMIN, accessToken: 'tok-1' })),
);
const user = userEvent.setup();
const { container } = renderLogin();
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
expect(email.value).toBe('admin@test.local');
const password = container.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(password, 'Password123!');
await user.click(screen.getByRole('checkbox', { name: 'Zapamiętaj mnie' }));
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
expect(await screen.findByText('HOME')).toBeInTheDocument();
expect(localStorage.getItem('fitos-remembered-email')).toBeNull();
});
it('shows the server error message on invalid credentials', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () =>
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid credentials' } }),
),
);
const user = userEvent.setup();
const { container } = renderLogin();
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
const password = container.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(email, 'admin@test.local');
await user.type(password, 'wrong');
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
expect(await screen.findByText('Invalid credentials')).toBeInTheDocument();
});
});

172
admin/test/Logs.test.tsx Normal file
View File

@@ -0,0 +1,172 @@
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 from '../src/pages/Logs';
import { Topbar } from '../src/topbar';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import type { ActivityLog } 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: null,
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' },
};
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) => {
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();
// szczegóły jako naturalny tekst (tytuł i actorId są w innych kolumnach)
expect(await screen.findByText('start: 2026-08-24')).toBeInTheDocument();
// ID aktora pod e-mailem w kolumnie „Użytkownik"
expect(screen.getAllByText('user-1').length).toBeGreaterThan(0);
// aktor: e-mail pod imieniem i nazwiskiem
expect(screen.getByText('anna@test.local')).toBeInTheDocument();
// 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();
});
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('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: 'Miesiąc' }));
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 kliknięcie zaznaczonego miesiąca odznacza filtr (brak from/to)
await userEvent.click(screen.getByRole('button', { name: 'Sierpień 2026' }));
await userEvent.click(screen.getByRole('button', { name: 'Sie' }));
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: 'Miesiąc' })).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();
expect(screen.getByText('anna@test.local')).toBeInTheDocument();
});
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();
});
});

View File

@@ -0,0 +1,278 @@
import { render, screen } 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 UserDetail from '../src/pages/UserDetail';
import { setAccessToken } from '../src/api/client';
import { API_BASE } from '../src/config';
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 G2: Gym = {
id: 'g2',
name: 'Gym B',
location: 'Kraków',
availability: null,
capacity: null,
equipment: [],
_count: { memberships: 0 },
};
const U1: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
age: 30,
heightCm: 180,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: ['chest'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: ['legs'],
createdAt: '2026-08-01T10:00:00.000Z',
memberships: [{ gymId: 'g1', roles: ['OWNER', 'TRAINER'], gym: G1 }],
};
const U2: User = {
...U1,
id: 'u2',
email: 'anna@test.local',
firstName: 'Anna',
lastName: 'Nowak',
memberships: [{ gymId: 'g1', roles: ['MEMBER'], gym: G1 }],
};
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) => {
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;
}
/**
* Mockuje fetch wg URL (odporny na kolejność żądań). Zwraca listę wywołań.
* `routes` mapuje fragment URL → fabryka odpowiedzi (wywoływana przy każdym żądaniu).
*/
function mockFetchRoutes(routes: Record<string, () => unknown>) {
const calls: { url: string; init?: RequestInit }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
calls.push({ url, init });
const handler = Object.entries(routes).find(([frag]) => url.includes(frag))?.[1];
if (!handler) throw new Error(`No mocked route for url: ${url}`);
return jsonResponse(200, handler());
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
function renderUserDetail(path = '/users/u1') {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={[path]}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/users/:id" element={<UserDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserDetail page', () => {
it('shows user details, per-role badges and role checkboxes', async () => {
mockFetchSequence(
jsonResponse(200, { users: [U1] }),
jsonResponse(200, { gyms: [G1, G2] }),
);
const user = userEvent.setup();
const { container } = renderUserDetail();
expect(await screen.findByRole('heading', { name: 'Jan Kowalski' })).toBeInTheDocument();
expect(screen.getByText('jan@test.local')).toBeInTheDocument();
// per-role summary badges in the header
expect(screen.getByText('Właściciel: Gym A')).toBeInTheDocument();
expect(screen.getByText('Trener: Gym A')).toBeInTheDocument();
// membership row with the gym description
expect(screen.getByText('Gym A')).toBeInTheDocument();
expect(screen.getByText('Warszawa')).toBeInTheDocument();
// searchable gym picker hides gyms the user already belongs to
await user.click(screen.getByRole('combobox', { name: 'Szukaj siłowni' }));
expect(screen.getByRole('option', { name: /Gym B/ })).toBeInTheDocument();
expect(screen.queryByRole('option', { name: /Gym A/ })).not.toBeInTheDocument();
// role checkboxes for the membership
const ownerBox = screen.getByRole('checkbox', { name: 'Właściciel w Gym A' });
const trainerBox = screen.getByRole('checkbox', { name: 'Trener w Gym A' });
const memberBox = screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' });
expect(ownerBox).toBeChecked();
expect(trainerBox).toBeChecked();
expect(memberBox).not.toBeChecked();
// email is editable in the edit form
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
expect(email).not.toBeNull();
expect(email.value).toBe('jan@test.local');
expect(screen.getByRole('button', { name: 'Zapisz' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Usuń użytkownika' })).toBeInTheDocument();
});
it('checking a role checkbox sends a PATCH with the full roles list', async () => {
const calls = mockFetchSequence(
jsonResponse(200, { users: [U1] }),
jsonResponse(200, { gyms: [G1, G2] }),
jsonResponse(200, { membership: { gymId: 'g1', roles: ['OWNER', 'TRAINER', 'MEMBER'] } }),
jsonResponse(200, { users: [U1] }),
);
const user = userEvent.setup();
renderUserDetail();
await screen.findByRole('heading', { name: 'Jan Kowalski' });
await user.click(screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' }));
const patch = calls.find(
(c) => c.url === `${API_BASE}/admin/users/u1/memberships/g1` && c.init?.method === 'PATCH',
);
expect(patch).toBeDefined();
expect(JSON.parse(patch?.init?.body as string)).toEqual({
roles: ['OWNER', 'TRAINER', 'MEMBER'],
});
});
it('keeps the membership when the last role cannot be unchecked', async () => {
const calls = mockFetchSequence(
jsonResponse(200, { users: [U2] }),
jsonResponse(200, { gyms: [G1, G2] }),
);
const user = userEvent.setup();
renderUserDetail('/users/u2');
await screen.findByRole('heading', { name: 'Anna Nowak' });
// the only active role is locked: unchecking it would empty the membership
const lastRole = screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' });
expect(lastRole).toBeDisabled();
expect(screen.getByRole('checkbox', { name: 'Trener w Gym A' })).toBeEnabled();
await user.click(lastRole);
expect(
calls.some((c) => c.init?.method === 'DELETE' || c.init?.method === 'PATCH'),
).toBe(false);
});
it('adds a membership via the searchable gym picker', async () => {
const calls = mockFetchSequence(
jsonResponse(200, { users: [U1] }),
jsonResponse(200, { gyms: [G1, G2] }),
jsonResponse(201, { membership: { gymId: 'g2', roles: ['MEMBER'] } }),
jsonResponse(200, { users: [U1] }),
);
const user = userEvent.setup();
renderUserDetail();
await screen.findByRole('heading', { name: 'Jan Kowalski' });
const combobox = screen.getByRole('combobox', { name: 'Szukaj siłowni' });
await user.click(combobox);
await user.type(combobox, 'Gym B');
await user.click(screen.getByRole('option', { name: /Gym B/ }));
await user.click(screen.getByRole('button', { name: 'Dodaj członkostwo' }));
const post = calls.find(
(c) => c.url === `${API_BASE}/admin/users/u1/memberships` && c.init?.method === 'POST',
);
expect(post).toBeDefined();
expect(JSON.parse(post?.init?.body as string)).toEqual({ gymId: 'g2', roles: ['MEMBER'] });
});
it('saves the training profile fields via the edit form', async () => {
const focusAreas = [
{ id: 'fa-1', name: 'Klatka piersiowa', muscle: 'chest', description: null, createdAt: '', updatedAt: '' },
{ id: 'fa-2', name: 'Nogi', muscle: 'legs', description: null, createdAt: '', updatedAt: '' },
];
const calls = mockFetchRoutes({
'/admin/users/u1/focus-chain': () => ({ develop: [], canDo: [], difficult: [], avoid: [] }),
'/admin/focus-areas': () => ({ focusAreas }),
'/admin/users': () => ({ users: [U1] }),
'/admin/gyms': () => ({ gyms: [G1, G2] }),
});
const user = userEvent.setup();
const { container } = renderUserDetail();
await screen.findByRole('heading', { name: 'Jan Kowalski' });
// availability editor renders a checkbox per day
const wtCheckbox = await screen.findByRole('checkbox', { name: 'Wt: dostępny' });
expect(wtCheckbox).not.toBeNull();
// focus area chips are rendered from the catalog (per section) — wait for the async fetch
const chestDevelop = await screen.findByRole('checkbox', { name: 'Klatka piersiowa (co rozwija)' });
const legsAvoid = await screen.findByRole('checkbox', { name: 'Nogi (co unikać)' });
expect(chestDevelop).toBeChecked(); // U1.developMuscles = ['chest']
expect(legsAvoid).toBeChecked(); // U1.avoidMuscles = ['legs']
// enable Tuesday (default 18:00-20:00)
await user.click(wtCheckbox);
// toggle off chest (develop) and toggle off legs (avoid)
await user.click(chestDevelop);
await user.click(legsAvoid);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
const patch = calls.find((c) => c.url === `${API_BASE}/admin/users/u1` && c.init?.method === 'PATCH');
expect(patch).toBeDefined();
const body = JSON.parse(patch?.init?.body as string);
expect(body.availability).toEqual([null, { start: '18:00', end: '20:00' }, null, null, null, null, null]);
// chest removed from develop, legs removed from avoid
expect(body.developMuscles).toEqual([]);
expect(body.canDoMuscles).toEqual([]);
expect(body.difficultMuscles).toEqual([]);
expect(body.avoidMuscles).toEqual([]);
});
it('saves the edited email via the edit form', async () => {
const calls = mockFetchSequence(
jsonResponse(200, { users: [U1] }),
jsonResponse(200, { gyms: [G1, G2] }),
jsonResponse(200, { user: U1 }),
jsonResponse(200, { users: [U1] }),
);
const user = userEvent.setup();
const { container } = renderUserDetail();
await screen.findByRole('heading', { name: 'Jan Kowalski' });
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
await user.clear(email);
await user.type(email, 'nowy-email@test.local');
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
const patch = calls.find(
(c) => c.url === `${API_BASE}/admin/users/u1` && c.init?.method === 'PATCH',
);
expect(patch).toBeDefined();
expect(JSON.parse(patch?.init?.body as string)).toMatchObject({
email: 'nowy-email@test.local',
});
});
});

View File

@@ -0,0 +1,92 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, useParams } from 'react-router-dom';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserForm from '../src/pages/UserForm';
import { setAccessToken } from '../src/api/client';
import { API_BASE } from '../src/config';
import type { User } from '../src/api/types';
const U3: User = {
id: 'u3',
email: 'nowy3@test.local',
firstName: 'Nowy',
lastName: null,
age: null,
heightCm: null,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-03T10:00:00.000Z',
memberships: [],
};
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) => {
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 DetailStub() {
const { id } = useParams();
return <div>DETAIL-{id}</div>;
}
function renderForm() {
return render(
<MemoryRouter initialEntries={['/users/new']}>
<Routes>
<Route path="/users/new" element={<UserForm />} />
<Route path="/users/:id" element={<DetailStub />} />
</Routes>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UserForm page', () => {
it('creates a user and opens the detail page', async () => {
const calls = mockFetchSequence(jsonResponse(201, { user: U3 }));
const user = userEvent.setup();
const { container } = renderForm();
const email = container.querySelector('input[type="email"]') as HTMLInputElement;
const password = container.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(email, 'nowy3@test.local');
await user.type(password, 'Password123!');
await user.click(screen.getByRole('button', { name: 'Utwórz użytkownika' }));
expect(await screen.findByText('DETAIL-u3')).toBeInTheDocument();
const post = calls.find((c) => c.init?.method === 'POST');
expect(post?.url).toBe(`${API_BASE}/admin/users`);
expect(JSON.parse(post?.init?.body as string)).toMatchObject({
email: 'nowy3@test.local',
password: 'Password123!',
isAdmin: false,
});
});
});

View File

@@ -0,0 +1,114 @@
import { render, screen, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UsersList from '../src/pages/UsersList';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import type { User } from '../src/api/types';
const U1: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
age: 30,
heightCm: 180,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-01T10:00:00.000Z',
memberships: [],
};
const U2: User = {
id: 'u2',
email: 'admin@test.local',
firstName: 'Admin',
lastName: null,
age: null,
heightCm: null,
phone: null,
isAdmin: true,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-02T10:00:00.000Z',
memberships: [],
};
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) => {
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 renderUsers() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={['/users']}>
<QueryClientProvider client={queryClient}>
<UsersList />
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
useListSearch.getState().setQuery('users', '');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin UsersList page', () => {
it('lists users fetched from the API', async () => {
mockFetchSequence(jsonResponse(200, { users: [U1, U2] }));
renderUsers();
expect(await screen.findByText('jan@test.local · wiek: 30')).toBeInTheDocument();
expect(screen.getByText('admin@test.local')).toBeInTheDocument();
// 'Admin' appears both as the user name link and as the admin badge
expect(screen.getAllByText('Admin')).toHaveLength(2);
});
it('filters users by the search box', async () => {
mockFetchSequence(jsonResponse(200, { users: [U1, U2] }));
renderUsers();
await screen.findByText('jan@test.local · wiek: 30');
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('users', 'admin'));
expect(screen.queryByText('jan@test.local · wiek: 30')).not.toBeInTheDocument();
expect(screen.getByText('admin@test.local')).toBeInTheDocument();
});
it('shows an error when the users request fails', async () => {
mockFetchSequence(jsonResponse(500, { error: { code: 'INTERNAL', message: 'Błąd wewnętrzny' } }));
renderUsers();
expect(await screen.findByText(/Błąd: Błąd wewnętrzny/)).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,129 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { useAuth } from '../src/store/auth';
import { setAccessToken, getAccessToken } from '../src/api/client';
import type { User } from '../src/api/types';
const ADMIN: User = {
id: 'u1',
email: 'admin@test.local',
firstName: 'Admin',
lastName: null,
age: null,
heightCm: null,
phone: null,
isAdmin: true,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
const NON_ADMIN: User = { ...ADMIN, id: 'u2', email: 'jan@test.local', isAdmin: false };
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockFetchSequence(...responses: Response[]) {
const fetchMock = vi.fn(async (url: string) => {
const next = responses.shift();
if (!next) throw new Error(`No more mocked responses for url: ${url}`);
return next;
});
vi.stubGlobal('fetch', fetchMock);
return fetchMock;
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin auth store', () => {
it('login stores the admin user and the access token', async () => {
mockFetchSequence(jsonResponse(200, { user: ADMIN, accessToken: 'tok-1' }));
await useAuth.getState().login('admin@test.local', 'Password123!');
expect(useAuth.getState().user).toEqual(ADMIN);
expect(getAccessToken()).toBe('tok-1');
expect(localStorage.getItem('fitos_admin_access')).toBe('tok-1');
});
it('login rejects for non-admin users and clears the token', async () => {
mockFetchSequence(jsonResponse(200, { user: NON_ADMIN, accessToken: 'tok-1' }));
await expect(useAuth.getState().login('jan@test.local', 'Password123!')).rejects.toThrow(
'Dostęp tylko dla administratorów',
);
expect(useAuth.getState().user).toBeNull();
expect(getAccessToken()).toBeNull();
expect(localStorage.getItem('fitos_admin_access')).toBeNull();
});
it('login rejects on invalid credentials', async () => {
mockFetchSequence(
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid credentials' } }),
);
await expect(useAuth.getState().login('admin@test.local', 'wrong')).rejects.toThrow(
'Invalid credentials',
);
expect(useAuth.getState().user).toBeNull();
});
it('logout clears the user and the token even when the API call fails', async () => {
useAuth.setState({ user: ADMIN });
setAccessToken('tok-2');
vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 500 })));
await useAuth.getState().logout();
expect(useAuth.getState().user).toBeNull();
expect(getAccessToken()).toBeNull();
});
it('init restores an admin session via refresh + /me', async () => {
const fetchMock = mockFetchSequence(
jsonResponse(200, { accessToken: 'tok-3' }),
jsonResponse(200, { user: ADMIN }),
);
await useAuth.getState().init();
expect(useAuth.getState().user).toEqual(ADMIN);
expect(useAuth.getState().ready).toBe(true);
expect(getAccessToken()).toBe('tok-3');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('init rejects a non-admin session', async () => {
mockFetchSequence(
jsonResponse(200, { accessToken: 'tok-4' }),
jsonResponse(200, { user: NON_ADMIN }),
);
await useAuth.getState().init();
expect(useAuth.getState().user).toBeNull();
expect(useAuth.getState().ready).toBe(true);
});
it('init without a valid session ends with a null user and ready=true', async () => {
mockFetchSequence(
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid refresh token' } }),
);
await useAuth.getState().init();
expect(useAuth.getState().user).toBeNull();
expect(useAuth.getState().ready).toBe(true);
});
it('the fitos:logout event clears the user', () => {
useAuth.setState({ user: ADMIN });
window.dispatchEvent(new Event('fitos:logout'));
expect(useAuth.getState().user).toBeNull();
});
});

136
admin/test/client.test.ts Normal file
View File

@@ -0,0 +1,136 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { api, setAccessToken, getAccessToken, ApiError } from '../src/api/client';
import { API_BASE } from '../src/config';
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) => {
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;
}
beforeEach(async () => {
// wait for any pending internal refresh-state cleanup from previous tests
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin api client', () => {
it('performs a GET request with the Authorization header when a token is set', async () => {
setAccessToken('admin-tok');
const calls = mockFetchSequence(jsonResponse(200, { ok: true }));
const data = await api<{ ok: boolean }>('/admin/users');
expect(data).toEqual({ ok: true });
expect(calls).toHaveLength(1);
expect(calls[0].url).toBe(`${API_BASE}/admin/users`);
expect(calls[0].init?.headers).toMatchObject({ Authorization: 'Bearer admin-tok' });
expect(calls[0].init?.credentials).toBe('include');
});
it('omits the Authorization header when no token is set', async () => {
setAccessToken(null);
const calls = mockFetchSequence(jsonResponse(200, { ok: true }));
await api('/me');
expect(calls[0].init?.headers).not.toHaveProperty('Authorization');
});
it('sends a JSON body for POST requests', async () => {
const calls = mockFetchSequence(jsonResponse(200, { ok: true }));
await api('/auth/login', { method: 'POST', body: { email: 'a@b.c', password: 'x' } });
expect(calls[0].init?.method).toBe('POST');
expect(calls[0].init?.body).toBe(JSON.stringify({ email: 'a@b.c', password: 'x' }));
});
it('throws an ApiError with status and server message on failure', async () => {
mockFetchSequence(
jsonResponse(403, { error: { code: 'FORBIDDEN', message: 'Admin only' } }),
);
let caught: unknown;
try {
await api('/admin/users');
} catch (e) {
caught = e;
}
expect(caught).toBeInstanceOf(ApiError);
expect((caught as ApiError).status).toBe(403);
expect((caught as ApiError).message).toBe('Admin only');
});
it('wraps a non-JSON error body (e.g. rate limiter) in an ApiError with the raw text message', async () => {
mockFetchSequence(new Response('Too many requests, please try again later.', { status: 429 }));
let caught: unknown;
try {
await api('/admin/users');
} catch (e) {
caught = e;
}
expect(caught).toBeInstanceOf(ApiError);
expect((caught as ApiError).status).toBe(429);
expect((caught as ApiError).message).toBe('Too many requests, please try again later.');
});
it('on 401 refreshes the token and retries the request', async () => {
setAccessToken('old-token');
const calls = mockFetchSequence(
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Unauthorized' } }),
jsonResponse(200, { accessToken: 'new-token' }),
jsonResponse(200, { users: [] }),
);
const data = await api<{ users: unknown[] }>('/admin/users');
expect(data).toEqual({ users: [] });
expect(calls).toHaveLength(3);
expect(calls[1].url).toBe(`${API_BASE}/auth/refresh`);
expect(getAccessToken()).toBe('new-token');
expect(calls[2].init?.headers).toMatchObject({ Authorization: 'Bearer new-token' });
});
it('on 401 with a failed refresh clears the token and dispatches fitos:logout', async () => {
setAccessToken('old-token');
const listener = vi.fn();
window.addEventListener('fitos:logout', listener);
const calls = mockFetchSequence(
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Unauthorized' } }),
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid refresh token' } }),
);
await expect(api('/admin/users')).rejects.toBeInstanceOf(ApiError);
expect(calls).toHaveLength(2);
expect(getAccessToken()).toBeNull();
expect(localStorage.getItem('fitos_admin_access')).toBeNull();
expect(listener).toHaveBeenCalledTimes(1);
window.removeEventListener('fitos:logout', listener);
});
it('does not attempt a refresh for the auth login endpoint', async () => {
const calls = mockFetchSequence(
jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'Invalid credentials' } }),
);
await expect(
api('/auth/login', { method: 'POST', body: { email: 'a@b.c', password: 'x' } }),
).rejects.toBeInstanceOf(ApiError);
expect(calls).toHaveLength(1);
});
it('persists the access token under the admin localStorage key', () => {
setAccessToken('abc');
expect(localStorage.getItem('fitos_admin_access')).toBe('abc');
setAccessToken(null);
expect(localStorage.getItem('fitos_admin_access')).toBeNull();
});
});

37
admin/test/setup.ts Normal file
View File

@@ -0,0 +1,37 @@
import '@testing-library/jest-dom/vitest';
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
// vitest runs with globals:false, so RTL auto-cleanup is not registered
// automatically; clean the DOM after every test.
afterEach(() => {
cleanup();
});
// Node 25 exposes a built-in `localStorage` global whose methods are unavailable
// without a valid --localstorage-file, and vitest's jsdom environment does not
// copy window.localStorage (a prototype property) onto globalThis.
// Provide a working in-memory implementation before app code reads it at import time.
const memory = new Map<string, string>();
const storage: Storage = {
getItem: (key: string) => (memory.has(key) ? memory.get(key)! : null),
setItem: (key: string, value: string) => {
memory.set(key, String(value));
},
removeItem: (key: string) => {
memory.delete(key);
},
clear: () => {
memory.clear();
},
key: (index: number) => [...memory.keys()][index] ?? null,
get length() {
return memory.size;
},
};
Object.defineProperty(globalThis, 'localStorage', {
value: storage,
configurable: true,
writable: true,
});

21
admin/tsconfig.app.json Normal file
View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"composite": true
},
"include": ["src"]
}

File diff suppressed because one or more lines are too long

14
admin/tsconfig.e2e.json Normal file
View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"moduleDetection": "force"
},
"include": ["e2e", "playwright.config.ts"]
}

4
admin/tsconfig.json Normal file
View File

@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.app.json" }]
}

11
admin/vite.config.ts Normal file
View File

@@ -0,0 +1,11 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 5174,
host: true,
},
});

14
admin/vitest.config.ts Normal file
View File

@@ -0,0 +1,14 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
esbuild: {
// test files are outside tsconfig.app.json (which sets jsx: react-jsx for src),
// so force the automatic JSX runtime for the whole transform
jsx: 'automatic',
},
test: {
environment: 'jsdom',
setupFiles: ['test/setup.ts'],
include: ['test/**/*.{test.ts,tsx}'],
},
});

4
api/.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
node_modules
dist
.env
*.log

10
api/.env.example Normal file
View File

@@ -0,0 +1,10 @@
DATABASE_URL=postgresql://fitos:fitos@localhost:5432/fitos
PORT=9002
NODE_ENV=development
JWT_ACCESS_SECRET=zmien-mna-access-secret
JWT_REFRESH_SECRET=zmien-mna-refresh-secret
FITOS_FIRST_ADMIN_EMAIL=admin@fitos.local
FITOS_FIRST_ADMIN_PASSWORD=ChangeMe123!
LOG_LEVEL=info
# true tylko gdy API jest serwowane po HTTPS (po HTTP przeglądarka odrzuca cookie Secure i refresh nie działa)
COOKIE_SECURE=false

6
api/.prettierrc.json Normal file
View File

@@ -0,0 +1,6 @@
{
"semi": true,
"singleQuote": true,
"printWidth": 100,
"trailingComma": "all"
}

21
api/Dockerfile Normal file
View File

@@ -0,0 +1,21 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY prisma ./prisma
RUN npx prisma generate
COPY tsconfig.json ./
COPY src ./src
RUN npm run build
FROM node:22-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci
COPY prisma ./prisma
RUN npx prisma generate
COPY --from=build /app/dist ./dist
EXPOSE 9002
# migrations (manual CLI, applied at startup) + idempotent seed + start
CMD ["sh", "-c", "npx prisma migrate deploy && node dist/seed.js && node dist/index.js"]

51
api/docker-compose.yml Normal file
View File

@@ -0,0 +1,51 @@
services:
api:
build: .
container_name: fitos-api
ports:
- "9002:9002"
environment:
DATABASE_URL: postgresql://fitos:fitos@db:5432/fitos
PORT: 9002
NODE_ENV: production
JWT_ACCESS_SECRET: ${JWT_ACCESS_SECRET:?set JWT_ACCESS_SECRET in .env}
JWT_REFRESH_SECRET: ${JWT_REFRESH_SECRET:?set JWT_REFRESH_SECRET in .env}
FITOS_FIRST_ADMIN_EMAIL: ${FITOS_FIRST_ADMIN_EMAIL:-admin@fitos.local}
FITOS_FIRST_ADMIN_PASSWORD: ${FITOS_FIRST_ADMIN_PASSWORD:-ChangeMe123!}
LOG_LEVEL: ${LOG_LEVEL:-info}
COOKIE_SECURE: ${COOKIE_SECURE:-false}
UPLOAD_DIR: /app/uploads
volumes:
- fitos_uploads:/app/uploads
depends_on:
db:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:9002/health"]
interval: 30s
timeout: 5s
retries: 5
start_period: 30s
restart: unless-stopped
db:
image: postgres:16-alpine
container_name: fitos-db
ports:
- "5432:5432"
environment:
POSTGRES_USER: fitos
POSTGRES_PASSWORD: fitos
POSTGRES_DB: fitos
volumes:
- fitos_pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U fitos -d fitos"]
interval: 10s
timeout: 5s
retries: 5
restart: unless-stopped
volumes:
fitos_pgdata:
fitos_uploads:

39
api/eslint.config.js Normal file
View File

@@ -0,0 +1,39 @@
import js from '@eslint/js';
import prettier from 'eslint-config-prettier';
import ts from '@typescript-eslint/eslint-plugin';
import tsParser from '@typescript-eslint/parser';
const files = ['**/*.{js,ts,mjs,cjs}'];
export default [
{ ignores: ['dist/', 'node_modules/'] },
{
...js.configs.recommended,
files,
languageOptions: {
parser: tsParser,
globals: {
console: 'readonly',
process: 'readonly',
module: 'readonly',
require: 'readonly',
__dirname: 'readonly',
setInterval: 'readonly',
clearInterval: 'readonly',
setTimeout: 'readonly',
clearTimeout: 'readonly',
},
},
plugins: {
'@typescript-eslint': ts,
},
rules: {
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
},
},
{
...prettier,
files,
},
];

Some files were not shown because too many files have changed in this diff Show More