Refaktoryzacja struktury i podział modułów (app/admin/api), konsolidacja testów w test/, komunikator (lista kontaktów, załącznik bez treści), profil podopiecznego (menu kontekstowe, nagłówek, zapamiętywanie zakładki), Tabs: strzałki poza scrollem + scroll-snap do całych zakładek, podniesione limity rate-limit

This commit is contained in:
tisachi
2026-09-04 23:19:28 +02:00
parent 1c8594ad96
commit e0f70ffa58
144 changed files with 5283 additions and 4788 deletions

5
.gitignore vendored
View File

@@ -4,6 +4,7 @@ dist/
*.log
.DS_Store
.vite/
test-results/
playwright-report/
**/test/results/
**/test/report/
blob-report/
*.tsbuildinfo

View File

@@ -4,17 +4,18 @@
- `app` (React+Vite, 5173), `admin` (React+Vite, 5174), `api` (Express+Prisma+PostgreSQL, 9002).
## Testy — obowiązkowe po każdej zmianie
- Konwencja: WSZYSTKIE testy projektu żyją w `<pkg>/test/` — unit/komponent w `test/*` (api: `test/unit/` + `test/integration/`), e2e w `test/e2e/`. Rezultaty i artefakty też pod `test/`: `test/results/` (trace/screenshoty Playwright) i `test/report/` (raport HTML) — oba gitignore'owane. Nie twórz katalogów testowych poza `test/`.
- `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.
- e2e bez API/DB: `mockApi(page, ...)` z `test/e2e/mock-api.ts`. Nowe pliki: `test/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
4. mocki `app|admin/test/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).

View File

@@ -72,11 +72,21 @@ npm run dev # http://localhost:5174
## Testy
W każdym projekcie: `npm test` (pojedynczy przebieg) lub `npm run test:watch`.
Konwencja: wszystkie testy projektu żyją w `<aplikacja>/test/` — razem z rezultatami:
```
<pkg>/test/
├── *.test.ts(x) # unit / komponent (vitest) [api: unit/ + integration/]
├── e2e/ # specy Playwright (app, admin) + fixtures/mock-api
├── results/ # artefakty Playwright (trace, screenshoty) — gitignore
└── report/ # raport HTML Playwright — gitignore
```
Uruchamianie: `npm test` (pojedynczy przebieg) lub `npm run test:watch`; e2e (app/admin): `npm run test:e2e` (dev server startuje sam, API mockowane).
### API (`api/`)
- Framework: Vitest + Supertest; testy w `api/test/` (unit + integration).
- 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`.
@@ -84,9 +94,10 @@ W każdym projekcie: `npm test` (pojedynczy przebieg) lub `npm run test:watch`.
### App i Admin (`app/`, `admin/`)
- Framework: Vitest + jsdom + Testing Library (React); testy w `test/`.
- Unit: 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`.
- E2E: Playwright w `test/e2e/` (`npm run test:e2e`); API mockowane przez `test/e2e/mock-api.ts`, rezultaty w `test/results/`, raport w `test/report/`.
## Kluczowe decyzje (MVP)

View File

@@ -1,12 +1,13 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
testDir: './test/e2e',
outputDir: './test/results',
timeout: 30_000,
expect: { timeout: 5_000 },
fullyParallel: true,
retries: process.env.CI ? 1 : 0,
reporter: [['list'], ['html', { open: 'never' }]],
reporter: [['list'], ['html', { outputFolder: 'test/report', open: 'never' }]],
use: {
baseURL: 'http://localhost:5174',
trace: 'on-first-retry',

View File

@@ -3,15 +3,15 @@ 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 GymsList from './pages/gyms/GymsList';
import GymForm from './pages/gyms/GymForm';
import GymDetail from './pages/gyms/GymDetail';
import UsersList from './pages/users/UsersList';
import UserForm from './pages/users/UserForm';
import UserDetail from './pages/users/UserDetail';
import FocusAreas from './pages/catalog/FocusAreas';
import Exercises from './pages/catalog/Exercises';
import EquipmentCatalog from './pages/catalog/Equipment';
import Logs from './pages/Logs';
import VerificationsList, { VerificationDetail } from './pages/Verifications';

View File

@@ -5,12 +5,9 @@ import type {
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 { Button as UIButton } from './ui/button';
import { Card as UICard } from './ui/card';
import { Badge as UIBadge } from './ui/badge';
import { Input as UIInput } from './ui/input';
@@ -20,14 +17,11 @@ 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';
export * from './ui/typography';
export * from './ui/content';
export * from './ui/dialogs';
export * from './ui/theme-toggle';
/* Button */
export type ButtonVariant = 'primary' | 'secondary' | 'danger' | 'ghost';
@@ -127,172 +121,7 @@ export function Field({
);
}
/* 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>;
}
@@ -301,152 +130,12 @@ 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,206 @@
import type { ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { ArrowLeft, X } from 'lucide-react';
import { buttonVariants } from './button';
import { H1, H2, H3, Muted } from './typography';
import { cn } from '../../lib/utils';
/* 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>
);
}
/* 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>
);
}
/* 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>
);
}

View File

@@ -0,0 +1,80 @@
import type { ReactNode } from 'react';
import { X } from 'lucide-react';
import { Button } from './button';
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from './dialog';
/* 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>
);
}

View File

@@ -0,0 +1,16 @@
import { Moon, Sun } from 'lucide-react';
import { useTheme } from '../../store/theme';
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,21 @@
import type { ReactNode } from 'react';
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>;
}
export function Muted({ className = '', children }: { className?: string; children: ReactNode }) {
return <span className={`text-dim ${className}`.trim()}>{children}</span>;
}
export function Loading({ children = 'Ładowanie…' }: { children?: ReactNode }) {
return <div className="text-dim">{children}</div>;
}

View File

@@ -1,11 +1,11 @@
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 { 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,
@@ -19,7 +19,7 @@ import {
Muted,
Select,
Textarea,
} from '../components/ui';
} from '../../components/ui';
interface FormState {
name: string;

View File

@@ -1,10 +1,10 @@
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 { api } from '../../api/client';
import type { Equipment, Exercise } from '../../api/types';
import { useTopbar } from '../../topbar';
import { useListSearch } from '../../store/list-search';
import {
Badge,
Button,
@@ -17,7 +17,7 @@ import {
Loading,
Modal,
Muted,
} from '../components/ui';
} from '../../components/ui';
interface FormState {
name: string;

View File

@@ -1,10 +1,10 @@
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 { api } from '../../api/client';
import type { FocusArea } from '../../api/types';
import { useTopbar } from '../../topbar';
import { useListSearch } from '../../store/list-search';
import {
Badge,
Button,
@@ -18,7 +18,7 @@ import {
Modal,
Muted,
Textarea,
} from '../components/ui';
} from '../../components/ui';
interface FormState {
name: string;

View File

@@ -2,11 +2,11 @@ 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 { 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,
@@ -22,9 +22,9 @@ import {
SectionHeader,
Select,
SuccessText,
} from '../components/ui';
import { AvailabilityEditor } from '../components/AvailabilityEditor';
import { formatAvailability, normalizeAvailability, TIME_SLOTS } from '../lib/availability';
} 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 (

View File

@@ -1,11 +1,11 @@
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';
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' });

View File

@@ -2,12 +2,12 @@ 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 { 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() {

View File

@@ -2,9 +2,9 @@ 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 { useTopbar } from '../../topbar';
import { api } from '../../api/client';
import type { FocusArea, FocusChain, Gym, GymRole, User } from '../../api/types';
import {
BackButton,
Badge,
@@ -22,11 +22,11 @@ import {
SectionHeader,
Select,
SuccessText,
} from '../components/ui';
} from '../../components/ui';
import { userName } from './UsersList';
import { AvailabilityEditor } from '../components/AvailabilityEditor';
import { Avatar } from '../components/Avatar';
import { formatAvailability, normalizeAvailability } from '../lib/availability';
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',

View File

@@ -1,8 +1,8 @@
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';
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' });

View File

@@ -2,12 +2,12 @@ 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';
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;

View File

@@ -17,6 +17,5 @@ export function useTopbar(config: TopbarConfig) {
useEffect(() => {
registerPage(config);
return () => registerPage(null);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}

View File

@@ -3,7 +3,7 @@ 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 EquipmentCatalog from '../src/pages/catalog/Equipment';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import { useListSearch } from '../src/store/list-search';

View File

@@ -3,7 +3,7 @@ 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 Exercises from '../src/pages/catalog/Exercises';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';

View File

@@ -2,7 +2,7 @@ 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 FocusAreas from '../src/pages/catalog/FocusAreas';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import type { FocusArea } from '../src/api/types';

View File

@@ -2,7 +2,7 @@ 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 GymDetail from '../src/pages/gyms/GymDetail';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import type { Equipment, Gym } from '../src/api/types';

View File

@@ -3,7 +3,7 @@ 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 GymsList from '../src/pages/gyms/GymsList';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import type { Gym } from '../src/api/types';

View File

@@ -3,7 +3,7 @@ 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 UserDetail from '../src/pages/users/UserDetail';
import { setAccessToken } from '../src/api/client';
import { API_BASE } from '../src/config';
import type { Gym, User } from '../src/api/types';

View File

@@ -2,7 +2,7 @@ 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 UserForm from '../src/pages/users/UserForm';
import { setAccessToken } from '../src/api/client';
import { API_BASE } from '../src/config';
import type { User } from '../src/api/types';

View File

@@ -2,7 +2,7 @@ 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 UsersList from '../src/pages/users/UsersList';
import { setAccessToken } from '../src/api/client';
import { useListSearch } from '../src/store/list-search';
import type { User } from '../src/api/types';

View File

@@ -1,5 +1,5 @@
import type { Page } from '@playwright/test';
import type { ActivityLog, Gym, GymClaim, User } from '../src/api/types';
import type { ActivityLog, Equipment, Gym, GymClaim, User } from '../../src/api/types';
export const TEST_ADMIN = {
id: 'admin-test',
@@ -20,9 +20,25 @@ export const TEST_ADMIN = {
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_EQUIPMENT: Equipment[] = [
{
id: 'eq-1',
name: 'Sztanga',
kind: 'BARBELL',
spec: { maxLoadKg: 100 },
description: 'Sztanga z talerzami.',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'eq-2',
name: 'Dywan',
kind: 'OTHER',
spec: null,
description: 'Dywan do ćwiczeń.',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
];
export const TEST_GYM_PHOTOS = [
@@ -115,6 +131,8 @@ export const TEST_USER: User = {
email: 'jan@fitos.pl',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
socialMedia: null,
age: 30,
heightCm: 180,
phone: '+48 500 100 200',
@@ -331,7 +349,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
page.route('**/api/v1/admin/gyms', (route) => {
const list = (gyms as { gyms?: Array<Record<string, unknown>> } | null)?.gyms;
const body = list
const body = list && gyms
? {
...gyms,
gyms: list.map((g) => (g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g)),

File diff suppressed because one or more lines are too long

View File

@@ -10,5 +10,5 @@
"isolatedModules": true,
"moduleDetection": "force"
},
"include": ["e2e", "playwright.config.ts"]
"include": ["test/e2e", "playwright.config.ts"]
}

View File

@@ -29,7 +29,7 @@ export default [
},
rules: {
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }],
},
},
{

View File

@@ -3,9 +3,15 @@ import rateLimit from 'express-rate-limit';
/** Standard error body — spójny z resztą API (JSON, nie plain text). */
export const RATE_LIMIT_BODY = { error: { code: 'RATE_LIMITED', message: 'Too many requests, try later' } };
/**
* Globalny limit per IP. SPA robi dużo równoległych zapytań (strona = kilka
* query React Query, staleTime=0 refetchuje przy nawigacji), a app i admin
* dzielą jedno IP — limit musi być wysoki, żeby normalne korzystanie nie
* blokowało nawet logowania. Ochronę anty-brute-force robi authLimiter.
*/
export const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
limit: 1500,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: RATE_LIMIT_BODY,
@@ -13,7 +19,7 @@ export const apiLimiter = rateLimit({
export const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 20,
limit: 50,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: { error: { code: 'RATE_LIMITED', message: 'Too many attempts, try later' } },

View File

@@ -1,119 +1,35 @@
import fs from 'node:fs';
import path from 'node:path';
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
acceptGymInvitation,
addEquipment,
addGymPhotos,
canManageGym,
createGym,
createGymClaim,
createOwnedGymException,
declineGymInvitation,
deleteGymPhoto,
deleteOwnedGym,
deleteOwnedGymException,
getGymPublic,
joinGym,
listAllGyms,
listGymInvitations,
listMyGymClaims,
listOwnedGymExceptions,
listUserGyms,
listVirtualGyms,
rateGym,
removeEquipment,
searchGymInvitees,
sendGymInvitation,
setGymPhotoCover,
updateEquipmentQuantity,
updateOwnedGym,
withdrawGymClaim,
withdrawGymInvitation,
} from '../services/gyms.js';
import { availabilitySchema } from './me.js';
import type { Availability } from '../services/me.js';
import { logActivity } from '../services/audit.js';
import { config } from '../config.js';
import {
MAX_CLAIM_FILES,
MAX_PHOTO_FILES,
claimUpload,
gymPhotoUpload,
photoUploadDir,
removeTmpFiles,
} from '../lib/uploads.js';
import { badRequest, forbidden, notFound } from '../lib/errors.js';
import { createGymSchema, rateGymSchema, updateGymSchema } from './gyms/schemas.js';
import { createGymClaimRoutes } from './gyms/claims.js';
import { createGymInvitationRoutes } from './gyms/invitations.js';
import { createGymPhotoRoutes } from './gyms/photos.js';
import { createGymManagementRoutes } from './gyms/management.js';
const createGymSchema = z.object({
name: z.string().min(1).max(200),
location: z.string().max(500).nullable().optional(),
availability: availabilitySchema,
capacity: z.number().int().positive().max(100000).nullable().optional(),
kind: z.enum(['VIRTUAL', 'REAL']).optional(),
isPrivate: z.boolean().optional(),
});
const updateGymSchema = createGymSchema.partial().omit({ kind: true });
const rateGymSchema = z.object({
vote: z.enum(['UP', 'DOWN']),
});
/** Multipart fields arrive as strings (multer) — gymAvailability is a JSON string. */
const gymClaimSchema = z.object({
gymId: z.string().min(1).optional(),
description: z.string().min(1).max(5000),
companyName: z.string().max(200).optional(),
nip: z.string().regex(/^\d{10}$/).optional(),
phone: z.string().max(20).optional(),
email: z.string().email().max(200).optional(),
address: z.string().max(500).optional(),
gymName: z.string().min(1).max(200).optional(),
gymLocation: z.string().max(500).optional(),
gymAvailability: z.string().optional(),
gymCapacity: z.coerce.number().int().positive().max(100000).optional(),
});
const gymInvitationSchema = z.object({
gymId: z.string().min(1),
userId: z.string().min(1),
});
const gymInviteeSearchSchema = z.object({
gymId: z.string().min(1),
firstName: z.string().min(1).max(100),
lastName: z.string().min(1).max(100),
});
const gymExceptionSchema = z.object({
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
availability: z
.object({
start: z.string().regex(/^\d{2}:\d{2}$/),
end: z.string().regex(/^\d{2}:\d{2}$/),
})
.nullable()
.optional(),
});
const equipmentSchema = z.object({
equipmentId: z.string().min(1),
quantity: z.number().int().min(1).max(10000).optional(),
});
const equipmentQuantitySchema = z.object({
quantity: z.number().int().min(1).max(10000),
});
export function createGymRoutes({ prisma }: AppDeps) {
export function createGymRoutes(deps: AppDeps) {
const { prisma } = deps;
const router = Router();
router.use(authenticate(prisma));
// Static prefixes first — before any /:gymId handler.
router.use('/claims', createGymClaimRoutes(deps));
router.use('/invitations', createGymInvitationRoutes(deps));
/**
* @openapi
* /gyms:
@@ -122,7 +38,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
*/
router.get('/', async (req, res, next) => {
try {
const result = await listUserGyms(prisma, req.user!.id);
@@ -140,7 +56,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
*/
router.get('/all', async (_req, res, next) => {
try {
const result = await listAllGyms(prisma);
@@ -160,7 +76,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* 201: { description: Created }
* 400: { description: Validation failed (e.g. missing location for VIRTUAL) }
* 403: { description: Non-admin requested kind=REAL }
*/
*/
router.post('/', validate(createGymSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof createGymSchema>;
@@ -186,7 +102,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
*/
router.get('/virtual', async (req, res, next) => {
try {
const result = await listVirtualGyms(prisma, req.user!.id);
@@ -196,284 +112,9 @@ export function createGymRoutes({ prisma }: AppDeps) {
}
});
/**
* @openapi
* /gyms/claims:
* post:
* summary: Submit a gym claim (multipart; verification of a virtual gym or a new real gym)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 400: { description: Validation failed (fields or files) }
* 404: { description: Gym not found }
* 409: { description: Gym is not virtual / pending claim already exists }
*/
router.post(
'/claims',
(req, res, next) =>
claimUpload.array('files', MAX_CLAIM_FILES)(req, res, (err) => {
if (err) {
const message =
err.code === 'LIMIT_FILE_SIZE'
? 'File too large (max 5 MB)'
: err.code === 'LIMIT_FILE_COUNT'
? 'Too many files (max 5)'
: err.message;
return next(badRequest(message));
}
next();
}),
validate(gymClaimSchema),
async (req, res, next) => {
try {
const body = req.body as z.infer<typeof gymClaimSchema>;
let gymAvailability: Availability | null | undefined;
if (body.gymAvailability) {
try {
gymAvailability = availabilitySchema.parse(JSON.parse(body.gymAvailability));
} catch {
throw badRequest('Invalid gym availability');
}
}
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
originalName: f.originalname,
mimeType: f.mimetype,
sizeBytes: f.size,
path: f.path,
}));
const result = await createGymClaim(
prisma,
req.user!.id,
{
gymId: body.gymId,
description: body.description,
companyName: body.companyName,
nip: body.nip,
phone: body.phone,
email: body.email,
address: body.address,
gymName: body.gymName,
gymLocation: body.gymLocation,
gymAvailability,
gymCapacity: body.gymCapacity,
},
files,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.created',
entityType: 'gym-claim',
entityId: result.claim.id,
details: { gymId: result.claim.gymId, type: result.claim.type },
});
res.status(201).json(result);
} catch (e) {
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
next(e);
}
},
);
/**
* @openapi
* /gyms/claims:
* get:
* summary: The user's own gym claims (all statuses)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/claims', async (req, res, next) => {
try {
const result = await listMyGymClaims(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/claims/{claimId}:
* delete:
* summary: Withdraw the user's own PENDING gym claim
* tags: [Gyms]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Not the claim author }
* 409: { description: Claim is not pending }
*/
router.delete('/claims/:claimId', async (req, res, next) => {
try {
await withdrawGymClaim(prisma, req.user!.id, req.params.claimId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.withdrawn',
entityType: 'gym-claim',
entityId: req.params.claimId,
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations:
* post:
* summary: Invite a user to a private virtual gym (owner only)
* tags: [Gyms]
* responses:
* 201: { description: Invitation sent }
* 400: { description: Cannot invite yourself }
* 403: { description: Not the gym owner }
* 404: { description: Gym or user not found }
* 409: { description: Gym not private virtual / already a member / pending invitation exists }
*/
router.post('/invitations', validate(gymInvitationSchema), async (req, res, next) => {
try {
const { gymId, userId } = req.body as z.infer<typeof gymInvitationSchema>;
const result = await sendGymInvitation(prisma, req.user!.id, gymId, userId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invited',
entityType: 'gym-invitation',
entityId: result.invitation.id,
details: { gymId, userId },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations:
* get:
* summary: The user's pending gym invitations (sent and received)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/invitations', async (req, res, next) => {
try {
const result = await listGymInvitations(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/search:
* get:
* summary: Search users to invite to a private virtual gym (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Gym not found }
*/
router.get(
'/invitations/search',
validate(gymInviteeSearchSchema, 'query'),
async (req, res, next) => {
try {
const q = req.query as z.infer<typeof gymInviteeSearchSchema>;
const result = await searchGymInvitees(
prisma,
req.user!.id,
q.gymId,
q.firstName,
q.lastName,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/invitations/{invitationId}/accept:
* post:
* summary: Accept a gym invitation (invited user only) → MEMBER
* tags: [Gyms]
* responses:
* 200: { description: Accepted }
* 403: { description: Not the invited user }
* 410: { description: Invitation expired }
*/
router.post('/invitations/:invitationId/accept', async (req, res, next) => {
try {
const result = await acceptGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.accepted',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/{invitationId}/decline:
* post:
* summary: Decline a gym invitation (invited user only)
* tags: [Gyms]
* responses:
* 200: { description: Declined }
* 403: { description: Not the invited user }
* 410: { description: Invitation expired }
*/
router.post('/invitations/:invitationId/decline', async (req, res, next) => {
try {
const result = await declineGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.declined',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/{invitationId}:
* delete:
* summary: Withdraw a pending gym invitation (sender only)
* tags: [Gyms]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Not the sender }
* 409: { description: Invitation is not pending }
*/
router.delete('/invitations/:invitationId', async (req, res, next) => {
try {
await withdrawGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.withdrawn',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.status(204).end();
} catch (e) {
next(e);
}
});
// Per-gym sub-routes: gallery photos, then equipment/exceptions.
router.use('/:gymId/photos', createGymPhotoRoutes(deps));
router.use('/:gymId', createGymManagementRoutes(deps));
/**
* @openapi
@@ -485,7 +126,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* 200: { description: OK, returns { gym, roles, isAdmin } }
* 403: { description: VIRTUAL gym and the caller is not a manager }
* 404: { description: Gym not found }
*/
*/
router.get('/:gymId', async (req, res, next) => {
try {
const result = await getGymPublic(prisma, req.user!.id, req.user!.isAdmin, req.params.gymId);
@@ -495,160 +136,6 @@ export function createGymRoutes({ prisma }: AppDeps) {
}
});
/**
* @openapi
* /gyms/{gymId}/photos:
* post:
* summary: Add photos to a REAL gym's gallery (owner or admin; multipart field `photos`)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 400: { description: Validation failed (file type/size/count or photo limit) }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Gym not found }
* 409: { description: Gym is not REAL }
*/
router.post(
'/:gymId/photos',
(req, res, next) =>
gymPhotoUpload.array('photos', MAX_PHOTO_FILES)(req, res, (err) => {
if (err) {
const message =
err.code === 'LIMIT_FILE_SIZE'
? 'File too large (max 5 MB)'
: err.code === 'LIMIT_FILE_COUNT'
? 'Too many files (max 10)'
: err.message;
return next(badRequest(message));
}
next();
}),
async (req, res, next) => {
try {
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
mimeType: f.mimetype,
sizeBytes: f.size,
path: f.path,
}));
const result = await addGymPhotos(
prisma,
req.user!.id,
req.user!.isAdmin,
req.params.gymId,
files,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photos.added',
entityType: 'gym',
entityId: req.params.gymId,
details: { count: files.length },
});
res.json(result);
} catch (e) {
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}:
* delete:
* summary: Remove a photo from a gym's gallery (owner or admin)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Photo not found }
*/
router.delete('/:gymId/photos/:photoId', async (req, res, next) => {
try {
const result = await deleteGymPhoto(
prisma,
req.user!.id,
req.user!.isAdmin,
req.params.gymId,
req.params.photoId,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photo.deleted',
entityType: 'gym',
entityId: req.params.gymId,
details: { photoId: req.params.photoId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}/cover:
* patch:
* summary: Set a photo as the gallery cover (owner or admin)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Photo not found }
*/
router.patch('/:gymId/photos/:photoId/cover', async (req, res, next) => {
try {
const result = await setGymPhotoCover(
prisma,
req.user!.id,
req.user!.isAdmin,
req.params.gymId,
req.params.photoId,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photo.cover',
entityType: 'gym',
entityId: req.params.gymId,
details: { photoId: req.params.photoId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}:
* get:
* summary: Serve a gym photo (REAL visible to all logged-in users; VIRTUAL to managers)
* tags: [Gyms]
* responses:
* 200: { description: Image bytes with the stored Content-Type }
* 403: { description: VIRTUAL gym and the caller is not a manager }
* 404: { description: Photo not found or file missing }
*/
router.get('/:gymId/photos/:photoId', async (req, res, next) => {
try {
const { gymId, photoId } = req.params;
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin)))
throw forbidden('You do not have access to this gym');
const filePath = path.join(photoUploadDir(gymId), photo.storedName);
if (!fs.existsSync(filePath)) throw notFound('Photo file not found');
res.type(photo.mimeType);
await new Promise<void>((resolve, reject) => {
res.sendFile(filePath, (err) => (err ? reject(err) : resolve()));
});
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/join:
@@ -658,7 +145,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* responses:
* 201: { description: Joined }
* 409: { description: Already a member }
*/
*/
router.post('/:gymId/join', async (req, res, next) => {
try {
const result = await joinGym(prisma, req.user!.id, req.params.gymId);
@@ -686,7 +173,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* 403: { description: The gym owner cannot rate their own gym }
* 404: { description: Gym not found }
* 409: { description: Gym is not a public virtual gym }
*/
*/
router.post('/:gymId/rate', validate(rateGymSchema), async (req, res, next) => {
try {
const { vote } = req.body as z.infer<typeof rateGymSchema>;
@@ -697,88 +184,6 @@ export function createGymRoutes({ prisma }: AppDeps) {
}
});
/**
* @openapi
* /gyms/{gymId}/equipment:
* post:
* summary: Add a catalog equipment item to a gym with a quantity (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Equipment not found }
* 409: { description: Equipment already exists (update its quantity instead) }
*/
router.post(
'/:gymId/equipment',
validate(equipmentSchema),
async (req, res, next) => {
try {
const { equipmentId, quantity } = req.body as z.infer<typeof equipmentSchema>;
const result = await addEquipment(
prisma,
req.params.gymId,
req.user!.id,
equipmentId,
quantity ?? 1,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/equipment/{equipmentId}:
* patch:
* summary: Change the quantity of a gym's equipment item (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 400: { description: Equipment not in the gym }
*/
router.patch(
'/:gymId/equipment/:equipmentId',
validate(equipmentQuantitySchema),
async (req, res, next) => {
try {
const { quantity } = req.body as z.infer<typeof equipmentQuantitySchema>;
const result = await updateEquipmentQuantity(
prisma,
req.params.gymId,
req.user!.id,
req.params.equipmentId,
quantity,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/equipment/{equipmentId}:
* delete:
* summary: Remove a catalog equipment item from a gym (owner only)
* tags: [Gyms]
* responses:
* 204: { description: Removed }
* 403: { description: Not the gym owner }
*/
router.delete('/:gymId/equipment/:equipmentId', async (req, res, next) => {
try {
await removeEquipment(prisma, req.params.gymId, req.user!.id, req.params.equipmentId);
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}:
@@ -789,7 +194,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Gym not found }
*/
*/
router.patch('/:gymId', validate(updateGymSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof updateGymSchema>;
@@ -817,7 +222,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
* 204: { description: Deleted }
* 403: { description: Not the gym owner }
* 404: { description: Gym not found }
*/
*/
router.delete('/:gymId', async (req, res, next) => {
try {
const result = await deleteOwnedGym(prisma, req.params.gymId, req.user!.id);
@@ -834,77 +239,5 @@ export function createGymRoutes({ prisma }: AppDeps) {
}
});
/**
* @openapi
* /gyms/{gymId}/exceptions:
* get:
* summary: List a gym's schedule exceptions (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
*/
router.get('/:gymId/exceptions', async (req, res, next) => {
try {
const result = await listOwnedGymExceptions(prisma, req.params.gymId, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/exceptions:
* post:
* summary: Add a one-off schedule exception (owner only)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 403: { description: Not the gym owner }
* 409: { description: Exception already exists for this date }
*/
router.post(
'/:gymId/exceptions',
validate(gymExceptionSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof gymExceptionSchema>;
const result = await createOwnedGymException(prisma, req.params.gymId, req.user!.id, {
date: data.date,
availability: data.availability ?? null,
});
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/exceptions/{exceptionId}:
* delete:
* summary: Remove a schedule exception (owner only)
* tags: [Gyms]
* responses:
* 204: { description: Removed }
* 403: { description: Not the gym owner }
* 404: { description: Exception not found }
*/
router.delete('/:gymId/exceptions/:exceptionId', async (req, res, next) => {
try {
await deleteOwnedGymException(
prisma,
req.params.gymId,
req.user!.id,
req.params.exceptionId,
);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,140 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../../deps.js';
import { validate } from '../../middleware/validate.js';
import { createGymClaim, listMyGymClaims, withdrawGymClaim } from '../../services/gyms.js';
import { availabilitySchema } from '../me.js';
import type { Availability } from '../../services/me.js';
import { logActivity } from '../../services/audit.js';
import { MAX_CLAIM_FILES, claimUpload, removeTmpFiles } from '../../lib/uploads.js';
import { badRequest } from '../../lib/errors.js';
import { gymClaimSchema } from './schemas.js';
/** Mounted at /gyms/claims. */
export function createGymClaimRoutes({ prisma }: AppDeps) {
const router = Router();
/**
* @openapi
* /gyms/claims:
* post:
* summary: Submit a gym claim (multipart; verification of a virtual gym or a new real gym)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 400: { description: Validation failed (fields or files) }
* 404: { description: Gym not found }
* 409: { description: Gym is not virtual / pending claim already exists }
*/
router.post(
'/',
(req, res, next) =>
claimUpload.array('files', MAX_CLAIM_FILES)(req, res, (err) => {
if (err) {
const message =
err.code === 'LIMIT_FILE_SIZE'
? 'File too large (max 5 MB)'
: err.code === 'LIMIT_FILE_COUNT'
? 'Too many files (max 5)'
: err.message;
return next(badRequest(message));
}
next();
}),
validate(gymClaimSchema),
async (req, res, next) => {
try {
const body = req.body as z.infer<typeof gymClaimSchema>;
let gymAvailability: Availability | null | undefined;
if (body.gymAvailability) {
try {
gymAvailability = availabilitySchema.parse(JSON.parse(body.gymAvailability));
} catch {
throw badRequest('Invalid gym availability');
}
}
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
originalName: f.originalname,
mimeType: f.mimetype,
sizeBytes: f.size,
path: f.path,
}));
const result = await createGymClaim(
prisma,
req.user!.id,
{
gymId: body.gymId,
description: body.description,
companyName: body.companyName,
nip: body.nip,
phone: body.phone,
email: body.email,
address: body.address,
gymName: body.gymName,
gymLocation: body.gymLocation,
gymAvailability,
gymCapacity: body.gymCapacity,
},
files,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.created',
entityType: 'gym-claim',
entityId: result.claim.id,
details: { gymId: result.claim.gymId, type: result.claim.type },
});
res.status(201).json(result);
} catch (e) {
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
next(e);
}
},
);
/**
* @openapi
* /gyms/claims:
* get:
* summary: The user's own gym claims (all statuses)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/', async (req, res, next) => {
try {
const result = await listMyGymClaims(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/claims/{claimId}:
* delete:
* summary: Withdraw the user's own PENDING gym claim
* tags: [Gyms]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Not the claim author }
* 409: { description: Claim is not pending }
*/
router.delete('/:claimId', async (req, res, next) => {
try {
await withdrawGymClaim(prisma, req.user!.id, req.params.claimId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.withdrawn',
entityType: 'gym-claim',
entityId: req.params.claimId,
});
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,178 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../../deps.js';
import { validate } from '../../middleware/validate.js';
import {
acceptGymInvitation,
declineGymInvitation,
listGymInvitations,
searchGymInvitees,
sendGymInvitation,
withdrawGymInvitation,
} from '../../services/gyms.js';
import { logActivity } from '../../services/audit.js';
import { gymInvitationSchema, gymInviteeSearchSchema } from './schemas.js';
/** Mounted at /gyms/invitations. */
export function createGymInvitationRoutes({ prisma }: AppDeps) {
const router = Router();
/**
* @openapi
* /gyms/invitations:
* post:
* summary: Invite a user to a private virtual gym (owner only)
* tags: [Gyms]
* responses:
* 201: { description: Invitation sent }
* 400: { description: Cannot invite yourself }
* 403: { description: Not the gym owner }
* 404: { description: Gym or user not found }
* 409: { description: Gym not private virtual / already a member / pending invitation exists }
*/
router.post('/', validate(gymInvitationSchema), async (req, res, next) => {
try {
const { gymId, userId } = req.body as z.infer<typeof gymInvitationSchema>;
const result = await sendGymInvitation(prisma, req.user!.id, gymId, userId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invited',
entityType: 'gym-invitation',
entityId: result.invitation.id,
details: { gymId, userId },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations:
* get:
* summary: The user's pending gym invitations (sent and received)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/', async (req, res, next) => {
try {
const result = await listGymInvitations(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/search:
* get:
* summary: Search users to invite to a private virtual gym (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Gym not found }
*/
router.get(
'/search',
validate(gymInviteeSearchSchema, 'query'),
async (req, res, next) => {
try {
const q = req.query as z.infer<typeof gymInviteeSearchSchema>;
const result = await searchGymInvitees(
prisma,
req.user!.id,
q.gymId,
q.firstName,
q.lastName,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/invitations/{invitationId}/accept:
* post:
* summary: Accept a gym invitation (invited user only) → MEMBER
* tags: [Gyms]
* responses:
* 200: { description: Accepted }
* 403: { description: Not the invited user }
* 410: { description: Invitation expired }
*/
router.post('/:invitationId/accept', async (req, res, next) => {
try {
const result = await acceptGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.accepted',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/{invitationId}/decline:
* post:
* summary: Decline a gym invitation (invited user only)
* tags: [Gyms]
* responses:
* 200: { description: Declined }
* 403: { description: Not the invited user }
* 410: { description: Invitation expired }
*/
router.post('/:invitationId/decline', async (req, res, next) => {
try {
const result = await declineGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.declined',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/{invitationId}:
* delete:
* summary: Withdraw a pending gym invitation (sender only)
* tags: [Gyms]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Not the sender }
* 409: { description: Invitation is not pending }
*/
router.delete('/:invitationId', async (req, res, next) => {
try {
await withdrawGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.withdrawn',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,182 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../../deps.js';
import { validate } from '../../middleware/validate.js';
import {
addEquipment,
createOwnedGymException,
deleteOwnedGymException,
listOwnedGymExceptions,
removeEquipment,
updateEquipmentQuantity,
} from '../../services/gyms.js';
import { equipmentQuantitySchema, equipmentSchema, gymExceptionSchema } from './schemas.js';
type GymParams = { gymId: string };
/** Mounted at /gyms/:gymId (mergeParams) — equipment and schedule exceptions. */
export function createGymManagementRoutes({ prisma }: AppDeps) {
const router = Router({ mergeParams: true });
/**
* @openapi
* /gyms/{gymId}/equipment:
* post:
* summary: Add a catalog equipment item to a gym with a quantity (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Equipment not found }
* 409: { description: Equipment already exists (update its quantity instead) }
*/
router.post(
'/equipment',
validate(equipmentSchema),
async (req, res, next) => {
try {
const { equipmentId, quantity } = req.body as z.infer<typeof equipmentSchema>;
const { gymId } = req.params as GymParams;
const result = await addEquipment(
prisma,
gymId,
req.user!.id,
equipmentId,
quantity ?? 1,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/equipment/{equipmentId}:
* patch:
* summary: Change the quantity of a gym's equipment item (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 400: { description: Equipment not in the gym }
*/
router.patch(
'/equipment/:equipmentId',
validate(equipmentQuantitySchema),
async (req, res, next) => {
try {
const { quantity } = req.body as z.infer<typeof equipmentQuantitySchema>;
const { gymId } = req.params as GymParams;
const result = await updateEquipmentQuantity(
prisma,
gymId,
req.user!.id,
req.params.equipmentId,
quantity,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/equipment/{equipmentId}:
* delete:
* summary: Remove a catalog equipment item from a gym (owner only)
* tags: [Gyms]
* responses:
* 204: { description: Removed }
* 403: { description: Not the gym owner }
*/
router.delete('/equipment/:equipmentId', async (req, res, next) => {
try {
const { gymId, equipmentId } = req.params as GymParams & { equipmentId: string };
await removeEquipment(prisma, gymId, req.user!.id, equipmentId);
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/exceptions:
* get:
* summary: List a gym's schedule exceptions (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
*/
router.get('/exceptions', async (req, res, next) => {
try {
const { gymId } = req.params as GymParams;
const result = await listOwnedGymExceptions(prisma, gymId, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/exceptions:
* post:
* summary: Add a one-off schedule exception (owner only)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 403: { description: Not the gym owner }
* 409: { description: Exception already exists for this date }
*/
router.post(
'/exceptions',
validate(gymExceptionSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof gymExceptionSchema>;
const { gymId } = req.params as GymParams;
const result = await createOwnedGymException(prisma, gymId, req.user!.id, {
date: data.date,
availability: data.availability ?? null,
});
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/exceptions/{exceptionId}:
* delete:
* summary: Remove a schedule exception (owner only)
* tags: [Gyms]
* responses:
* 204: { description: Removed }
* 403: { description: Not the gym owner }
* 404: { description: Exception not found }
*/
router.delete('/exceptions/:exceptionId', async (req, res, next) => {
try {
const { gymId, exceptionId } = req.params as GymParams & { exceptionId: string };
await deleteOwnedGymException(
prisma,
gymId,
req.user!.id,
exceptionId,
);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,179 @@
import fs from 'node:fs';
import path from 'node:path';
import { Router } from 'express';
import type { AppDeps } from '../../deps.js';
import {
addGymPhotos,
canManageGym,
deleteGymPhoto,
setGymPhotoCover,
} from '../../services/gyms.js';
import { logActivity } from '../../services/audit.js';
import { MAX_PHOTO_FILES, gymPhotoUpload, photoUploadDir, removeTmpFiles } from '../../lib/uploads.js';
import { badRequest, forbidden, notFound } from '../../lib/errors.js';
type GymParams = { gymId: string };
/** Mounted at /gyms/:gymId/photos (mergeParams). */
export function createGymPhotoRoutes({ prisma }: AppDeps) {
const router = Router({ mergeParams: true });
/**
* @openapi
* /gyms/{gymId}/photos:
* post:
* summary: Add photos to a REAL gym's gallery (owner or admin; multipart field `photos`)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 400: { description: Validation failed (file type/size/count or photo limit) }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Gym not found }
* 409: { description: Gym is not REAL }
*/
router.post(
'/',
(req, res, next) =>
gymPhotoUpload.array('photos', MAX_PHOTO_FILES)(req, res, (err) => {
if (err) {
const message =
err.code === 'LIMIT_FILE_SIZE'
? 'File too large (max 5 MB)'
: err.code === 'LIMIT_FILE_COUNT'
? 'Too many files (max 10)'
: err.message;
return next(badRequest(message));
}
next();
}),
async (req, res, next) => {
const { gymId } = req.params as GymParams;
try {
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
mimeType: f.mimetype,
sizeBytes: f.size,
path: f.path,
}));
const result = await addGymPhotos(
prisma,
req.user!.id,
req.user!.isAdmin,
gymId,
files,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photos.added',
entityType: 'gym',
entityId: gymId,
details: { count: files.length },
});
res.json(result);
} catch (e) {
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}:
* delete:
* summary: Remove a photo from a gym's gallery (owner or admin)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Photo not found }
*/
router.delete('/:photoId', async (req, res, next) => {
const { gymId, photoId } = req.params as GymParams & { photoId: string };
try {
const result = await deleteGymPhoto(
prisma,
req.user!.id,
req.user!.isAdmin,
gymId,
photoId,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photo.deleted',
entityType: 'gym',
entityId: gymId,
details: { photoId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}/cover:
* patch:
* summary: Set a photo as the gallery cover (owner or admin)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Photo not found }
*/
router.patch('/:photoId/cover', async (req, res, next) => {
const { gymId, photoId } = req.params as GymParams & { photoId: string };
try {
const result = await setGymPhotoCover(
prisma,
req.user!.id,
req.user!.isAdmin,
gymId,
photoId,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photo.cover',
entityType: 'gym',
entityId: gymId,
details: { photoId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}:
* get:
* summary: Serve a gym photo (REAL visible to all logged-in users; VIRTUAL to managers)
* tags: [Gyms]
* responses:
* 200: { description: Image bytes with the stored Content-Type }
* 403: { description: VIRTUAL gym and the caller is not a manager }
* 404: { description: Photo not found or file missing }
*/
router.get('/:photoId', async (req, res, next) => {
try {
const { gymId, photoId } = req.params as GymParams & { photoId: string };
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin)))
throw forbidden('You do not have access to this gym');
const filePath = path.join(photoUploadDir(gymId), photo.storedName);
if (!fs.existsSync(filePath)) throw notFound('Photo file not found');
res.type(photo.mimeType);
await new Promise<void>((resolve, reject) => {
res.sendFile(filePath, (err) => (err ? reject(err) : resolve()));
});
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,63 @@
import { z } from 'zod';
import { availabilitySchema } from '../me.js';
export const createGymSchema = z.object({
name: z.string().min(1).max(200),
location: z.string().max(500).nullable().optional(),
availability: availabilitySchema,
capacity: z.number().int().positive().max(100000).nullable().optional(),
kind: z.enum(['VIRTUAL', 'REAL']).optional(),
isPrivate: z.boolean().optional(),
});
export const updateGymSchema = createGymSchema.partial().omit({ kind: true });
export const rateGymSchema = z.object({
vote: z.enum(['UP', 'DOWN']),
});
/** Multipart fields arrive as strings (multer) — gymAvailability is a JSON string. */
export const gymClaimSchema = z.object({
gymId: z.string().min(1).optional(),
description: z.string().min(1).max(5000),
companyName: z.string().max(200).optional(),
nip: z.string().regex(/^\d{10}$/).optional(),
phone: z.string().max(20).optional(),
email: z.string().email().max(200).optional(),
address: z.string().max(500).optional(),
gymName: z.string().min(1).max(200).optional(),
gymLocation: z.string().max(500).optional(),
gymAvailability: z.string().optional(),
gymCapacity: z.coerce.number().int().positive().max(100000).optional(),
});
export const gymInvitationSchema = z.object({
gymId: z.string().min(1),
userId: z.string().min(1),
});
export const gymInviteeSearchSchema = z.object({
gymId: z.string().min(1),
firstName: z.string().min(1).max(100),
lastName: z.string().min(1).max(100),
});
export const gymExceptionSchema = z.object({
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
availability: z
.object({
start: z.string().regex(/^\d{2}:\d{2}$/),
end: z.string().regex(/^\d{2}:\d{2}$/),
})
.nullable()
.optional(),
});
export const equipmentSchema = z.object({
equipmentId: z.string().min(1),
quantity: z.number().int().min(1).max(10000).optional(),
});
export const equipmentQuantitySchema = z.object({
quantity: z.number().int().min(1).max(10000),
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,178 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Prisma, PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { logger } from '../../lib/logger.js';
import { claimUploadDir, removeClaimFiles, storedFileName } from '../../lib/uploads.js';
import { toPrismaAvailability, type Availability } from '../me.js';
export interface GymClaimInput {
/** Set = verification of that virtual gym; absent = claim for a NEW real gym. */
gymId?: string;
description: string;
companyName?: string;
nip?: string;
phone?: string;
email?: string;
/** Verification claims only: overrides gym.location on approval. */
address?: string;
/** New-real claims only: */
gymName?: string;
gymLocation?: string;
gymAvailability?: Availability | null;
gymCapacity?: number;
}
export interface UploadedClaimFile {
originalName: string;
mimeType: string;
sizeBytes: number;
/** Temp path (multer) — moved into the per-claim directory. */
path: string;
}
type ClaimWithRelations = Prisma.GymClaimGetPayload<{
include: {
gym: { select: { id: true; name: true; kind: true; isPrivate: true } };
documents: {
select: { id: true; originalName: true; mimeType: true; sizeBytes: true; createdAt: true };
};
};
}>;
export function claimToDto(c: ClaimWithRelations) {
return {
id: c.id,
gymId: c.gymId,
type: c.gymId ? ('verification' as const) : ('new' as const),
gym: c.gym
? { id: c.gym.id, name: c.gym.name, kind: c.gym.kind, isPrivate: c.gym.isPrivate }
: null,
gymName: c.gymName,
gymLocation: c.gymLocation,
gymAvailability: c.gymAvailability,
gymCapacity: c.gymCapacity,
description: c.description,
companyName: c.companyName,
nip: c.nip,
phone: c.phone,
email: c.email,
address: c.address,
status: c.status,
rejectReason: c.rejectReason,
createdAt: c.createdAt.toISOString(),
updatedAt: c.updatedAt.toISOString(),
documents: c.documents.map((d) => ({
id: d.id,
originalName: d.originalName,
mimeType: d.mimeType,
sizeBytes: d.sizeBytes,
createdAt: d.createdAt.toISOString(),
})),
};
}
/**
* Create a gym claim (multipart). gymId set → verification of a virtual gym;
* absent → claim for a new real gym (gymName/gymLocation required).
* Files are moved from the temp dir into UPLOAD_DIR/<claimId>/.
*/
export async function createGymClaim(
prisma: PrismaClient,
userId: string,
data: GymClaimInput,
files: UploadedClaimFile[],
) {
if (data.gymId) {
const gym = await prisma.gym.findUnique({ where: { id: data.gymId } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL') throw conflict('Only virtual gyms can be verified');
const pending = await prisma.gymClaim.findFirst({
where: { gymId: data.gymId, userId, status: 'PENDING' },
select: { id: true },
});
if (pending) throw conflict('You already have a pending claim for this gym');
} else {
if (!data.gymName?.trim()) throw badRequest('Gym name is required');
if (!data.gymLocation?.trim()) throw badRequest('Gym location is required');
}
const claim = await prisma.gymClaim.create({
data: {
gymId: data.gymId ?? null,
userId,
gymName: data.gymId ? null : data.gymName?.trim() ?? null,
gymLocation: data.gymId ? null : data.gymLocation?.trim() ?? null,
gymAvailability: data.gymId ? undefined : toPrismaAvailability(data.gymAvailability ?? null),
gymCapacity: data.gymId ? null : data.gymCapacity ?? null,
description: data.description,
companyName: data.companyName ?? null,
nip: data.nip ?? null,
phone: data.phone ?? null,
email: data.email ?? null,
address: data.address ?? null,
},
});
if (files.length > 0) {
const claimDir = claimUploadDir(claim.id);
try {
fs.mkdirSync(claimDir, { recursive: true });
for (const f of files) {
const storedName = storedFileName(f.mimeType);
fs.renameSync(f.path, path.join(claimDir, storedName));
await prisma.gymClaimDocument.create({
data: {
claimId: claim.id,
originalName: f.originalName,
storedName,
mimeType: f.mimeType,
sizeBytes: f.sizeBytes,
},
});
}
} catch (e) {
// storage failure: roll the claim back and clean up moved/temp files
await prisma.gymClaim.delete({ where: { id: claim.id } }).catch(() => undefined);
removeClaimFiles(claim.id);
logger.error({ err: e, claimId: claim.id }, 'Failed to store claim files');
throw new AppError(500, 'UPLOAD_FAILED', 'Failed to store uploaded files');
}
}
const created = await prisma.gymClaim.findUnique({
where: { id: claim.id },
include: {
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
documents: {
select: { id: true, originalName: true, mimeType: true, sizeBytes: true, createdAt: true },
},
},
});
return { claim: claimToDto(created!) };
}
/** The user's own claims (all statuses, newest first). */
export async function listMyGymClaims(prisma: PrismaClient, userId: string) {
const claims = await prisma.gymClaim.findMany({
where: { userId },
include: {
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
documents: {
select: { id: true, originalName: true, mimeType: true, sizeBytes: true, createdAt: true },
},
},
orderBy: { createdAt: 'desc' },
});
return { claims: claims.map(claimToDto) };
}
/** Withdraw the user's own PENDING claim (files removed best-effort). */
export async function withdrawGymClaim(prisma: PrismaClient, userId: string, claimId: string) {
const claim = await prisma.gymClaim.findUnique({ where: { id: claimId } });
if (!claim) throw notFound('Claim not found');
if (claim.userId !== userId) throw forbidden('Only the claim author can withdraw it');
if (claim.status !== 'PENDING') throw conflict('Only pending claims can be withdrawn');
await prisma.gymClaim.delete({ where: { id: claimId } });
removeClaimFiles(claimId);
}

View File

@@ -0,0 +1,266 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { isPrismaNotFound } from '../../lib/prisma.js';
import { removeGymClaimFiles, removeGymPhotoFiles } from '../../lib/uploads.js';
import { toPrismaAvailability, type Availability } from '../me.js';
import { gymCoverInclude, gymEquipmentInclude } from './includes.js';
import { coverUrlOf } from './photos.js';
export type GymKind = 'VIRTUAL' | 'REAL';
export interface CreateGymInput {
name: string;
location?: string | null;
availability?: Availability | null;
capacity?: number | null;
kind?: GymKind;
isPrivate?: boolean;
}
export interface UpdateGymInput {
name?: string;
location?: string | null;
availability?: Availability | null;
capacity?: number | null;
isPrivate?: boolean;
}
export async function listUserGyms(prisma: PrismaClient, userId: string) {
const memberships = await prisma.gymMembership.findMany({
where: { userId },
include: { gym: { include: { ...gymEquipmentInclude, ...gymCoverInclude } } },
orderBy: { gym: { name: 'asc' } },
});
return {
gyms: memberships.map((m) => {
const { photos, ...gym } = m.gym;
return { ...gym, coverPhoto: coverUrlOf(gym.id, photos), roles: m.roles };
}),
};
}
/** All REAL gyms in the system (for selecting an existing gym). */
export async function listAllGyms(prisma: PrismaClient) {
const gyms = await prisma.gym.findMany({
where: { kind: 'REAL' },
include: { ...gymEquipmentInclude, ...gymCoverInclude },
orderBy: { name: 'asc' },
});
return {
gyms: gyms.map((g) => {
const { photos, ...rest } = g;
return { ...rest, coverPhoto: coverUrlOf(g.id, photos) };
}),
};
}
/**
* Public virtual gyms (with rating counts, the caller's vote and claim status)
* plus the caller's own private virtual gyms (no rating fields).
* Public: score (up-down) desc, then name asc; own private last, by name.
*/
export async function listVirtualGyms(prisma: PrismaClient, userId: string) {
const [publicGyms, privateGyms, claims, myRatings] = await Promise.all([
prisma.gym.findMany({
where: { kind: 'VIRTUAL', isPrivate: false },
include: { ...gymEquipmentInclude, ratings: true, _count: { select: { memberships: true } } },
}),
prisma.gym.findMany({
where: {
kind: 'VIRTUAL',
isPrivate: true,
memberships: { some: { userId, roles: { has: 'OWNER' } } },
},
include: { ...gymEquipmentInclude, _count: { select: { memberships: true } } },
}),
prisma.gymClaim.findMany({
where: { userId, status: { in: ['PENDING', 'REJECTED'] } },
select: { gymId: true, status: true, rejectReason: true },
orderBy: { createdAt: 'desc' },
}),
prisma.gymRating.findMany({
where: { userId },
select: { gymId: true, vote: true },
}),
]);
const myVoteByGym = new Map(myRatings.map((r) => [r.gymId, r.vote]));
const claimByGym = new Map<string, { status: string; rejectReason: string | null }>();
for (const c of claims) {
if (c.gymId && !claimByGym.has(c.gymId)) claimByGym.set(c.gymId, c);
}
const publicList = publicGyms.map((g) => {
const up = g.ratings.filter((r) => r.vote === 'UP').length;
const down = g.ratings.filter((r) => r.vote === 'DOWN').length;
const claim = claimByGym.get(g.id);
return {
id: g.id,
name: g.name,
location: g.location,
availability: g.availability,
capacity: g.capacity,
kind: g.kind,
isPrivate: g.isPrivate,
equipment: g.equipment,
memberCount: g._count.memberships,
up,
down,
myVote: myVoteByGym.get(g.id) ?? null,
claimStatus: claim?.status ?? null,
rejectReason: claim?.status === 'REJECTED' ? claim.rejectReason ?? null : null,
};
});
publicList.sort(
(a, b) => b.up - b.down - (a.up - a.down) || a.name.localeCompare(b.name, 'pl'),
);
const privateList = privateGyms
.map((g) => ({ ...g, isPrivate: true, memberCount: g._count.memberships }))
.sort((a, b) => a.name.localeCompare(b.name, 'pl'));
return { gyms: [...publicList, ...privateList] };
}
/**
* Thumb vote on a public virtual gym (how well it mirrors the real one).
* Upsert with toggle: the same vote again removes it. The owner cannot vote.
*/
export async function rateGym(
prisma: PrismaClient,
userId: string,
gymId: string,
vote: 'UP' | 'DOWN',
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL' || gym.isPrivate)
throw conflict('Only public virtual gyms can be rated');
const isOwner = await prisma.gymMembership.findFirst({
where: { gymId, userId, roles: { has: 'OWNER' } },
});
if (isOwner) throw forbidden('The gym owner cannot rate their own gym');
const existing = await prisma.gymRating.findUnique({
where: { gymId_userId: { gymId, userId } },
});
if (existing?.vote === vote) {
await prisma.gymRating.delete({ where: { id: existing.id } });
} else {
await prisma.gymRating.upsert({
where: { gymId_userId: { gymId, userId } },
update: { vote },
create: { gymId, userId, vote },
});
}
const [up, down] = await Promise.all([
prisma.gymRating.count({ where: { gymId, vote: 'UP' } }),
prisma.gymRating.count({ where: { gymId, vote: 'DOWN' } }),
]);
return { vote: existing?.vote === vote ? null : vote, up, down };
}
/** Join an existing gym (creates a MEMBER membership). */
export async function joinGym(prisma: PrismaClient, userId: string, gymId: string) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
const existing = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
if (existing) throw conflict('Already a member of this gym');
const membership = await prisma.gymMembership.create({
data: { userId, gymId, roles: ['MEMBER'] },
});
return { membership: { gymId, name: gym.name, roles: membership.roles } };
}
/**
* Create a gym; the creator becomes its OWNER.
* Non-admins can only create VIRTUAL gyms (location required); passing REAL → 403.
* Admins pick the kind (default VIRTUAL); isPrivate is only allowed for VIRTUAL.
*/
export async function createGym(
prisma: PrismaClient,
userId: string,
data: CreateGymInput,
isAdmin: boolean,
) {
let kind: GymKind = data.kind ?? 'VIRTUAL';
if (!isAdmin) {
if (kind === 'REAL') throw forbidden('Only admins can create real gyms');
kind = 'VIRTUAL';
}
if (kind === 'VIRTUAL' && !data.location?.trim())
throw badRequest('Location is required for virtual gyms');
const isPrivate = data.isPrivate ?? false;
if (kind === 'REAL' && isPrivate) throw badRequest('Real gyms are always public');
const gym = await prisma.gym.create({
data: {
name: data.name,
location: data.location ?? null,
availability: toPrismaAvailability(data.availability ?? null),
capacity: data.capacity ?? null,
kind,
isPrivate,
},
});
await prisma.gymMembership.create({
data: { userId, gymId: gym.id, roles: ['OWNER'] },
});
return { gym: { ...gym, roles: ['OWNER'] } };
}
export async function assertGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { memberships: { where: { userId } }, equipment: true },
});
if (!gym) throw notFound('Gym not found');
const isOwner = gym.memberships.some((m) => m.roles.includes('OWNER'));
if (!isOwner) throw forbidden('Only the gym owner can manage this gym');
return gym;
}
/** Update a gym's data (owner only). isPrivate is only allowed for VIRTUAL gyms. */
export async function updateOwnedGym(
prisma: PrismaClient,
gymId: string,
userId: string,
data: UpdateGymInput,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
if (data.isPrivate === true && gym.kind === 'REAL')
throw badRequest('Real gyms are always public');
try {
const { availability, ...rest } = data;
const updated = await prisma.gym.update({
where: { id: gymId },
data: { ...rest, availability: toPrismaAvailability(availability) },
});
return { gym: updated };
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
throw e;
}
}
/** Delete a gym (owner only). Memberships are removed; user plans are kept. */
export async function deleteOwnedGym(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await assertGymOwner(prisma, gymId, userId);
const claimIds = await listGymClaimIds(prisma, gymId);
try {
await prisma.gym.delete({ where: { id: gymId } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
throw e;
}
await removeGymClaimFiles(claimIds);
removeGymPhotoFiles(gymId);
return { name: gym.name };
}
export async function listGymClaimIds(prisma: PrismaClient, gymId: string): Promise<string[]> {
const claims = await prisma.gymClaim.findMany({
where: { gymId },
select: { id: true },
});
return claims.map((c) => c.id);
}

View File

@@ -0,0 +1,175 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, conflict, notFound } from '../../lib/errors.js';
import { isPrismaUnique } from '../../lib/prisma.js';
import { toPrismaJson, type DayAvailability } from '../me.js';
import { assertGymOwner } from './core.js';
import { gymEquipmentInclude } from './includes.js';
export interface CreateGymExceptionInput {
/** ISO date (YYYY-MM-DD) the exception applies to. */
date: string;
/** null = closed, { start, end } = different hours. */
availability: DayAvailability | null;
}
/** List a gym's upcoming schedule exceptions (owner only). */
export async function listOwnedGymExceptions(
prisma: PrismaClient,
gymId: string,
userId: string,
) {
await assertGymOwner(prisma, gymId, userId);
const exceptions = await prisma.gymException.findMany({
where: { gymId },
orderBy: { date: 'asc' },
});
return { exceptions };
}
/** Add a one-off schedule exception for a specific date (owner only). */
export async function createOwnedGymException(
prisma: PrismaClient,
gymId: string,
userId: string,
data: CreateGymExceptionInput,
) {
await assertGymOwner(prisma, gymId, userId);
const date = new Date(data.date);
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
try {
const exception = await prisma.gymException.create({
data: {
gymId,
date,
availability: toPrismaJson(data.availability),
},
});
return { exception };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
throw e;
}
}
/** Remove a schedule exception (owner only). */
export async function deleteOwnedGymException(
prisma: PrismaClient,
gymId: string,
userId: string,
exceptionId: string,
) {
await assertGymOwner(prisma, gymId, userId);
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
await prisma.gymException.delete({ where: { id: exceptionId } });
}
/** Add a catalog equipment item to a gym with a quantity (owner only). */
export async function addEquipment(
prisma: PrismaClient,
gymId: string,
userId: string,
equipmentId: string,
quantity = 1,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const item = await prisma.equipment.findUnique({ where: { id: equipmentId } });
if (!item) throw notFound('Equipment not found');
if (gym.equipment.some((e) => e.equipmentId === equipmentId))
throw conflict('Equipment already exists in this gym — update its quantity instead');
try {
await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } });
} catch (e) {
if (isPrismaUnique(e)) throw conflict('Equipment already exists in this gym — update its quantity instead');
throw e;
}
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: gymEquipmentInclude,
});
return { gym: updated };
}
/** Change the quantity of a gym's equipment item (owner only). */
export async function updateEquipmentQuantity(
prisma: PrismaClient,
gymId: string,
userId: string,
equipmentId: string,
quantity: number,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
if (!link) throw badRequest('Equipment not found in this gym');
await prisma.gymEquipment.update({ where: { id: link.id }, data: { quantity } });
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: gymEquipmentInclude,
});
return { gym: updated };
}
/** Remove a catalog equipment item from a gym (owner only). */
export async function removeEquipment(
prisma: PrismaClient,
gymId: string,
userId: string,
equipmentId: string,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
if (!link) throw badRequest('Equipment not found in this gym');
await prisma.gymEquipment.delete({ where: { id: link.id } });
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: gymEquipmentInclude,
});
return { gym: updated };
}
/** List a gym's upcoming schedule exceptions. */
export async function listGymExceptions(prisma: PrismaClient, gymId: string) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
const exceptions = await prisma.gymException.findMany({
where: { gymId },
orderBy: { date: 'asc' },
});
return { exceptions };
}
/** Add a one-off schedule exception for a specific date. */
export async function createGymException(
prisma: PrismaClient,
gymId: string,
data: CreateGymExceptionInput,
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
const date = new Date(data.date);
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
try {
const exception = await prisma.gymException.create({
data: {
gymId,
date,
availability: toPrismaJson(data.availability),
},
});
return { exception };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
throw e;
}
}
/** Remove a schedule exception. */
export async function deleteGymException(
prisma: PrismaClient,
gymId: string,
exceptionId: string,
) {
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
await prisma.gymException.delete({ where: { id: exceptionId } });
}

View File

@@ -0,0 +1,20 @@
/** Gym equipment links with the catalog item, ordered by equipment name. */
export const gymEquipmentInclude = {
equipment: {
include: { equipment: true },
orderBy: { equipment: { name: 'asc' as const } },
},
};
/** Gallery photos, cover first (smallest order, tie → oldest). */
export const gymPhotosInclude = {
photos: { orderBy: [{ order: 'asc' as const }, { createdAt: 'asc' as const }] },
};
/** Only the cover photo (for lists). */
export const gymCoverInclude = {
photos: {
orderBy: [{ order: 'asc' as const }, { createdAt: 'asc' as const }],
take: 1,
},
};

View File

@@ -0,0 +1,199 @@
import type { PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { INVITATION_TTL_DAYS } from '../trainer.js';
async function assertGymOwnerOf(prisma: PrismaClient, gymId: string, userId: string): Promise<void> {
const membership = await prisma.gymMembership.findFirst({
where: { gymId, userId, roles: { has: 'OWNER' } },
select: { id: true },
});
if (!membership) throw forbidden('Only the gym owner can do this');
}
/**
* Invite a user to a PRIVATE virtual gym. Owner only. A re-invite after DECLINED
* updates the existing row (new invitedAt/expiresAt/invitedBy).
*/
export async function sendGymInvitation(
prisma: PrismaClient,
ownerId: string,
gymId: string,
userId: string,
) {
if (ownerId === userId) throw badRequest('Cannot invite yourself');
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL' || !gym.isPrivate)
throw conflict('Only private virtual gyms can receive invitations');
await assertGymOwnerOf(prisma, gymId, ownerId);
const target = await prisma.user.findUnique({ where: { id: userId } });
if (!target) throw notFound('User not found');
const member = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
if (member) throw conflict('User is already a member of this gym');
const existing = await prisma.gymInvitation.findFirst({ where: { gymId, userId } });
if (existing?.status === 'PENDING') throw conflict('Invitation already exists');
const now = new Date();
const expiresAt = new Date(now.getTime() + INVITATION_TTL_DAYS * 24 * 60 * 60 * 1000);
const invitation = existing
? await prisma.gymInvitation.update({
where: { id: existing.id },
data: { status: 'PENDING', invitedAt: now, expiresAt, invitedById: ownerId },
})
: await prisma.gymInvitation.create({
data: { gymId, userId, invitedById: ownerId, expiresAt },
});
return { invitation };
}
/** Pending, not-expired gym invitations of the user — sent and received. */
export async function listGymInvitations(prisma: PrismaClient, userId: string) {
const now = new Date();
const invitations = await prisma.gymInvitation.findMany({
where: {
status: 'PENDING',
expiresAt: { gt: now },
OR: [{ userId }, { invitedById: userId }],
},
include: {
gym: { select: { id: true, name: true, location: true, kind: true, isPrivate: true } },
user: { select: { id: true, firstName: true, lastName: true, email: true } },
invitedBy: { select: { id: true, firstName: true, lastName: true, email: true } },
},
orderBy: { invitedAt: 'desc' },
});
return {
invitations: invitations.map((i) => {
const direction = i.invitedById === userId ? ('sent' as const) : ('received' as const);
return {
id: i.id,
direction,
gym: {
id: i.gym.id,
name: i.gym.name,
location: i.gym.location,
kind: i.gym.kind,
isPrivate: i.gym.isPrivate,
},
user:
direction === 'sent'
? {
id: i.user.id,
firstName: i.user.firstName,
lastName: i.user.lastName,
email: i.user.email,
}
: null,
invitedBy:
direction === 'received'
? {
id: i.invitedBy.id,
firstName: i.invitedBy.firstName,
lastName: i.invitedBy.lastName,
email: i.invitedBy.email,
}
: null,
invitedAt: i.invitedAt.toISOString(),
expiresAt: i.expiresAt.toISOString(),
};
}),
};
}
/**
* Search users to invite to a private virtual gym (owner only).
* Excludes the owner, current members and users with a pending invitation.
*/
export async function searchGymInvitees(
prisma: PrismaClient,
ownerId: string,
gymId: string,
firstName: string,
lastName: string,
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
await assertGymOwnerOf(prisma, gymId, ownerId);
const [members, pending] = await Promise.all([
prisma.gymMembership.findMany({ where: { gymId }, select: { userId: true } }),
prisma.gymInvitation.findMany({ where: { gymId, status: 'PENDING' }, select: { userId: true } }),
]);
const excludeIds = new Set([
ownerId,
...members.map((m) => m.userId),
...pending.map((p) => p.userId),
]);
const users = await prisma.user.findMany({
where: {
firstName: { contains: firstName, mode: 'insensitive' },
lastName: { contains: lastName, mode: 'insensitive' },
NOT: { id: { in: [...excludeIds] } },
},
select: { id: true, firstName: true, lastName: true, email: true, phone: true },
take: 20,
orderBy: { createdAt: 'asc' },
});
return { users };
}
async function loadPendingGymInvitation(prisma: PrismaClient, invitationId: string) {
const invitation = await prisma.gymInvitation.findUnique({ where: { id: invitationId } });
if (!invitation) throw notFound('Invitation not found');
if (invitation.status !== 'PENDING') throw conflict('Invitation is not pending');
if (invitation.expiresAt <= new Date()) throw new AppError(410, 'GONE', 'Invitation expired');
return invitation;
}
/** Accept a gym invitation (invited user only) → MEMBER membership (idempotent). */
export async function acceptGymInvitation(
prisma: PrismaClient,
userId: string,
invitationId: string,
) {
const invitation = await loadPendingGymInvitation(prisma, invitationId);
if (invitation.userId !== userId) throw forbidden('You are not the invited user');
const existing = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId: invitation.gymId } },
select: { id: true },
});
if (!existing) {
await prisma.gymMembership.create({
data: { userId, gymId: invitation.gymId, roles: ['MEMBER'] },
});
}
const updated = await prisma.gymInvitation.update({
where: { id: invitationId },
data: { status: 'ACCEPTED' },
});
return { invitation: updated };
}
/** Decline a gym invitation (invited user only). */
export async function declineGymInvitation(
prisma: PrismaClient,
userId: string,
invitationId: string,
) {
const invitation = await loadPendingGymInvitation(prisma, invitationId);
if (invitation.userId !== userId) throw forbidden('You are not the invited user');
const updated = await prisma.gymInvitation.update({
where: { id: invitationId },
data: { status: 'DECLINED' },
});
return { invitation: updated };
}
/** Withdraw a pending gym invitation (sender only) — removes the row. */
export async function withdrawGymInvitation(
prisma: PrismaClient,
userId: string,
invitationId: string,
) {
const invitation = await prisma.gymInvitation.findUnique({ where: { id: invitationId } });
if (!invitation) throw notFound('Invitation not found');
if (invitation.status !== 'PENDING') throw conflict('Invitation is not pending');
if (invitation.invitedById !== userId) throw forbidden('Only the sender can withdraw the invitation');
await prisma.gymInvitation.delete({ where: { id: invitationId } });
}

View File

@@ -0,0 +1,200 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Prisma, PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { logger } from '../../lib/logger.js';
import {
MAX_GYM_PHOTOS,
photoUploadDir,
removeGymPhotoFile,
storedFileName,
} from '../../lib/uploads.js';
import { gymEquipmentInclude, gymPhotosInclude } from './includes.js';
export interface GymPhotoDto {
id: string;
url: string;
order: number;
createdAt: string;
}
/** Public photo URL (served by GET /gyms/:gymId/photos/:photoId). */
export function gymPhotoUrl(gymId: string, photoId: string): string {
return `/gyms/${gymId}/photos/${photoId}`;
}
export function coverUrlOf(gymId: string, photos: { id: string }[]): string | null {
return photos[0] ? gymPhotoUrl(gymId, photos[0].id) : null;
}
type GymWithPhotos = Prisma.GymGetPayload<{
include: {
equipment: { include: { equipment: true } };
photos: true;
};
}>;
function gymToDto(g: GymWithPhotos) {
const photos: GymPhotoDto[] = g.photos.map((p) => ({
id: p.id,
url: gymPhotoUrl(g.id, p.id),
order: p.order,
createdAt: p.createdAt.toISOString(),
}));
return {
id: g.id,
name: g.name,
location: g.location,
availability: g.availability,
capacity: g.capacity,
kind: g.kind,
isPrivate: g.isPrivate,
equipment: g.equipment,
photos,
coverPhoto: coverUrlOf(g.id, g.photos),
};
}
async function loadGymDto(prisma: PrismaClient, gymId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
});
if (!gym) throw notFound('Gym not found');
return gymToDto(gym);
}
/** True when the user may manage the gym: an admin or a member with the OWNER role. */
export async function canManageGym(
prisma: PrismaClient,
gymId: string,
userId: string,
isAdmin: boolean,
): Promise<boolean> {
if (isAdmin) return true;
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { roles: true },
});
return !!membership?.roles.includes('OWNER');
}
/**
* Public gym detail. REAL gyms are visible to any logged-in user; VIRTUAL gyms
* only to their managers (owner or admin). Includes the photo gallery.
*/
export async function getGymPublic(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
});
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('You do not have access to this gym');
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
return { gym: gymToDto(gym), roles: membership?.roles ?? [], isAdmin };
}
export interface UploadedPhotoFile {
mimeType: string;
sizeBytes: number;
/** Temp path (multer) — moved into the per-gym directory. */
path: string;
}
/** Add photos to a REAL gym's gallery (owner or admin). */
export async function addGymPhotos(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
files: UploadedPhotoFile[],
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { photos: { select: { order: true } } },
});
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL') throw conflict('Only real gyms have a gallery');
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('Only the gym owner or an admin can manage photos');
if (gym.photos.length + files.length > MAX_GYM_PHOTOS)
throw badRequest(`A gym can have at most ${MAX_GYM_PHOTOS} photos`);
const maxOrder = gym.photos.reduce((m, p) => Math.max(m, p.order), -1);
const dir = photoUploadDir(gymId);
const moved: string[] = [];
try {
fs.mkdirSync(dir, { recursive: true });
for (let i = 0; i < files.length; i++) {
const f = files[i];
const storedName = storedFileName(f.mimeType);
fs.renameSync(f.path, path.join(dir, storedName));
moved.push(path.join(dir, storedName));
await prisma.gymPhoto.create({
data: {
gymId,
storedName,
mimeType: f.mimeType,
sizeBytes: f.sizeBytes,
order: maxOrder + 1 + i,
},
});
}
} catch (e) {
for (const p of moved) fs.rmSync(p, { force: true });
logger.error({ err: e, gymId }, 'Failed to store gym photos');
throw new AppError(500, 'UPLOAD_FAILED', 'Failed to store uploaded photos');
}
return { gym: await loadGymDto(prisma, gymId) };
}
/** Remove a photo from a gym's gallery (owner or admin). */
export async function deleteGymPhoto(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
photoId: string,
) {
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('Only the gym owner or an admin can manage photos');
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
await prisma.gymPhoto.delete({ where: { id: photoId } });
removeGymPhotoFile(gymId, photo.storedName);
return { gym: await loadGymDto(prisma, gymId) };
}
/** Make a photo the gallery cover (order 0; the rest shift by +1). Owner or admin. */
export async function setGymPhotoCover(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
photoId: string,
) {
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('Only the gym owner or an admin can manage photos');
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
if (photo.order !== 0) {
await prisma.$transaction(async (tx) => {
await tx.gymPhoto.update({ where: { id: photoId }, data: { order: 0 } });
const others = await tx.gymPhoto.findMany({
where: { gymId, id: { not: photoId } },
select: { id: true, order: true },
});
for (const p of others) {
await tx.gymPhoto.update({ where: { id: p.id }, data: { order: p.order + 1 } });
}
});
}
return { gym: await loadGymDto(prisma, gymId) };
}

View File

@@ -363,7 +363,7 @@ export async function assertActiveTrainee(prisma: PrismaClient, trainerId: strin
* Restricted trainee detail: training metrics only (no body parameters, no profile).
*/
export async function getTraineeDetail(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
const coaching = await assertActiveTrainee(prisma, trainerId, userId);
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
@@ -381,6 +381,7 @@ export async function getTraineeDetail(prisma: PrismaClient, trainerId: string,
computeTraineeMetrics(prisma, userId),
]);
return {
coachingId: coaching.id,
user: {
id: user.id,
firstName: user.firstName,

View File

@@ -305,6 +305,11 @@ describe('trainer — invitations and trainees', () => {
expect(res.body).toHaveProperty('missing');
expect(res.body).toHaveProperty('lastSessionAt');
expect(res.body).toHaveProperty('flags');
// coaching relation id — allows messaging the trainee directly from the detail page
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId: trainer.id, userId: trainee.id } },
});
expect(res.body.coachingId).toBe(coaching!.id);
// restricted: no profile/body data leaks
expect(res.body).not.toHaveProperty('age');
expect(res.body).not.toHaveProperty('heightCm');

View File

@@ -1 +0,0 @@
{"root":["./src/app.ts","./src/config.ts","./src/deps.ts","./src/index.ts","./src/seed.ts","./src/swagger.ts","./src/data/exercises.ts","./src/lib/equipmentspec.ts","./src/lib/errors.ts","./src/lib/jwt.ts","./src/lib/logger.ts","./src/lib/prisma.ts","./src/lib/publicuser.ts","./src/lib/uploads.ts","./src/middleware/auth.ts","./src/middleware/errorhandler.ts","./src/middleware/ratelimit.ts","./src/middleware/validate.ts","./src/routes/admin.ts","./src/routes/auth.ts","./src/routes/calendar.ts","./src/routes/dashboard.ts","./src/routes/equipment.ts","./src/routes/equipmentpublic.ts","./src/routes/exercisepool.ts","./src/routes/exercises.ts","./src/routes/focusareas.ts","./src/routes/gyms.ts","./src/routes/me.ts","./src/routes/messages.ts","./src/routes/plans-schemas.ts","./src/routes/plans.ts","./src/routes/sessions.ts","./src/routes/trainer.ts","./src/services/admin.ts","./src/services/audit.ts","./src/services/auth.ts","./src/services/calendar.ts","./src/services/comments.ts","./src/services/dashboard.ts","./src/services/equipment.ts","./src/services/exercisepool.ts","./src/services/exerciseprogress.ts","./src/services/exercises.ts","./src/services/focusareas.ts","./src/services/focuschain.ts","./src/services/gyms.ts","./src/services/killstreak.ts","./src/services/me.ts","./src/services/messages.ts","./src/services/plans.ts","./src/services/scheduler.ts","./src/services/sessions.ts","./src/services/trainer.ts"],"version":"5.9.3"}

View File

@@ -1,12 +1,13 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
testDir: './test/e2e',
outputDir: './test/results',
timeout: 30_000,
expect: { timeout: 5_000 },
fullyParallel: true,
retries: process.env.CI ? 1 : 0,
reporter: [['list'], ['html', { open: 'never' }]],
reporter: [['list'], ['html', { outputFolder: 'test/report', open: 'never' }]],
use: {
baseURL: 'http://localhost:5173',
trace: 'on-first-retry',

View File

@@ -5,25 +5,25 @@ import Layout from './components/Layout';
import Login from './pages/Login';
import Register from './pages/Register';
import Dashboard from './pages/Dashboard';
import Plans from './pages/Plans';
import PlanEditor from './pages/PlanEditor';
import PlanDetail from './pages/PlanDetail';
import Plans from './pages/plans/Plans';
import PlanEditor from './pages/plans/PlanEditor';
import PlanDetail from './pages/plans/PlanDetail';
import Calendar from './pages/Calendar';
import DayExecution from './pages/DayExecution';
import Profile from './pages/Profile';
import ProfileInfo from './pages/ProfileInfo';
import ProfileBodyParameters from './pages/ProfileBodyParameters';
import ProfileHistory from './pages/ProfileHistory';
import ProfileProgress from './pages/ProfileProgress';
import ProfileGyms from './pages/ProfileGyms';
import ProfileClaims from './pages/ProfileClaims';
import Gyms from './pages/Gyms';
import GymDetail from './pages/GymDetail';
import Trainees from './pages/Trainees';
import TraineeDetail from './pages/TraineeDetail';
import Profile from './pages/profile/Profile';
import ProfileInfo from './pages/profile/ProfileInfo';
import ProfileBodyParameters from './pages/profile/ProfileBodyParameters';
import ProfileHistory from './pages/profile/ProfileHistory';
import ProfileProgress from './pages/profile/ProfileProgress';
import ProfileGyms from './pages/profile/ProfileGyms';
import ProfileClaims from './pages/profile/ProfileClaims';
import Gyms from './pages/gyms/Gyms';
import GymDetail from './pages/gyms/GymDetail';
import Trainees from './pages/trainees/Trainees';
import TraineeDetail from './pages/trainees/TraineeDetail';
import Invitations from './pages/Invitations';
import Messages from './pages/Messages';
import MessageThread from './pages/MessageThread';
import Messages from './pages/messages/Messages';
import MessageThread from './pages/messages/MessageThread';
export default function App() {
const { user, ready, init } = useAuth();

View File

@@ -488,6 +488,8 @@ export interface Trainee {
}
export interface TraineeDetail {
/** Id relacji coaching — pozwala otworzyć wątek komunikatora z podopiecznym. */
coachingId: string;
user: { id: string; firstName: string | null; lastName: string | null; nickname: string | null };
socialMedia: SocialMediaEntry[] | null;
gyms: { id: string; name: string }[];

View File

@@ -10,7 +10,8 @@ import {
YAxis,
} from 'recharts';
import type { ExerciseProgress } from '../api/types';
import { fmtDate, MUSCLE_NAMES } from './helpers';
import { fmtDate } from '../lib/format';
import { MUSCLE_NAMES } from '../lib/labels';
import { Card, H3 } from './ui';
const TOOLTIP_STYLE = {

View File

@@ -1,7 +1,8 @@
import { useState } from 'react';
import { ChevronDown, ChevronUp, MessageSquarePlus, Trash2 } from 'lucide-react';
import type { HistorySession } from '../api/types';
import { fmtDate, fmtDateTime, MUSCLE_NAMES, SESSION_STATUS } from './helpers';
import { fmtDate, fmtDateTime } from '../lib/format';
import { MUSCLE_NAMES, SESSION_STATUS } from '../lib/labels';
import { Badge, Button, Textarea } from './ui';
interface HistoryTableProps {

View File

@@ -1,6 +1,6 @@
import { Dumbbell } from 'lucide-react';
import type { MessageAttachment } from '../api/types';
import { fmtDate } from './helpers';
import { fmtDate } from '../lib/format';
/**
* Karta załącznika wyniku w wiadomości: data sesji, plan, ćwiczenie (serie)

View File

@@ -1,6 +1,7 @@
import { useState } from 'react';
import { CalendarDays, ChevronLeft, ChevronRight } from 'lucide-react';
import { DAY_STATUS, monthStr } from '../helpers';
import { monthStr } from '../../lib/format';
import { DAY_STATUS } from '../../lib/labels';
import { MONTH_SHORT, formatMonth } from '../../store/body-params';
import type { CalendarDay } from '../../api/types';
import { Badge, Button, EmptyState } from '../ui';

View File

@@ -1,11 +1,11 @@
import { useEffect, useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { createGymClaim, useMe, type GymClaimInput } from '../api/queries';
import type { Availability, GymClaim } from '../api/types';
import { Button, ErrorText, Field, Input, Modal, Textarea } from './ui';
import { useToast } from './toast';
import { AvailabilityEditor } from './AvailabilityEditor';
import { emptyAvailability } from '../lib/availability';
import { createGymClaim, useMe, type GymClaimInput } from '../../api/queries';
import type { Availability, GymClaim } from '../../api/types';
import { Button, ErrorText, Field, Input, Modal, Textarea } from '../ui';
import { useToast } from '../toast';
import { AvailabilityEditor } from '../AvailabilityEditor';
import { emptyAvailability } from '../../lib/availability';
const MAX_FILES = 5;
const MAX_FILE_BYTES = 5 * 1024 * 1024;

View File

@@ -1,11 +1,11 @@
import { useEffect, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { createGym, useMe } from '../api/queries';
import type { Availability, GymKind } from '../api/types';
import { Button, Field, Input, Modal, Select } from './ui';
import { useToast } from './toast';
import { AvailabilityEditor } from './AvailabilityEditor';
import { emptyAvailability } from '../lib/availability';
import { createGym, useMe } from '../../api/queries';
import type { Availability, GymKind } from '../../api/types';
import { Button, Field, Input, Modal, Select } from '../ui';
import { useToast } from '../toast';
import { AvailabilityEditor } from '../AvailabilityEditor';
import { emptyAvailability } from '../../lib/availability';
/**
* Wspólny modal tworzenia siłowni (strona „Siłownie” i profil).

View File

@@ -1,10 +1,10 @@
import { useRef, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { ImagePlus, Star, Trash2 } from 'lucide-react';
import { addGymPhotos, deleteGymPhoto, gymPhotoSrc, setGymPhotoCover } from '../api/queries';
import type { Gym, GymPhoto } from '../api/types';
import { Badge, Button, ErrorText } from './ui';
import { useToast } from './toast';
import { addGymPhotos, deleteGymPhoto, gymPhotoSrc, setGymPhotoCover } from '../../api/queries';
import type { Gym, GymPhoto } from '../../api/types';
import { Badge, Button, ErrorText } from '../ui';
import { useToast } from '../toast';
const MAX_FILES = 10;
const MAX_FILE_BYTES = 5 * 1024 * 1024;

View File

@@ -10,11 +10,11 @@ import {
useEquipment,
useGyms,
type UserGym,
} from '../api/queries';
import { GYM_ROLE } from './helpers';
import { Badge, Button, Card, H3, Loading, Select } from './ui';
import { useToast } from './toast';
import { formatEquipmentSpec, formatGymEquipment } from '../lib/equipment';
} from '../../api/queries';
import { GYM_ROLE } from '../../lib/labels';
import { Badge, Button, Card, H3, Loading, Select } from '../ui';
import { useToast } from '../toast';
import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment';
import GymCreateModal from './GymCreateModal';
export default function GymsSection({

View File

@@ -1,8 +1,8 @@
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { sendGymInvitation, useGymInviteeSearch } from '../api/queries';
import { Button, ErrorText, Field, Input, Loading, Modal } from './ui';
import { useToast } from './toast';
import { sendGymInvitation, useGymInviteeSearch } from '../../api/queries';
import { Button, ErrorText, Field, Input, Loading, Modal } from '../ui';
import { useToast } from '../toast';
/** Wyszukajka imię + nazwisko → „Zaproś” per user (właściciel prywatnej VIRTUAL). */
export default function InviteGymModal({

View File

@@ -1,6 +1,6 @@
import { Link } from 'react-router-dom';
import { CalendarDays, ChevronRight } from 'lucide-react';
import { fmtDate } from '../helpers';
import { fmtDate } from '../../lib/format';
import { MetaItem } from '../ui';
import type { Plan } from '../../api/types';

View File

@@ -1,7 +1,8 @@
import type { ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { Play } from 'lucide-react';
import { DAY_NAMES, DAY_STATUS, fmtDate } from '../helpers';
import { fmtDate } from '../../lib/format';
import { DAY_NAMES, DAY_STATUS } from '../../lib/labels';
import { Badge, Button, Card, H2 } from '../ui';
import type { PlanDay, PlanWeek } from '../../api/types';

View File

@@ -5,15 +5,9 @@ import type {
SelectHTMLAttributes,
TextareaHTMLAttributes,
} from 'react';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { ArrowLeft, ChevronLeft, ChevronRight, Moon, Sun, X } from 'lucide-react';
import { cva } from 'class-variance-authority';
import { useTheme } from '../store/theme';
import { formatMonth } from '../store/body-params';
import { fmtDate } from './helpers';
import { cn } from '../lib/utils';
import { Button as UIButton, buttonVariants } from './ui/button';
import { Button as UIButton } from './ui/button';
import { Card as UICard } from './ui/card';
import { Badge as UIBadge } from './ui/badge';
import { Input as UIInput } from './ui/input';
@@ -23,7 +17,12 @@ 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';
export * from './ui/typography';
export * from './ui/content';
export * from './ui/dialogs';
export * from './ui/week-picker';
export * from './ui/theme-toggle';
/* Button */
export type ButtonVariant = 'primary' | 'secondary' | 'danger' | 'ghost';
@@ -154,193 +153,7 @@ export function MiniInput({
);
}
/* Headings */
export function H1({ className = '', children }: { className?: string; children: ReactNode }) {
return <h1 className={`text-[1.75rem] 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.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>
);
}
/* Stat tile: bez boxa — mini etykieta (uppercase) + duża wartość */
export function StatTile({
label,
value,
valueClassName = 'truncate',
className = '',
}: {
label: ReactNode;
value: ReactNode;
/** Styl wartości (domyślnie `truncate`; np. `break-words` dla długich tekstów). */
valueClassName?: string;
className?: string;
}) {
return (
<div data-slot="stat-tile" className={`min-w-0 ${className}`.trim()}>
<div className="text-[11px] uppercase tracking-[0.1em] text-dim font-bold">{label}</div>
<div className={`font-display text-[1.5rem] leading-tight font-bold tabular-nums tracking-[-0.02em] ${valueClassName}`.trim()}>{value}</div>
</div>
);
}
/* 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>
);
}
/* 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>
);
}
/* 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>;
}
@@ -349,509 +162,12 @@ 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 data-slot="empty-state" 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.95rem] 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 data-slot="tabs" 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.
`wide` = szerszy panel (sm:max-w-2xl) dla rozbudowanych formularzy. */
export function Modal({
open,
onClose,
title,
children,
wide,
}: {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
wide?: boolean;
}) {
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className={wide ? 'sm:max-w-2xl' : undefined}>
<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>
);
}
/* Number pad dialog — mobile-friendly numeric entry (keypad + Wpisz/Anuluj). */
export function NumberPadDialog({
open,
title,
value,
hint,
onConfirm,
onClose,
}: {
open: boolean;
title: string;
value: string;
hint?: string;
onConfirm: (value: string) => void;
onClose: () => void;
}) {
const [draft, setDraft] = useState(value);
useEffect(() => {
if (open) setDraft(value);
}, [open, value]);
const press = (d: string) => {
setDraft((cur) => {
if (d === 'C') return '';
if (d === '⌫') return cur.slice(0, -1);
if (cur.length >= 3) return cur;
return cur + d;
});
};
const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'C', '0', '⌫'];
return (
<Modal open={open} onClose={onClose} title={title}>
<div className="mb-4">
<input
value={draft}
onChange={(e) => setDraft(e.target.value.replace(/\D/g, '').slice(0, 3))}
inputMode="numeric"
placeholder="—"
aria-label={title}
className="w-full text-center text-5xl font-bold font-display tabular-nums text-ink bg-input border border-line rounded-[10px] py-2 shadow-(--inset-shadow) focus:outline-none focus:border-accent-text focus:ring-[3px] focus:ring-accent/18"
/>
{hint && <div className="text-center text-dim text-[0.85rem] mt-1.5">{hint}</div>}
</div>
<div className="grid grid-cols-3 gap-2 mb-4">
{KEYS.map((d) => (
<button
key={d}
type="button"
onClick={() => press(d)}
aria-label={d === 'C' ? 'Wyczyść' : d === '⌫' ? 'Usuń cyfrę' : d}
className="h-14 rounded-[10px] bg-input border border-line text-xl font-semibold text-ink shadow-(--inset-shadow) cursor-pointer hover:border-accent/55 hover:text-accent-text active:bg-line/40 transition-all duration-150"
>
{d}
</button>
))}
</div>
<div className="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3">
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
Anuluj
</Button>
<Button onClick={() => onConfirm(draft)} className="w-full sm:w-auto">
Wpisz
</Button>
</div>
</Modal>
);
}
/* Difficulty slider dialog — 1 (łatwo) … 5 (trudno). */
export function DifficultyDialog({
open,
value,
onConfirm,
onClose,
}: {
open: boolean;
value: string;
onConfirm: (value: string) => void;
onClose: () => void;
}) {
const normalize = (v: string) => {
const parsed = v === '' ? NaN : parseInt(v);
return String(isNaN(parsed) ? 3 : Math.max(1, Math.min(5, parsed)));
};
const [draft, setDraft] = useState(() => normalize(value));
useEffect(() => {
if (open) setDraft(normalize(value));
}, [open, value]);
return (
<Modal open={open} onClose={onClose} title="Trudność">
<div className="text-center mb-5">
<div className="text-5xl font-bold tabular-nums text-ink">{draft}</div>
</div>
<div className="mb-5">
<input
type="range"
min={1}
max={5}
step={1}
value={parseInt(draft)}
onChange={(e) => setDraft(e.target.value)}
aria-label="Trudność (suwak)"
className="w-full accent-accent cursor-pointer"
/>
<div className="flex justify-between text-dim text-[0.85rem] mt-2">
<span>łatwo</span>
<span>trudno</span>
</div>
</div>
<div className="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3">
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
Anuluj
</Button>
<Button onClick={() => onConfirm(draft)} className="w-full sm:w-auto">
Wpisz
</Button>
</div>
</Modal>
);
}
/* Metadata for the set fields edited in SetEditDialog. */
const SET_FIELD_META: { key: 'reps' | 'rir' | 'difficulty'; label: string; hint: string }[] = [
{ key: 'reps', label: 'Powtórzenia', hint: 'liczba powtórzeń' },
{ key: 'rir', label: 'RIR', hint: '0–10 (reps in reserve)' },
{ key: 'difficulty', label: 'Trudność', hint: '1–5' },
];
export type SetFieldValues = { reps: string; rir: string; difficulty: string };
export type PlannedValues = { reps: number | null; rir: number | null; difficulty: number | null };
/* Bulk set editor — fill in all set fields at once (each via the number pad). */
export function SetEditDialog({
open,
setIndex,
values,
planned,
title,
onSave,
onClose,
}: {
open: boolean;
setIndex: number;
values: SetFieldValues;
planned: PlannedValues;
/** Tytuł okna — domyślnie „Uzupełnij serię N” (przekazuj „Edytuj serię N” dla uzupełnionych serii). */
title?: string;
onSave: (values: SetFieldValues) => void;
onClose: () => void;
}) {
const [drafts, setDrafts] = useState<SetFieldValues>(values);
const [editingField, setEditingField] = useState<'reps' | 'rir' | 'difficulty' | null>(null);
useEffect(() => {
if (open) setDrafts(values);
}, [open, values]);
const editing = editingField ? SET_FIELD_META.find((f) => f.key === editingField) : undefined;
const hasNorm = planned.reps != null;
const fillNorm = () => {
setDrafts({
reps: planned.reps?.toString() ?? '',
rir: planned.rir?.toString() ?? '',
difficulty: planned.difficulty?.toString() ?? '',
});
};
return (
<>
<Modal open={open} onClose={onClose} title={title ?? `Uzupełnij serię ${setIndex + 1}`}>
{hasNorm && (
<Button variant="secondary" size="sm" onClick={fillNorm} className="mb-3 w-full">
Norma spełniona
</Button>
)}
<div className="space-y-2 mb-4">
{SET_FIELD_META.map((f) => (
<button
key={f.key}
type="button"
onClick={() => setEditingField(f.key)}
className="w-full flex items-center justify-between rounded-[10px] border border-line bg-input px-3.5 py-3 shadow-(--inset-shadow) cursor-pointer hover:border-accent/55 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60"
>
<span className="text-[0.9rem] font-semibold text-ink">{f.label}</span>
<span className={`text-[1.1rem] font-bold ${drafts[f.key] ? 'text-ink' : 'text-dim'}`}>
{drafts[f.key] || '—'}
</span>
</button>
))}
</div>
<div className="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3">
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
Anuluj
</Button>
<Button onClick={() => onSave(drafts)} className="w-full sm:w-auto">
Zapisz
</Button>
</div>
</Modal>
{editing &&
(editing.key === 'difficulty' ? (
<DifficultyDialog
open
value={drafts[editing.key]}
onConfirm={(v) => {
setDrafts((d) => ({ ...d, [editing.key]: v }));
setEditingField(null);
}}
onClose={() => setEditingField(null)}
/>
) : (
<NumberPadDialog
open
title={editing.label}
value={drafts[editing.key]}
hint={editing.hint}
onConfirm={(v) => {
setDrafts((d) => ({ ...d, [editing.key]: v }));
setEditingField(null);
}}
onClose={() => setEditingField(null)}
/>
))}
</>
);
}
/* 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>
);
}
/* Wybór tygodnia startu: siatka miesiąca, w której kliknięcie dowolnego dnia zaznacza
CAŁY tydzień (Pn–Nd) — data startu to poniedziałek zaznaczonego tygodnia.
Minione tygodnie są zablokowane (start nie może być w przeszłości). */
const WEEK_DOWS = ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'Nd'];
function localDayKey(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
function parseIsoLocal(iso: string): Date {
const [y, m, d] = iso.split('-').map(Number);
return new Date(y, m - 1, d);
}
function mondayOf(d: Date): Date {
const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
return x;
}
function addDaysLocal(d: Date, n: number): Date {
const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() + n);
return x;
}
/** Poniedziałek bieżącego tygodnia (czas lokalny) — najwcześniej dozwolony tydzień startu. */
export function currentMonday(): Date {
const now = new Date();
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate());
d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
return d;
}
/** Czy podany tydzień (poniedziałek YYYY-MM-DD) jest miniony. */
export function isPastWeek(monday: string): boolean {
if (!monday) return false;
const [y, m, d] = monday.split('-').map(Number);
return new Date(y, m - 1, d) < currentMonday();
}
export function WeekPicker({ value, onChange }: { value: string; onChange: (monday: string) => void }) {
const now = new Date();
const [view, setView] = useState<[number, number]>(() => {
if (value) {
const [y, m] = value.split('-').map(Number);
return [y, m];
}
return [now.getFullYear(), now.getMonth() + 1];
});
const [y, m] = view;
const shift = (delta: number) => {
const d = new Date(y, m - 1 + delta, 1);
setView([d.getFullYear(), d.getMonth() + 1]);
};
// Monday-first grid
const firstDay = new Date(y, m - 1, 1);
const startOffset = (firstDay.getDay() + 6) % 7;
const gridStart = new Date(y, m - 1, 1 - startOffset);
const cells: Date[] = [];
for (let i = 0; i < 42; i++) {
const d = new Date(gridStart);
d.setDate(gridStart.getDate() + i);
cells.push(d);
}
const selMondayKey = value ? localDayKey(mondayOf(parseIsoLocal(value))) : null;
return (
<div className="w-full max-w-xs">
<div className="flex items-center justify-between gap-2 mb-2">
<Button size="sm" variant="ghost" onClick={() => shift(-1)} aria-label="Poprzedni miesiąc">
<ChevronLeft className="w-4 h-4" />
</Button>
<span className="text-[0.9rem] font-semibold">{formatMonth(`${y}-${String(m).padStart(2, '0')}`)}</span>
<Button size="sm" variant="ghost" onClick={() => shift(1)} aria-label="Następny miesiąc">
<ChevronRight className="w-4 h-4" />
</Button>
</div>
<div className="grid grid-cols-7 gap-1" role="group" aria-label="Wybór tygodnia startu">
{WEEK_DOWS.map((d) => (
<div key={d} className="text-center text-dim text-[0.75rem] py-1">
{d}
</div>
))}
{cells.map((d, i) => {
const inMonth = d.getMonth() === m - 1;
const weekMonday = mondayOf(d);
const isPast = isPastWeek(localDayKey(weekMonday));
const isSel = selMondayKey != null && localDayKey(weekMonday) === selMondayKey;
return (
<button
key={i}
type="button"
disabled={isPast}
onClick={() => onChange(localDayKey(weekMonday))}
aria-pressed={isSel}
className={`h-8 rounded-md text-[0.8rem] transition-colors ${
isPast
? 'text-dim/40 cursor-not-allowed'
: isSel
? 'bg-accent/15 text-accent-text font-bold cursor-pointer'
: inMonth
? 'text-ink hover:bg-line/30 cursor-pointer'
: 'text-dim/60 hover:bg-line/30 cursor-pointer'
}`}
>
{d.getDate()}
</button>
);
})}
</div>
{value && (
<p className="text-dim text-[0.8rem] mt-2">
Start: tydzień {fmtDate(value)} – {fmtDate(localDayKey(addDaysLocal(parseIsoLocal(value), 6)))}
</p>
)}
</div>
);
}

View File

@@ -0,0 +1,306 @@
import type { ReactNode } from 'react';
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { ArrowLeft, ChevronLeft, ChevronRight, X } from 'lucide-react';
import { buttonVariants } from './button';
import { H1, H2, H3, Muted } from './typography';
import { cn } from '../../lib/utils';
/* Page header: opcjonalny element przed tytułem (np. awatar), tytuł + badge,
akcje zawsze w tej samej linii po prawej (nie stackują się na mobile). */
export function PageHeader({
title,
leading,
badge,
actions,
}: {
title: string;
/** Element przed tytułem (np. awatar). */
leading?: ReactNode;
badge?: ReactNode;
actions?: ReactNode;
}) {
return (
<div className="flex items-center justify-between gap-3 mb-5">
<div className="flex min-w-0 items-center gap-3 flex-wrap">
{leading}
<H1 className="mb-0">{title}</H1>
{badge}
</div>
{actions && <div className="shrink-0">{actions}</div>}
</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>
);
}
/* Stat tile: bez boxa — mini etykieta (uppercase) + duża wartość */
export function StatTile({
label,
value,
valueClassName = 'truncate',
className = '',
}: {
label: ReactNode;
value: ReactNode;
/** Styl wartości (domyślnie `truncate`; np. `break-words` dla długich tekstów). */
valueClassName?: string;
className?: string;
}) {
return (
<div data-slot="stat-tile" className={`min-w-0 ${className}`.trim()}>
<div className="text-[11px] uppercase tracking-[0.1em] text-dim font-bold">{label}</div>
<div className={`font-display text-[1.5rem] leading-tight font-bold tabular-nums tracking-[-0.02em] ${valueClassName}`.trim()}>{value}</div>
</div>
);
}
/* 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>
);
}
/* 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>
);
}
/* 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>
);
}
/* Empty state */
export function EmptyState({
icon: Icon,
title,
description,
action,
}: {
icon: React.ComponentType<{ className?: string }>;
title: string;
description?: string;
action?: ReactNode;
}) {
return (
<div data-slot="empty-state" 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.95rem] max-w-sm">{description}</p>}
{action && <div className="mt-4">{action}</div>}
</div>
);
}
/* Tabs — przy przepełnieniu: ukryty scrollbar + strzałki przewijające o kolejną
grupę zakładek; aktywna zakładka dosuwana do widoku. */
export function Tabs({
tabs,
active,
onChange,
}: {
tabs: { id: string; label: string }[];
active: string;
onChange: (id: string) => void;
}) {
const scrollRef = useRef<HTMLDivElement>(null);
const [overflow, setOverflow] = useState(false);
const [canPrev, setCanPrev] = useState(false);
const [canNext, setCanNext] = useState(false);
const updateArrows = () => {
const el = scrollRef.current;
if (!el) return;
const over = el.scrollWidth > el.clientWidth + 2;
setOverflow(over);
setCanPrev(over && el.scrollLeft > 2);
setCanNext(over && el.scrollLeft + el.clientWidth < el.scrollWidth - 2);
};
useEffect(() => {
updateArrows();
window.addEventListener('resize', updateArrows);
return () => window.removeEventListener('resize', updateArrows);
}, [tabs.length]);
// aktywna zakładka zawsze w widoku (dosuwa też zapamiętany scroll)
useEffect(() => {
const el = scrollRef.current;
const btn = el?.querySelector<HTMLElement>(`[data-tab-id="${CSS.escape(active)}"]`);
if (!el || !btn) return;
const br = btn.getBoundingClientRect();
const er = el.getBoundingClientRect();
if (br.left < er.left) el.scrollBy({ left: br.left - er.left - 8, behavior: 'smooth' });
else if (br.right > er.right) el.scrollBy({ left: br.right - er.right + 8, behavior: 'smooth' });
updateArrows();
}, [active]);
const scrollByGroup = (dir: 1 | -1) => {
const el = scrollRef.current;
if (!el) return;
el.scrollBy({ left: dir * el.clientWidth * 0.9, behavior: 'smooth' });
};
return (
<div data-slot="tabs" className="flex items-center gap-1.5">
{/* strzałki poza scrollem — nigdy nie nachodzą na zakładki; miejsce zarezerwowane,
żeby layout nie skakał przy przewijaniu */}
<div className={cn('shrink-0', overflow ? 'w-7' : 'w-0')}>
{canPrev && (
<button
type="button"
aria-label="Poprzednie zakładki"
onClick={() => scrollByGroup(-1)}
className="grid h-7 w-7 cursor-pointer place-items-center rounded-full border border-line bg-card text-dim shadow-card transition-colors hover:text-ink"
>
<ChevronLeft className="h-4 w-4" />
</button>
)}
</div>
<div
ref={scrollRef}
onScroll={updateArrows}
className="flex min-w-0 flex-1 gap-1 p-1 bg-input rounded-[10px] border border-line overflow-x-auto [scroll-snap-type:x_mandatory] [scroll-padding-inline:4px] [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden"
>
{tabs.map((t) => (
<button
key={t.id}
type="button"
data-tab-id={t.id}
data-active={active === t.id || undefined}
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 [scroll-snap-align:start] ${
active === t.id ? 'bg-card text-ink border border-line shadow-card' : 'border border-transparent text-dim hover:text-ink'
}`}
>
{t.label}
</button>
))}
</div>
<div className={cn('shrink-0', overflow ? 'w-7' : 'w-0')}>
{canNext && (
<button
type="button"
aria-label="Następne zakładki"
onClick={() => scrollByGroup(1)}
className="grid h-7 w-7 cursor-pointer place-items-center rounded-full border border-line bg-card text-dim shadow-card transition-colors hover:text-ink"
>
<ChevronRight className="h-4 w-4" />
</button>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,308 @@
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';
import { X } from 'lucide-react';
import { Button } from './button';
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './dialog';
/* Modal — Radix Dialog: focus trap, Esc, scroll-lock, aria; bottom-sheet na mobile.
`wide` = szerszy panel (sm:max-w-2xl) dla rozbudowanych formularzy. */
export function Modal({
open,
onClose,
title,
children,
wide,
}: {
open: boolean;
onClose: () => void;
title: string;
children: ReactNode;
wide?: boolean;
}) {
return (
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className={wide ? 'sm:max-w-2xl' : undefined}>
<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>
);
}
/* Number pad dialog — mobile-friendly numeric entry (keypad + Wpisz/Anuluj). */
export function NumberPadDialog({
open,
title,
value,
hint,
onConfirm,
onClose,
}: {
open: boolean;
title: string;
value: string;
hint?: string;
onConfirm: (value: string) => void;
onClose: () => void;
}) {
const [draft, setDraft] = useState(value);
useEffect(() => {
if (open) setDraft(value);
}, [open, value]);
const press = (d: string) => {
setDraft((cur) => {
if (d === 'C') return '';
if (d === '⌫') return cur.slice(0, -1);
if (cur.length >= 3) return cur;
return cur + d;
});
};
const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'C', '0', '⌫'];
return (
<Modal open={open} onClose={onClose} title={title}>
<div className="mb-4">
<input
value={draft}
onChange={(e) => setDraft(e.target.value.replace(/\D/g, '').slice(0, 3))}
inputMode="numeric"
placeholder="—"
aria-label={title}
className="w-full text-center text-5xl font-bold font-display tabular-nums text-ink bg-input border border-line rounded-[10px] py-2 shadow-(--inset-shadow) focus:outline-none focus:border-accent-text focus:ring-[3px] focus:ring-accent/18"
/>
{hint && <div className="text-center text-dim text-[0.85rem] mt-1.5">{hint}</div>}
</div>
<div className="grid grid-cols-3 gap-2 mb-4">
{KEYS.map((d) => (
<button
key={d}
type="button"
onClick={() => press(d)}
aria-label={d === 'C' ? 'Wyczyść' : d === '⌫' ? 'Usuń cyfrę' : d}
className="h-14 rounded-[10px] bg-input border border-line text-xl font-semibold text-ink shadow-(--inset-shadow) cursor-pointer hover:border-accent/55 hover:text-accent-text active:bg-line/40 transition-all duration-150"
>
{d}
</button>
))}
</div>
<div className="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3">
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
Anuluj
</Button>
<Button onClick={() => onConfirm(draft)} className="w-full sm:w-auto">
Wpisz
</Button>
</div>
</Modal>
);
}
/* Difficulty slider dialog — 1 (łatwo) … 5 (trudno). */
export function DifficultyDialog({
open,
value,
onConfirm,
onClose,
}: {
open: boolean;
value: string;
onConfirm: (value: string) => void;
onClose: () => void;
}) {
const normalize = (v: string) => {
const parsed = v === '' ? NaN : parseInt(v);
return String(isNaN(parsed) ? 3 : Math.max(1, Math.min(5, parsed)));
};
const [draft, setDraft] = useState(() => normalize(value));
useEffect(() => {
if (open) setDraft(normalize(value));
}, [open, value]);
return (
<Modal open={open} onClose={onClose} title="Trudność">
<div className="text-center mb-5">
<div className="text-5xl font-bold tabular-nums text-ink">{draft}</div>
</div>
<div className="mb-5">
<input
type="range"
min={1}
max={5}
step={1}
value={parseInt(draft)}
onChange={(e) => setDraft(e.target.value)}
aria-label="Trudność (suwak)"
className="w-full accent-accent cursor-pointer"
/>
<div className="flex justify-between text-dim text-[0.85rem] mt-2">
<span>łatwo</span>
<span>trudno</span>
</div>
</div>
<div className="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3">
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
Anuluj
</Button>
<Button onClick={() => onConfirm(draft)} className="w-full sm:w-auto">
Wpisz
</Button>
</div>
</Modal>
);
}
/* Metadata for the set fields edited in SetEditDialog. */
const SET_FIELD_META: { key: 'reps' | 'rir' | 'difficulty'; label: string; hint: string }[] = [
{ key: 'reps', label: 'Powtórzenia', hint: 'liczba powtórzeń' },
{ key: 'rir', label: 'RIR', hint: '0–10 (reps in reserve)' },
{ key: 'difficulty', label: 'Trudność', hint: '1–5' },
];
export type SetFieldValues = { reps: string; rir: string; difficulty: string };
export type PlannedValues = { reps: number | null; rir: number | null; difficulty: number | null };
/* Bulk set editor — fill in all set fields at once (each via the number pad). */
export function SetEditDialog({
open,
setIndex,
values,
planned,
title,
onSave,
onClose,
}: {
open: boolean;
setIndex: number;
values: SetFieldValues;
planned: PlannedValues;
/** Tytuł okna — domyślnie „Uzupełnij serię N” (przekazuj „Edytuj serię N” dla uzupełnionych serii). */
title?: string;
onSave: (values: SetFieldValues) => void;
onClose: () => void;
}) {
const [drafts, setDrafts] = useState<SetFieldValues>(values);
const [editingField, setEditingField] = useState<'reps' | 'rir' | 'difficulty' | null>(null);
useEffect(() => {
if (open) setDrafts(values);
}, [open, values]);
const editing = editingField ? SET_FIELD_META.find((f) => f.key === editingField) : undefined;
const hasNorm = planned.reps != null;
const fillNorm = () => {
setDrafts({
reps: planned.reps?.toString() ?? '',
rir: planned.rir?.toString() ?? '',
difficulty: planned.difficulty?.toString() ?? '',
});
};
return (
<>
<Modal open={open} onClose={onClose} title={title ?? `Uzupełnij serię ${setIndex + 1}`}>
{hasNorm && (
<Button variant="secondary" size="sm" onClick={fillNorm} className="mb-3 w-full">
Norma spełniona
</Button>
)}
<div className="space-y-2 mb-4">
{SET_FIELD_META.map((f) => (
<button
key={f.key}
type="button"
onClick={() => setEditingField(f.key)}
className="w-full flex items-center justify-between rounded-[10px] border border-line bg-input px-3.5 py-3 shadow-(--inset-shadow) cursor-pointer hover:border-accent/55 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60"
>
<span className="text-[0.9rem] font-semibold text-ink">{f.label}</span>
<span className={`text-[1.1rem] font-bold ${drafts[f.key] ? 'text-ink' : 'text-dim'}`}>
{drafts[f.key] || '—'}
</span>
</button>
))}
</div>
<div className="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3">
<Button variant="secondary" onClick={onClose} className="w-full sm:w-auto">
Anuluj
</Button>
<Button onClick={() => onSave(drafts)} className="w-full sm:w-auto">
Zapisz
</Button>
</div>
</Modal>
{editing &&
(editing.key === 'difficulty' ? (
<DifficultyDialog
open
value={drafts[editing.key]}
onConfirm={(v) => {
setDrafts((d) => ({ ...d, [editing.key]: v }));
setEditingField(null);
}}
onClose={() => setEditingField(null)}
/>
) : (
<NumberPadDialog
open
title={editing.label}
value={drafts[editing.key]}
hint={editing.hint}
onConfirm={(v) => {
setDrafts((d) => ({ ...d, [editing.key]: v }));
setEditingField(null);
}}
onClose={() => setEditingField(null)}
/>
))}
</>
);
}

View File

@@ -0,0 +1,16 @@
import { Moon, Sun } from 'lucide-react';
import { useTheme } from '../../store/theme';
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,21 @@
import type { ReactNode } from 'react';
export function H1({ className = '', children }: { className?: string; children: ReactNode }) {
return <h1 className={`text-[1.75rem] 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.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>;
}
export function Muted({ className = '', children }: { className?: string; children: ReactNode }) {
return <span className={`text-dim ${className}`.trim()}>{children}</span>;
}
export function Loading({ children = 'Ładowanie…' }: { children?: ReactNode }) {
return <div className="text-dim">{children}</div>;
}

View File

@@ -0,0 +1,128 @@
import { useState } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from './button';
import { formatMonth } from '../../store/body-params';
import { fmtDate } from '../../lib/format';
const WEEK_DOWS = ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'Nd'];
function localDayKey(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
function parseIsoLocal(iso: string): Date {
const [y, m, d] = iso.split('-').map(Number);
return new Date(y, m - 1, d);
}
function mondayOf(d: Date): Date {
const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
return x;
}
function addDaysLocal(d: Date, n: number): Date {
const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() + n);
return x;
}
/** Poniedziałek bieżącego tygodnia (czas lokalny) — najwcześniej dozwolony tydzień startu. */
export function currentMonday(): Date {
const now = new Date();
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate());
d.setDate(d.getDate() - ((d.getDay() + 6) % 7));
return d;
}
/** Czy podany tydzień (poniedziałek YYYY-MM-DD) jest miniony. */
export function isPastWeek(monday: string): boolean {
if (!monday) return false;
const [y, m, d] = monday.split('-').map(Number);
return new Date(y, m - 1, d) < currentMonday();
}
/* Wybór tygodnia startu: siatka miesiąca, w której kliknięcie dowolnego dnia zaznacza
CAŁY tydzień (Pn–Nd) — data startu to poniedziałek zaznaczonego tygodnia.
Minione tygodnie są zablokowane (start nie może być w przeszłości). */
export function WeekPicker({ value, onChange }: { value: string; onChange: (monday: string) => void }) {
const now = new Date();
const [view, setView] = useState<[number, number]>(() => {
if (value) {
const [y, m] = value.split('-').map(Number);
return [y, m];
}
return [now.getFullYear(), now.getMonth() + 1];
});
const [y, m] = view;
const shift = (delta: number) => {
const d = new Date(y, m - 1 + delta, 1);
setView([d.getFullYear(), d.getMonth() + 1]);
};
// Monday-first grid
const firstDay = new Date(y, m - 1, 1);
const startOffset = (firstDay.getDay() + 6) % 7;
const gridStart = new Date(y, m - 1, 1 - startOffset);
const cells: Date[] = [];
for (let i = 0; i < 42; i++) {
const d = new Date(gridStart);
d.setDate(gridStart.getDate() + i);
cells.push(d);
}
const selMondayKey = value ? localDayKey(mondayOf(parseIsoLocal(value))) : null;
return (
<div className="w-full max-w-xs">
<div className="flex items-center justify-between gap-2 mb-2">
<Button size="sm" variant="ghost" onClick={() => shift(-1)} aria-label="Poprzedni miesiąc">
<ChevronLeft className="w-4 h-4" />
</Button>
<span className="text-[0.9rem] font-semibold">{formatMonth(`${y}-${String(m).padStart(2, '0')}`)}</span>
<Button size="sm" variant="ghost" onClick={() => shift(1)} aria-label="Następny miesiąc">
<ChevronRight className="w-4 h-4" />
</Button>
</div>
<div className="grid grid-cols-7 gap-1" role="group" aria-label="Wybór tygodnia startu">
{WEEK_DOWS.map((d) => (
<div key={d} className="text-center text-dim text-[0.75rem] py-1">
{d}
</div>
))}
{cells.map((d, i) => {
const inMonth = d.getMonth() === m - 1;
const weekMonday = mondayOf(d);
const isPast = isPastWeek(localDayKey(weekMonday));
const isSel = selMondayKey != null && localDayKey(weekMonday) === selMondayKey;
return (
<button
key={i}
type="button"
disabled={isPast}
onClick={() => onChange(localDayKey(weekMonday))}
aria-pressed={isSel}
className={`h-8 rounded-md text-[0.8rem] transition-colors ${
isPast
? 'text-dim/40 cursor-not-allowed'
: isSel
? 'bg-accent/15 text-accent-text font-bold cursor-pointer'
: inMonth
? 'text-ink hover:bg-line/30 cursor-pointer'
: 'text-dim/60 hover:bg-line/30 cursor-pointer'
}`}
>
{d.getDate()}
</button>
);
})}
</div>
{value && (
<p className="text-dim text-[0.8rem] mt-2">
Start: tydzień {fmtDate(value)} – {fmtDate(localDayKey(addDaysLocal(parseIsoLocal(value), 6)))}
</p>
)}
</div>
);
}

55
app/src/lib/format.ts Normal file
View File

@@ -0,0 +1,55 @@
/** Nickname jako główna nazwa, z fallbackiem na imię + nazwisko. */
export function displayName(
u: { nickname?: string | null; firstName?: string | null; lastName?: string | null },
fallback = '—',
): string {
return u.nickname || [u.firstName, u.lastName].filter(Boolean).join(' ') || fallback;
}
export function fmtDate(iso: string | null | undefined): string {
if (!iso) return '—';
return new Date(iso).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit', year: 'numeric' });
}
export function fmtDateTime(iso: string | null | undefined): string {
if (!iso) return '—';
return new Date(iso).toLocaleString('pl-PL', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
}
/** Czas względny po polsku: „przed chwilą”, „5 min temu”, „wczoraj”, potem data. */
export function timeAgo(iso: string | null | undefined): string {
if (!iso) return '—';
const diffMin = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
if (diffMin < 1) return 'przed chwilą';
if (diffMin < 60) return `${diffMin} min temu`;
const h = Math.floor(diffMin / 60);
if (h < 24) return `${h} godz. temu`;
const d = Math.floor(h / 24);
if (d === 1) return 'wczoraj';
if (d < 7) return `${d} dni temu`;
return fmtDate(iso);
}
/** Polska odmiana: „została 1 seria”, „zostały 2 serie”, „zostało 5 serii”. */
export function setsPlural(n: number): string {
if (n === 1) return 'została 1 seria';
const last = n % 10;
const lastTwo = n % 100;
if (last >= 2 && last <= 4 && !(lastTwo >= 12 && lastTwo <= 14)) return `zostały ${n} serie`;
return `zostało ${n} serii`;
}
export function todayStr(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export function monthStr(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}

View File

@@ -1,5 +1,5 @@
import type { Plan, PlanDay, Session, SocialMediaPlatform, TraineeFlag } from '../api/types';
import type { BadgeColor } from './ui';
import type { BadgeColor } from '../components/ui';
export const MUSCLE_NAMES: Record<string, string> = {
chest: 'Klatka',
@@ -55,59 +55,3 @@ export const SOCIAL_MEDIA_LABELS: Record<SocialMediaPlatform, string> = {
X: 'X',
OTHER: 'Inne',
};
/** Nickname jako główna nazwa, z fallbackiem na imię + nazwisko. */
export function displayName(
u: { nickname?: string | null; firstName?: string | null; lastName?: string | null },
fallback = '—',
): string {
return u.nickname || [u.firstName, u.lastName].filter(Boolean).join(' ') || fallback;
}
export function fmtDate(iso: string | null | undefined): string {
if (!iso) return '—';
return new Date(iso).toLocaleDateString('pl-PL', { day: '2-digit', month: '2-digit', year: 'numeric' });
}
export function fmtDateTime(iso: string | null | undefined): string {
if (!iso) return '—';
return new Date(iso).toLocaleString('pl-PL', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
}
/** Czas względny po polsku: „przed chwilą”, „5 min temu”, „wczoraj”, potem data. */
export function timeAgo(iso: string | null | undefined): string {
if (!iso) return '—';
const diffMin = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
if (diffMin < 1) return 'przed chwilą';
if (diffMin < 60) return `${diffMin} min temu`;
const h = Math.floor(diffMin / 60);
if (h < 24) return `${h} godz. temu`;
const d = Math.floor(h / 24);
if (d === 1) return 'wczoraj';
if (d < 7) return `${d} dni temu`;
return fmtDate(iso);
}
/** Polska odmiana: „została 1 seria”, „zostały 2 serie”, „zostało 5 serii”. */
export function setsPlural(n: number): string {
if (n === 1) return 'została 1 seria';
const last = n % 10;
const lastTwo = n % 100;
if (last >= 2 && last <= 4 && !(lastTwo >= 12 && lastTwo <= 14)) return `zostały ${n} serie`;
return `zostało ${n} serii`;
}
export function todayStr(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export function monthStr(d: Date): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}

View File

@@ -1,7 +1,8 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useCalendar } from '../api/queries';
import { DAY_STATUS, monthStr, MUSCLE_NAMES } from '../components/helpers';
import { monthStr } from '../lib/format';
import { DAY_STATUS, MUSCLE_NAMES } from '../lib/labels';
import { useTopbar } from '../topbar';
import type { CalendarDay } from '../api/types';
import {

View File

@@ -4,7 +4,8 @@ import { CalendarPlus, Dumbbell, Flame, Play } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useActiveSession, useDashboard } from '../api/queries';
import { useAuth } from '../store/auth';
import { DAY_NAMES, fmtDate, MUSCLE_NAMES, todayStr } from '../components/helpers';
import { fmtDate, todayStr } from '../lib/format';
import { DAY_NAMES, MUSCLE_NAMES } from '../lib/labels';
import { useTopbar } from '../topbar';
import { Button, Card, EmptyState, ErrorText, SectionHeader, Skeleton } from '../components/ui';

View File

@@ -14,7 +14,8 @@ import {
useSession,
updateSessionSet,
} from '../api/queries';
import { DAY_NAMES, fmtDate, MUSCLE_NAMES, SESSION_STATUS, setsPlural } from '../components/helpers';
import { fmtDate, setsPlural } from '../lib/format';
import { DAY_NAMES, MUSCLE_NAMES, SESSION_STATUS } from '../lib/labels';
import type { Exercise, PlanSet, Session, SessionExercise, SessionSet } from '../api/types';
import { api } from '../api/client';
import { playAlarm } from '../lib/sound';

View File

@@ -12,7 +12,7 @@ import {
withdrawInvitation,
} from '../api/queries';
import type { GymInvitation, Invitation } from '../api/types';
import { displayName, fmtDate } from '../components/helpers';
import { displayName, fmtDate } from '../lib/format';
import {
Badge,
Button,
@@ -77,7 +77,10 @@ function InvitationRow({
onWithdraw: () => void;
}) {
return (
<div className="flex flex-wrap items-center gap-3 rounded-lg px-2 py-3 transition-colors hover:bg-line/20">
<div
data-slot="list-row"
className="flex flex-wrap items-center gap-3 rounded-lg px-2 py-3 transition-colors hover:bg-line/20"
>
<div className="relative shrink-0">
<Avatar name={avatarName} size={38} />
<span

View File

@@ -1,896 +0,0 @@
import { useMemo, useState } from 'react';
import type { ReactNode } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
Activity,
ChevronDown,
ChevronRight,
Copy,
Plus,
Trash2,
X,
} from 'lucide-react';
import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import {
createPlan,
createTraineePlan,
updatePlan,
updateTraineePlan,
usePlan,
useTraineePlan,
useTraineeExerciseProgress,
useTraineeLatestResults,
useExercises,
type PlanWeekInput,
} from '../api/queries';
import { DAY_NAMES, fmtDate, MUSCLE_NAMES } from '../components/helpers';
import type { Exercise, ExerciseProgress, ExerciseProgressPoint, LatestExerciseResult } from '../api/types';
import {
BackButton,
Badge,
Button,
Card,
ErrorText,
Field,
H2,
H3,
Input,
MiniInput,
Select,
WeekPicker,
isPastWeek,
type BadgeColor,
} from '../components/ui';
import { useTopbar } from '../topbar';
const TOOLTIP_STYLE = {
background: 'var(--bg-card)',
border: '1px solid var(--border)',
borderRadius: 12,
color: 'var(--text)',
};
interface EditorSet {
reps: string;
loadKg: string;
restSec: string;
rir: string;
difficulty: string;
}
interface EditorExercise {
exerciseId: string;
sets: EditorSet[];
}
interface EditorDay {
dayOfWeek: number;
exercises: EditorExercise[];
}
interface EditorWeek {
days: EditorDay[];
detached: boolean;
}
const DEFAULT_SET: EditorSet = { reps: '10', loadKg: '20', restSec: '90', rir: '2', difficulty: '3' };
function emptyWeek(): EditorWeek {
return { days: [], detached: false };
}
function displayedDaysOf(ws: EditorWeek[], wi: number): EditorDay[] {
const w = ws[wi];
if (wi === 0 || w.detached) return w.days;
return ws[0].days;
}
function weekFromApi(week: { index: number; days: { dayOfWeek: number; exercises: { exerciseId: string; sets: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null; difficulty: number | null }[] }[] }[] }): EditorWeek {
return {
days: week.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e) => ({
exerciseId: e.exerciseId,
sets: e.sets.map((s) => ({
reps: s.reps?.toString() ?? '',
loadKg: s.loadKg?.toString() ?? '',
restSec: s.restSec?.toString() ?? '',
rir: s.rir?.toString() ?? '',
difficulty: s.difficulty?.toString() ?? '',
})),
})),
})),
detached: true,
};
}
/* Meta planu: tytuł, długość, tydzień startu (+ hint) — siatka pól. */
function PlanMetaForm({
title,
onTitleChange,
weeksCount,
onWeeksCountChange,
startDate,
onStartDateChange,
showStartWeek,
}: {
title: string;
onTitleChange: (v: string) => void;
weeksCount: number;
onWeeksCountChange: (n: number) => void;
startDate: string;
onStartDateChange: (v: string) => void;
showStartWeek: boolean;
}) {
return (
<Card>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Field label="Tytuł">
<Input
value={title}
onChange={(e) => onTitleChange(e.target.value)}
placeholder="np. Plan masowy 8-tygodniowy"
/>
</Field>
<Field label="Długość (tygodnie)">
<Select value={weeksCount} onChange={(e) => onWeeksCountChange(parseInt(e.target.value))}>
{[1, 2, 3, 4, 5, 6, 7, 8].map((n) => (
<option key={n} value={n}>
{n}
</option>
))}
</Select>
</Field>
</div>
{showStartWeek && (
<div className="mt-4">
<Field label="Tydzień startu">
<WeekPicker value={startDate} onChange={onStartDateChange} />
</Field>
</div>
)}
{showStartWeek && (
<p className="mt-3 text-dim text-[0.875rem]">
Opcjonalnie zaznacz tydzień startu — plan zostanie od razu aktywowany (start = poniedziałek
zaznaczonego tygodnia), a daty dni treningowych wyliczone automatycznie. Bez tygodnia plan
pozostanie szkicem.
</p>
)}
</Card>
);
}
/* Akordeon tygodnia: chevron + H2 + badge podsumowania + Kopiuj z tyg. N / Wyczyść. */
function WeekAccordion({
index,
summary,
expanded,
onToggle,
canCopy,
onCopyPrev,
canClear,
onClear,
children,
}: {
index: number;
summary: { text: string; color: BadgeColor };
expanded: boolean;
onToggle: () => void;
canCopy: boolean;
onCopyPrev: () => void;
canClear: boolean;
onClear: () => void;
children: ReactNode;
}) {
return (
<Card className="mb-4">
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<button
type="button"
onClick={onToggle}
aria-expanded={expanded}
className="flex items-center gap-2 cursor-pointer"
>
{expanded ? (
<ChevronDown className="w-5 h-5 text-dim" />
) : (
<ChevronRight className="w-5 h-5 text-dim" />
)}
<H2 className="mb-0">Tydzień {index + 1}</H2>
</button>
<Badge color={summary.color}>{summary.text}</Badge>
<div className="flex items-center flex-wrap gap-2 sm:ml-auto">
{canCopy && (
<Button variant="secondary" size="sm" onClick={onCopyPrev}>
<Copy className="w-4 h-4" />
Kopiuj z tyg. {index}
</Button>
)}
{canClear && (
<Button variant="secondary" size="sm" onClick={onClear}>
<Trash2 className="w-4 h-4" />
Wyczyść
</Button>
)}
</div>
</div>
{expanded && <div className="mt-4">{children}</div>}
</Card>
);
}
/* Wybór dni treningowych tygodnia: siatka 7 dni. */
function DayPicker({ days, onToggleDay }: { days: EditorDay[]; onToggleDay: (dow: number) => void }) {
return (
<div className="grid grid-cols-7 gap-1.5" role="group" aria-label="Dni treningowe">
{[1, 2, 3, 4, 5, 6, 7].map((dow) => {
const selected = days.some((d) => d.dayOfWeek === dow);
return (
<button
key={dow}
type="button"
aria-pressed={selected}
onClick={() => onToggleDay(dow)}
title={DAY_NAMES[dow]}
className={`rounded-lg py-2 text-[0.8rem] font-semibold border transition-colors cursor-pointer ${
selected
? 'bg-accent text-accent-ink border-accent'
: 'bg-input border-line text-dim hover:border-accent hover:text-accent-text'
}`}
>
{DAY_NAMES[dow].slice(0, 3)}
</button>
);
})}
</div>
);
}
/* Wiersz serii: Seria N + X + grid MiniInput. */
function SetEditor({
set,
index,
onField,
onRemove,
}: {
set: EditorSet;
index: number;
onField: (field: keyof EditorSet, value: string) => void;
onRemove: () => void;
}) {
return (
<div className="rounded-[10px] bg-input/40 px-3 py-2.5">
<div className="mb-2 flex items-center justify-between">
<span className="text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
Seria {index + 1}
</span>
<button
type="button"
aria-label={`Usuń serię ${index + 1}`}
onClick={onRemove}
className="p-1.5 -m-1.5 text-dim hover:text-danger cursor-pointer"
>
<X className="w-4 h-4" />
</button>
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2">
<MiniInput
label="Powt."
value={set.reps}
onChange={(v) => onField('reps', v)}
inputMode="numeric"
/>
<MiniInput
label="Obciążenie (kg)"
value={set.loadKg}
onChange={(v) => onField('loadKg', v)}
inputMode="decimal"
/>
<MiniInput
label="Przerwa (s)"
value={set.restSec}
onChange={(v) => onField('restSec', v)}
inputMode="numeric"
/>
<MiniInput
label="RIR"
value={set.rir}
onChange={(v) => onField('rir', v)}
inputMode="numeric"
/>
<MiniInput
label="Trudność"
value={set.difficulty}
onChange={(v) => onField('difficulty', v)}
inputMode="numeric"
/>
</div>
</div>
);
}
/* Ćwiczenie dnia: nazwa + Wyniki/Usuń + serie + Dodaj serię (+ panel wyników). */
function ExerciseEditor({
exercise,
exerciseName,
isTraineeMode,
resultsOpen,
onToggleResults,
onRemove,
onSetField,
onAddSet,
onRemoveSet,
latest,
points,
onPrefill,
}: {
exercise: EditorExercise;
exerciseName: (eid: string) => string;
isTraineeMode: boolean;
resultsOpen: boolean;
onToggleResults: () => void;
onRemove: () => void;
onSetField: (si: number, field: keyof EditorSet, value: string) => void;
onAddSet: () => void;
onRemoveSet: (si: number) => void;
latest: LatestExerciseResult | undefined;
points: ExerciseProgressPoint[];
onPrefill: () => void;
}) {
return (
<div className="rounded-lg border border-line bg-card/40 p-3">
<div className="mb-1 flex items-center justify-between gap-3">
<strong className="text-[0.95rem]">{exerciseName(exercise.exerciseId)}</strong>
<div className="flex items-center gap-2">
{isTraineeMode && (
<Button variant="secondary" size="sm" onClick={onToggleResults}>
<Activity className="w-4 h-4" />
Wyniki
</Button>
)}
<Button variant="danger" size="sm" onClick={onRemove}>
<X className="w-4 h-4" />
Usuń
</Button>
</div>
</div>
<div className="flex flex-col gap-1.5">
{exercise.sets.map((s, si) => (
<SetEditor
key={si}
set={s}
index={si}
onField={(field, value) => onSetField(si, field, value)}
onRemove={() => onRemoveSet(si)}
/>
))}
</div>
{isTraineeMode && resultsOpen && (
<ExerciseResultsPanel latest={latest} points={points} onPrefill={onPrefill} />
)}
<Button variant="secondary" size="sm" className="mt-3" onClick={onAddSet}>
<Plus className="w-4 h-4" />
Dodaj serię
</Button>
</div>
);
}
/* Dzień tygodnia: H3 + badge ćwiczeń + lista ćwiczeń + select „+ dodaj ćwiczenie…”. */
function DayEditor({
day,
weekIndex,
dayIndex,
exerciseName,
isTraineeMode,
grouped,
resultsOpenKey,
onToggleResults,
onAddExercise,
onRemoveExercise,
onSetField,
onAddSet,
onRemoveSet,
latestByExercise,
progressByExercise,
onPrefill,
}: {
day: EditorDay;
weekIndex: number;
dayIndex: number;
exerciseName: (eid: string) => string;
isTraineeMode: boolean;
grouped: Map<string, Exercise[]>;
resultsOpenKey: string | null;
onToggleResults: (ei: number) => void;
onAddExercise: (exerciseId: string) => void;
onRemoveExercise: (ei: number) => void;
onSetField: (ei: number, si: number, field: keyof EditorSet, value: string) => void;
onAddSet: (ei: number) => void;
onRemoveSet: (ei: number, si: number) => void;
latestByExercise: Map<string, LatestExerciseResult>;
progressByExercise: Map<string, ExerciseProgress>;
onPrefill: (ei: number) => void;
}) {
return (
<div className="py-3">
<div className="mb-2 flex items-center justify-between gap-3">
<H3 className="mb-0">{DAY_NAMES[day.dayOfWeek]}</H3>
<Badge color={day.exercises.length > 0 ? 'green' : 'gray'}>
{day.exercises.length > 0
? `${day.exercises.length} ${day.exercises.length === 1 ? 'ćwiczenie' : 'ćwiczeń'}`
: 'brak ćwiczeń'}
</Badge>
</div>
<div className="flex flex-col gap-2">
{day.exercises.map((ex, ei) => (
<ExerciseEditor
key={ei}
exercise={ex}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
resultsOpen={resultsOpenKey === `${weekIndex}:${dayIndex}:${ei}`}
onToggleResults={() => onToggleResults(ei)}
onRemove={() => onRemoveExercise(ei)}
onSetField={(si, field, value) => onSetField(ei, si, field, value)}
onAddSet={() => onAddSet(ei)}
onRemoveSet={(si) => onRemoveSet(ei, si)}
latest={latestByExercise.get(ex.exerciseId)}
points={progressByExercise.get(ex.exerciseId)?.points ?? []}
onPrefill={() => onPrefill(ei)}
/>
))}
</div>
<Select
defaultValue=""
className="mt-3 sm:max-w-xs"
onChange={(e) => {
if (e.target.value) {
onAddExercise(e.target.value);
e.target.value = '';
}
}}
>
<option value="">+ dodaj ćwiczenie…</option>
{[...grouped.entries()].map(([muscle, list]) => (
<optgroup key={muscle} label={MUSCLE_NAMES[muscle] || muscle}>
{list.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</optgroup>
))}
</Select>
</div>
);
}
export default function PlanEditor() {
const { id, userId, planId } = useParams();
const traineeUserId = userId ?? '';
const isTraineeMode = !!traineeUserId;
const planIdParam = id ?? planId ?? '';
const isEdit = !!planIdParam;
useTopbar({
title: isTraineeMode
? isEdit
? 'Edycja planu podopiecznego'
: 'Plan dla podopiecznego'
: isEdit
? 'Edycja planu'
: 'Nowy plan',
});
const navigate = useNavigate();
const ownerPlan = usePlan(isTraineeMode ? '' : planIdParam);
const traineePlan = useTraineePlan(traineeUserId, isTraineeMode ? planIdParam : '');
const planData = isTraineeMode ? traineePlan.data : ownerPlan.data;
const { data: exData } = useExercises();
const { data: latestData } = useTraineeLatestResults(traineeUserId);
const { data: progressData } = useTraineeExerciseProgress(traineeUserId);
const [title, setTitle] = useState('');
const [startDate, setStartDate] = useState('');
const [weeksCount, setWeeksCount] = useState(4);
const [weeks, setWeeks] = useState<EditorWeek[]>(Array.from({ length: 4 }, () => emptyWeek()));
const [expandedWeek, setExpandedWeek] = useState(0);
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const [initialized, setInitialized] = useState(!isEdit);
const [resultsOpenKey, setResultsOpenKey] = useState<string | null>(null);
const backPath = isTraineeMode ? `/trainees/${traineeUserId}?tab=plans` : '/plans';
const exercises = exData?.exercises ?? [];
// Initialize from API when editing
if (isEdit && planData && !initialized) {
setTitle(planData.plan.title);
setWeeksCount(planData.plan.weeksCount);
setWeeks(planData.plan.weeks.map((w) => weekFromApi(w)));
setInitialized(true);
}
const grouped = useMemo(() => {
const g = new Map<string, Exercise[]>();
for (const p of exercises) {
const list = g.get(p.primaryMuscle) ?? [];
list.push(p);
g.set(p.primaryMuscle, list);
}
return g;
}, [exercises]);
const latestByExercise = useMemo(
() => new Map((latestData?.results ?? []).map((r) => [r.exerciseId, r])),
[latestData],
);
const progressByExercise = useMemo(
() => new Map((progressData?.exercises ?? []).map((p) => [p.exerciseId, p])),
[progressData],
);
const editWeek = (wi: number, updater: (w: EditorWeek) => Partial<EditorWeek>) =>
setWeeks((ws) => {
const next = ws.map((w, i) => {
if (i !== wi) return w;
const base = i > 0 && !w.detached ? { ...w, days: JSON.parse(JSON.stringify(ws[0].days)) } : w;
return { ...base, ...updater(base), detached: true };
});
return next;
});
const addDay = (wi: number, dayOfWeek: number) =>
editWeek(wi, (w) => ({
days: [...w.days, { dayOfWeek, exercises: [] }].sort((a, b) => a.dayOfWeek - b.dayOfWeek),
}));
const removeDay = (wi: number, dayOfWeek: number) =>
editWeek(wi, (w) => ({ days: w.days.filter((d) => d.dayOfWeek !== dayOfWeek) }));
const addExercise = (wi: number, di: number, exerciseId: string) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di ? { ...d, exercises: [...d.exercises, { exerciseId, sets: [{ ...DEFAULT_SET }] }] } : d,
),
}));
const removeExercise = (wi: number, di: number, ei: number) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di ? { ...d, exercises: d.exercises.filter((_, x) => x !== ei) } : d,
),
}));
const setSetField = (wi: number, di: number, ei: number, si: number, field: keyof EditorSet, value: string) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di
? {
...d,
exercises: d.exercises.map((ex, x) =>
x === ei
? { ...ex, sets: ex.sets.map((s, y) => (y === si ? { ...s, [field]: value } : s)) }
: ex,
),
}
: d,
),
}));
const addSet = (wi: number, di: number, ei: number) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di
? {
...d,
exercises: d.exercises.map((ex, x) =>
x === ei ? { ...ex, sets: [...ex.sets, { ...DEFAULT_SET }] } : ex,
),
}
: d,
),
}));
const removeSet = (wi: number, di: number, ei: number, si: number) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) => {
if (idx !== di) return d;
const updated = d.exercises.map((ex, x) =>
x === ei ? { ...ex, sets: ex.sets.filter((_, y) => y !== si) } : ex,
);
// An exercise without sets is meaningless — drop it.
if (updated[ei].sets.length === 0) {
return { ...d, exercises: updated.filter((_, x) => x !== ei) };
}
return { ...d, exercises: updated };
}),
}));
/** Prefill serii z ostatniej sesji podopiecznego (reps/loadKg; brak danych → domyślne). */
const prefillExercise = (wi: number, di: number, ei: number, latest: LatestExerciseResult) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di
? {
...d,
exercises: d.exercises.map((ex, x) =>
x === ei
? {
...ex,
sets: latest.sets.map((ls) => ({
...DEFAULT_SET,
reps: ls.reps != null ? String(ls.reps) : DEFAULT_SET.reps,
loadKg: ls.loadKg != null ? String(ls.loadKg) : DEFAULT_SET.loadKg,
})),
}
: ex,
),
}
: d,
),
}));
const copyPrevWeek = (wi: number) => {
if (wi === 0) return;
setWeeks((ws) => {
const prevDays = displayedDaysOf(ws, wi - 1);
return ws.map((w, i) => (i === wi ? { days: JSON.parse(JSON.stringify(prevDays)), detached: true } : w));
});
};
const clearWeek = (wi: number) =>
setWeeks((ws) => ws.map((w, i) => (i === wi ? { ...w, days: [], detached: true } : w)));
const dayLabel = (n: number) => (n === 1 ? '1 dzień' : `${n} dni`);
const weekSummary = (wi: number, w: EditorWeek, days: EditorDay[]): { text: string; color: BadgeColor } => {
if (days.length === 0) {
if (wi === 0) return { text: 'pusty', color: 'gray' };
return w.detached ? { text: 'przerwa', color: 'blue' } : { text: 'odzwierciedla tyg. 1', color: 'yellow' };
}
return { text: dayLabel(days.length), color: 'green' };
};
const save = async () => {
setError('');
if (!title.trim()) {
setError('Podaj tytuł planu');
return;
}
if (weeks.length !== weeksCount) {
setError(`Plan ma ${weeksCount} tygodni — zdefiniuj je wszystkie`);
return;
}
const body: { title: string; weeksCount: number; weeks: PlanWeekInput[]; startDate?: string } = {
title: title.trim(),
weeksCount,
weeks: weeks.map((_, i) => ({
index: i,
days: displayedDaysOf(weeks, i).map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e, oi) => ({
exerciseId: e.exerciseId,
order: oi,
sets: e.sets.map((s, si) => ({
index: si,
reps: s.reps ? parseInt(s.reps) : null,
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
restSec: s.restSec ? parseInt(s.restSec) : null,
rir: s.rir !== '' ? parseInt(s.rir) : null,
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
})),
})),
})),
})),
};
// Data startu tylko przy tworzeniu — plan tworzony i aktywowany w jednym kroku.
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
if (!isEdit && startDate) {
if (isPastWeek(startDate)) {
setError('Tydzień startu nie może być w przeszłości');
return;
}
body.startDate = startDate;
}
setSaving(true);
try {
if (isTraineeMode) {
if (isEdit) await updateTraineePlan(traineeUserId, planIdParam, body);
else await createTraineePlan(traineeUserId, body);
navigate(backPath);
return;
}
if (isEdit) {
await updatePlan(planIdParam, body);
} else {
const res = await createPlan(body);
navigate(`/plans/${res.plan.id}`);
return;
}
navigate(`/plans/${planIdParam}`);
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd zapisu');
} finally {
setSaving(false);
}
};
const exerciseName = (eid: string) => exercises.find((p) => p.id === eid)?.name ?? eid;
return (
<>
<div className="flex justify-end mb-4">
<BackButton onClick={() => navigate(backPath)} />
</div>
<PlanMetaForm
title={title}
onTitleChange={setTitle}
weeksCount={weeksCount}
onWeeksCountChange={(n) => {
setWeeksCount(n);
setWeeks((ws) => {
const next = [...ws];
while (next.length < n) {
const prev = next[next.length - 1] ?? emptyWeek();
next.push({ days: JSON.parse(JSON.stringify(prev.days)), detached: true });
}
return next.slice(0, n);
});
}}
startDate={startDate}
onStartDateChange={setStartDate}
showStartWeek={!isEdit}
/>
{weeks.map((w, wi) => {
const days = displayedDaysOf(weeks, wi);
const summary = weekSummary(wi, w, days);
const expanded = expandedWeek === wi;
return (
<WeekAccordion
key={wi}
index={wi}
summary={summary}
expanded={expanded}
onToggle={() => setExpandedWeek(expanded ? -1 : wi)}
canCopy={wi > 0}
onCopyPrev={() => copyPrevWeek(wi)}
canClear={days.length > 0 || !w.detached}
onClear={() => clearWeek(wi)}
>
<DayPicker
days={days}
onToggleDay={(dow) =>
days.some((d) => d.dayOfWeek === dow) ? removeDay(wi, dow) : addDay(wi, dow)
}
/>
{days.length === 0 && (
<p className="text-dim mt-3">
{wi === 0
? 'Wybierz dni treningowe powyżej — pozostałe tygodnie będą je odzwierciedlać.'
: w.detached
? 'Tydzień wolny (przerwa) — pozostanie pusty.'
: 'Odzwierciedla tydzień 1. Kliknij dzień, aby edytować niezależnie.'}
</p>
)}
{days.length > 0 && (
<div className="mt-3 divide-y divide-line">
{days.map((d, di) => (
<DayEditor
key={d.dayOfWeek}
day={d}
weekIndex={wi}
dayIndex={di}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
grouped={grouped}
resultsOpenKey={resultsOpenKey}
onToggleResults={(ei) => {
const key = `${wi}:${di}:${ei}`;
setResultsOpenKey(resultsOpenKey === key ? null : key);
}}
onAddExercise={(exerciseId) => addExercise(wi, di, exerciseId)}
onRemoveExercise={(ei) => removeExercise(wi, di, ei)}
onSetField={(ei, si, field, value) => setSetField(wi, di, ei, si, field, value)}
onAddSet={(ei) => addSet(wi, di, ei)}
onRemoveSet={(ei, si) => removeSet(wi, di, ei, si)}
latestByExercise={latestByExercise}
progressByExercise={progressByExercise}
onPrefill={(ei) => {
const latest = latestByExercise.get(d.exercises[ei].exerciseId);
if (latest) prefillExercise(wi, di, ei, latest);
}}
/>
))}
</div>
)}
</WeekAccordion>
);
})}
<div className="sticky bottom-0 -mx-4 px-4 py-3 bg-bg/95 backdrop-blur border-t border-line mt-2 md:-mx-8 md:px-8">
{error && <ErrorText>{error}</ErrorText>}
<div className="flex flex-col sm:flex-row gap-3">
<Button onClick={save} disabled={saving} className="w-full sm:w-auto">
{saving ? 'Zapisywanie…' : isEdit ? 'Zapisz zmiany' : 'Utwórz plan'}
</Button>
<Button variant="secondary" onClick={() => navigate(backPath)} className="w-full sm:w-auto">
Anuluj
</Button>
</div>
</div>
</>
);
}
/**
* Panel wyników podopiecznego (tylko tryb podopiecznego): wykres 1RM per sesja,
* ostatnia sesja (serie powt. @ kg) i przycisk „Wstaw wyniki" (prefill serii).
*/
function ExerciseResultsPanel({
latest,
points,
onPrefill,
}: {
latest: LatestExerciseResult | undefined;
points: ExerciseProgressPoint[];
onPrefill: () => void;
}) {
const oneRmPoints = points.filter((p) => p.oneRm != null);
if (!latest && oneRmPoints.length === 0) {
return <p className="mt-3 text-dim text-[0.875rem]">Brak wyników dla tego ćwiczenia.</p>;
}
return (
<div className="mt-3">
<div className="mb-2 flex items-center justify-between gap-2">
<span className="text-[11px] font-bold text-dim uppercase tracking-[0.1em]">
Wyniki podopiecznego
</span>
{latest && (
<Button variant="secondary" size="sm" onClick={onPrefill}>
Wstaw wyniki
</Button>
)}
</div>
{oneRmPoints.length >= 2 ? (
<ResponsiveContainer width="100%" height={140}>
<LineChart data={oneRmPoints.map((p) => ({ date: fmtDate(p.date), oneRm: p.oneRm }))}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Line
type="monotone"
dataKey="oneRm"
name="1RM (kg)"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
) : (
<p className="text-dim text-[0.875rem]">Za mało danych na wykres 1RM (min. 2 sesje).</p>
)}
{latest && (
<div className="mt-2">
<div className="mb-1.5 text-[0.875rem]">
Ostatnia sesja: <strong>{fmtDate(latest.date)}</strong>
{latest.oneRm != null && <span className="text-dim"> · 1RM {latest.oneRm} kg</span>}
</div>
<div className="flex flex-wrap gap-1.5">
{latest.sets.map((s, i) => (
<span key={i} className="rounded-lg border border-line bg-input px-2 py-1 text-[0.875rem]">
{s.reps ?? '?'} powt.{s.loadKg != null ? ` @ ${s.loadKg} kg` : ''}
</span>
))}
</div>
</div>
)}
</div>
);
}

View File

@@ -1,795 +0,0 @@
import { useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { Archive, Flame, Plus } from 'lucide-react';
import {
abandonTraineePlan,
activateTraineePlan,
addTraineeComment,
archiveTrainee,
completeTraineePlan,
deleteComment,
deleteTraineePlan,
useMe,
useTrainee,
useTraineeCalendar,
useTraineeExerciseProgress,
useTraineeHistory,
useTraineeMoves,
useTraineePlan,
useTraineePlans,
useTraineeReport,
} from '../api/queries';
import {
DAY_STATUS,
displayName,
fmtDate,
fmtDateTime,
monthStr,
MUSCLE_NAMES,
PLAN_STATUS,
SOCIAL_MEDIA_LABELS,
todayStr,
TRAINEE_FLAGS,
} from '../components/helpers';
import HistoryTable from '../components/HistoryTable';
import ExerciseProgressCards from '../components/ExerciseProgressCards';
import { PlanActions } from '../components/plans/PlanActions';
import { PlanDayRow } from '../components/plans/PlanWeeks';
import {
CalendarMonthNav,
MobileDayList,
MonthGrid,
dayKey,
groupDaysByDate,
monthCells,
} from '../components/calendar/CalendarView';
import {
BackButton,
Badge,
Button,
Card,
ConfirmDialog,
ErrorText,
H2,
H3,
ListRow,
Loading,
Muted,
PageHeader,
ProgressBar,
SectionHeader,
Skeleton,
StatTile,
Tabs,
} from '../components/ui';
import { useToast } from '../components/toast';
import { useTopbar } from '../topbar';
import { Avatar } from '../components/Avatar';
import type { CalendarDay, DayMoveEntry, Plan, TraineeDetail as TraineeDetailData, TraineeReport } from '../api/types';
function DisciplineHeatmap({ days }: { days: TraineeReport['days'] }) {
const today = todayStr();
return (
<div>
<div className="flex flex-wrap gap-1.5">
{days.map((d) => {
const dateStr = d.date.slice(0, 10);
const isPast = dateStr < today;
let cls = 'bg-line/40';
if (d.status === 'COMPLETED')
cls = 'bg-accent shadow-[0_1px_6px_-2px_color-mix(in_srgb,var(--accent)_70%,transparent)]';
else if (d.status === 'SKIPPED') cls = 'bg-danger';
else if (isPast) cls = 'bg-line';
const border = d.moved ? 'border-warn' : 'border-transparent';
return (
<div
key={d.date}
title={`${fmtDate(d.date)} — ${DAY_STATUS[d.status].label}${d.moved ? ' (przesunięty)' : ''}`}
className={`h-4 w-4 rounded-[5px] ${cls} border-2 ${border}`}
/>
);
})}
</div>
<div className="mt-3 flex flex-wrap gap-3 text-[0.875rem] text-dim">
<span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded bg-accent inline-block" />ukończony</span>
<span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded bg-danger inline-block" />pominięty</span>
<span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded bg-line inline-block" />zaplanowany (miniony)</span>
<span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded bg-line/40 inline-block" />zaplanowany (przyszły)</span>
<span className="flex items-center gap-1.5"><span className="w-3 h-3 rounded border-2 border-warn inline-block" />przesunięty</span>
</div>
</div>
);
}
/* Zakładka „Przegląd”: podstawowe informacje (StatTile) + karta aktywnego planu. */
function OverviewTab({ data }: { data: TraineeDetailData }) {
return (
<>
<Card>
<SectionHeader title="Podstawowe informacje" />
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4 sm:gap-5">
<StatTile
label="Siłownie"
value={data.gyms.length > 0 ? data.gyms.map((g) => g.name).join(', ') : '—'}
/>
<StatTile label="Ostatnia sesja" value={data.lastSessionAt ? fmtDateTime(data.lastSessionAt) : '—'} />
<StatTile
label="Killstreak"
value={
<span className="inline-flex items-center gap-1.5">
<Flame className={`w-4 h-4 ${data.killstreak > 0 ? 'text-accent-text' : 'text-dim'}`} />
{data.killstreak}
</span>
}
/>
<StatTile
label="Social media"
value={
data.socialMedia && data.socialMedia.length > 0 ? (
<span className="flex flex-wrap gap-x-3 gap-y-1">
{data.socialMedia.map((s, i) => (
<a
key={i}
href={s.url}
target="_blank"
rel="noopener noreferrer"
className="text-accent-text hover:underline"
>
{s.platform === 'OTHER' ? s.label || 'Inne' : SOCIAL_MEDIA_LABELS[s.platform]}
</a>
))}
</span>
) : (
'—'
)
}
/>
</div>
</Card>
<Card>
<SectionHeader title="Aktywny plan" />
{data.activePlan ? (
<>
<div className="mb-2 flex flex-wrap items-center justify-between gap-2">
<strong>{data.activePlan.title}</strong>
<Muted className="text-[0.875rem]">start {fmtDate(data.activePlan.startDate)}</Muted>
</div>
{data.progress && (
<>
<div className="mb-1 flex items-center justify-between text-[0.875rem]">
<Muted>
{data.progress.completed}/{data.progress.total} dni
</Muted>
<Muted>{data.progress.percent}%</Muted>
</div>
<ProgressBar percent={data.progress.percent} />
</>
)}
<div className="mt-4 grid grid-cols-2 gap-4">
<StatTile label="Nadmiar (serie)" value={data.extra ? `+${data.extra.sets}` : '—'} />
<StatTile label="Deficyt (serie)" value={data.missing ? data.missing.sets : '—'} />
</div>
{data.nextTraining && (
<div className="mt-4">
<H3 className="mb-1.5">Następny trening</H3>
<div className="text-[0.875rem]">
<strong>{fmtDate(data.nextTraining.date)}</strong>
<Muted className="ml-2">
{data.nextTraining.exercises.map((e) => MUSCLE_NAMES[e.muscle] || e.muscle).join(', ')}
</Muted>
</div>
</div>
)}
</>
) : (
<p className="text-dim">Podopieczny nie ma aktywnego planu.</p>
)}
</Card>
</>
);
}
/* Zakładka „Dyscyplina”: heatmapa + przesunięte dni (ListRow). */
function DisciplineTab({
report,
reportLoading,
reportError,
movesData,
movesLoading,
movesError,
}: {
report: TraineeReport | undefined;
reportLoading: boolean;
reportError: Error | null;
movesData: { moves: DayMoveEntry[] } | undefined;
movesLoading: boolean;
movesError: Error | null;
}) {
return (
<Card>
<SectionHeader title="Dyscyplina" />
{reportLoading && <Loading />}
{reportError && <ErrorText>Błąd: {(reportError as Error).message}</ErrorText>}
{!reportLoading && !reportError && (report?.days.length ?? 0) === 0 && (
<p className="text-dim">Brak dni w aktywnym planie.</p>
)}
{!reportLoading && !reportError && (report?.days.length ?? 0) > 0 && (
<DisciplineHeatmap days={report!.days} />
)}
<div className="mt-4">
<H3 className="mb-1.5">Przesunięte dni</H3>
{movesLoading && <Loading />}
{movesError && <ErrorText>Błąd: {(movesError as Error).message}</ErrorText>}
{!movesLoading && !movesError && (movesData?.moves.length ?? 0) === 0 && (
<p className="text-dim">Brak przesuniętych dni.</p>
)}
{!movesLoading && !movesError && (movesData?.moves.length ?? 0) > 0 && (
<div className="divide-y divide-line">
{movesData!.moves.map((m) => (
<ListRow
key={`${m.dayId}-${m.movedAt}`}
title={
<>
{fmtDate(m.fromDate)} <span>→</span> {fmtDate(m.toDate)}
</>
}
meta={m.reason ? <span>· {m.reason}</span> : undefined}
actions={<Muted className="text-[0.875rem]">przesunięto {fmtDateTime(m.movedAt)}</Muted>}
/>
))}
</div>
)}
</div>
</Card>
);
}
/* Karta wybranego dnia w widoku trenera (read-only — bez CTA „Rozpocznij trening"). */
function TraineeDayCard({ day }: { day: CalendarDay }) {
const st = DAY_STATUS[day.status];
return (
<Card>
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
<H2 className="mb-0 capitalize">
{new Date(day.date).toLocaleDateString('pl-PL', {
weekday: 'long',
day: 'numeric',
month: 'long',
})}
</H2>
<Badge color={st.color}>{st.label}</Badge>
</div>
{day.exercises.length === 0 ? (
<p className="mt-2 text-dim">Brak ćwiczeń.</p>
) : (
<ul className="mt-2 divide-y divide-line">
{day.exercises.map((e, i) => (
<li
key={i}
className="flex items-center justify-between gap-3 rounded-lg px-2 py-2 transition-colors hover:bg-line/20"
>
<span className="min-w-0 truncate font-semibold">{e.name}</span>
<span className="shrink-0 text-dim text-[0.8125rem]">{MUSCLE_NAMES[e.muscle] || e.muscle}</span>
</li>
))}
</ul>
)}
</Card>
);
}
/* Zakładka „Kalendarz”: kalendarz podopiecznego (dni jego aktywnego planu). */
function TraineeCalendarTab({ userId }: { userId: string }) {
const now = new Date();
const [month, setMonth] = useState(monthStr(now));
const [selectedDayId, setSelectedDayId] = useState<string | null>(null);
const { data, isLoading, error } = useTraineeCalendar(userId, month);
const goToMonth = (m: string) => {
setMonth(m);
setSelectedDayId(null);
};
const { cells, monthIndex } = monthCells(month);
const todayKey = dayKey(now);
const daysByDate = data ? groupDaysByDate(data.days) : new Map<string, CalendarDay[]>();
const selected = data?.days.find((d) => d.id === selectedDayId);
const sortedDays = [...(data?.days ?? [])].sort((a, b) => a.date.localeCompare(b.date));
return (
<>
<Card>
<div className="mb-4 flex items-center justify-between gap-3">
<SectionHeader title="Kalendarz podopiecznego" />
<CalendarMonthNav month={month} onMonth={goToMonth} />
</div>
{isLoading && <Skeleton className="h-64" />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
{data && (
<MonthGrid
cells={cells}
daysByDate={daysByDate}
todayKey={todayKey}
monthIndex={monthIndex}
selectedDayId={selectedDayId}
onSelect={setSelectedDayId}
/>
)}
{data && <MobileDayList days={sortedDays} onSelect={setSelectedDayId} />}
</Card>
{selected && <TraineeDayCard day={selected} />}
</>
);
}
export default function TraineeDetail() {
const { userId = '' } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { push } = useToast();
const [params] = useSearchParams();
const initialOpenSessionId = params.get('session') ?? undefined;
// ?tab=<id> otwiera podaną zakładkę (np. ?tab=plans po zapisie planu); ?session=<id>
// (np. z karty załącznika w komunikatorze) otwiera od razu zakładkę Historia.
const initialTab = params.get('tab') ?? (initialOpenSessionId ? 'history' : 'overview');
const [tab, setTab] = useState(initialTab);
const [confirmOpen, setConfirmOpen] = useState(false);
const [busy, setBusy] = useState(false);
const { data, isLoading, error } = useTrainee(userId);
const { data: hist, isLoading: histLoading, error: histError } = useTraineeHistory(userId);
const { data: report, isLoading: reportLoading, error: reportError } = useTraineeReport(userId);
const { data: movesData, isLoading: movesLoading, error: movesError } = useTraineeMoves(userId);
const { data: meData } = useMe();
const addComment = async (args: { sessionId: string; sessionExerciseId: string; body: string }) => {
try {
await addTraineeComment(userId, args);
await queryClient.invalidateQueries({ queryKey: ['trainees', userId, 'history'] });
push('Komentarz dodany', 'success');
} catch (e) {
push((e as Error).message, 'error');
}
};
const removeComment = async (commentId: string) => {
try {
await deleteComment(commentId, { userId });
await queryClient.invalidateQueries({ queryKey: ['trainees', userId, 'history'] });
push('Komentarz usunięty', 'success');
} catch (e) {
push((e as Error).message, 'error');
}
};
const doArchive = async () => {
setBusy(true);
try {
await archiveTrainee(userId);
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['trainees'] }),
queryClient.invalidateQueries({ queryKey: ['invitations'] }),
]);
push('Relacja zarchiwizowana', 'success');
navigate('/trainees');
} catch (e) {
push((e as Error).message, 'error');
setConfirmOpen(false);
} finally {
setBusy(false);
}
};
useTopbar({
title: 'Podopieczni',
actions: [
{ label: 'Archiwizuj', icon: Archive, variant: 'danger', onClick: () => setConfirmOpen(true) },
],
});
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-9 w-48" />
<Skeleton className="h-48" />
<Skeleton className="h-64" />
</div>
);
}
if (error || !data) {
return (
<Card>
<ErrorText>Błąd: {(error as Error).message}</ErrorText>
</Card>
);
}
const name = displayName(data.user);
return (
<>
<PageHeader
title={name}
badge={
<div className="flex flex-wrap items-center gap-1.5">
<Avatar name={name} size={26} />
<span
title="Killstreak"
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[0.75rem] font-bold tabular-nums ${
data.killstreak > 0 ? 'bg-accent/14 text-accent-text' : 'bg-dim/13 text-dim'
}`}
>
<Flame className="h-3 w-3" />
{data.killstreak}
</span>
{data.flags.map((f) => (
<Badge key={f} color={TRAINEE_FLAGS[f].color}>
{TRAINEE_FLAGS[f].label}
</Badge>
))}
</div>
}
actions={<BackButton onClick={() => navigate('/trainees')} />}
/>
<div className="mb-4">
<Tabs
tabs={[
{ id: 'overview', label: 'Przegląd' },
{ id: 'calendar', label: 'Kalendarz' },
{ id: 'history', label: 'Historia' },
{ id: 'progress', label: 'Postępy' },
{ id: 'discipline', label: 'Dyscyplina' },
{ id: 'plans', label: 'Plany' },
]}
active={tab}
onChange={setTab}
/>
</div>
{tab === 'overview' && <OverviewTab data={data} />}
{tab === 'calendar' && <TraineeCalendarTab userId={userId} />}
{tab === 'history' && (
<Card>
<H2 className="mb-0">Historia treningów</H2>
{histLoading && <Loading />}
{histError && <ErrorText>Błąd: {(histError as Error).message}</ErrorText>}
{!histLoading && !histError && (hist?.sessions ?? []).length === 0 && (
<p className="text-dim">Brak sesji.</p>
)}
{!histLoading && !histError && (hist?.sessions ?? []).length > 0 && (
<HistoryTable
sessions={hist!.sessions}
canComment
myUserId={meData?.user.id}
initialOpenSessionId={initialOpenSessionId}
onAddComment={addComment}
onDeleteComment={removeComment}
/>
)}
</Card>
)}
{tab === 'progress' && (
<ProgressTab
userId={userId}
report={report}
reportLoading={reportLoading}
reportError={reportError}
/>
)}
{tab === 'discipline' && (
<DisciplineTab
report={report}
reportLoading={reportLoading}
reportError={reportError}
movesData={movesData}
movesLoading={movesLoading}
movesError={movesError}
/>
)}
{tab === 'plans' && <TraineePlansTab userId={userId} />}
<ConfirmDialog
open={confirmOpen}
onClose={() => setConfirmOpen(false)}
onConfirm={() => void doArchive()}
title="Archiwizuj relację"
description={`Czy na pewno chcesz zarchiwizować relację z ${name}? Podopieczny przestanie być widoczny na Twojej liście.`}
confirmLabel="Archiwizuj"
danger
busy={busy}
/>
</>
);
}
interface ProgressTabProps {
userId: string;
report: TraineeReport | undefined;
reportLoading: boolean;
reportError: Error | null;
}
function ProgressTab({ userId, report, reportLoading, reportError }: ProgressTabProps) {
const { data: progress, isLoading: progressLoading, error: progressError } =
useTraineeExerciseProgress(userId);
return (
<>
<Card>
<SectionHeader
title="Postępy per ćwiczenie"
description="1RM Epley: zaplanowane obciążenie × (1 + powtórzenia/30), maks. per sesja; objętość = Σ obciążenie × powtórzenia."
/>
{progressLoading && <Loading />}
{progressError && <ErrorText>Błąd: {(progressError as Error).message}</ErrorText>}
{!progressLoading && !progressError && <ExerciseProgressCards exercises={progress?.exercises ?? []} />}
</Card>
<Card>
<SectionHeader
title="Objętość per partia"
description="Faktyczne serie względem planu i zalecanego zakresu: akcent = w zakresie, pomarańcz = &gt;10% powyżej, czerwień = deficyt."
/>
{reportLoading && <Loading />}
{reportError && <ErrorText>Błąd: {(reportError as Error).message}</ErrorText>}
{!reportLoading && !reportError && (report?.muscles ?? []).length === 0 && (
<p className="text-dim">Brak aktywnego planu — raport niedostępny.</p>
)}
{!reportLoading && !reportError && (report?.muscles ?? []).length > 0 && (
<div className="flex flex-col gap-3">
{(report?.muscles ?? []).map((m) => {
const scaleMax = Math.max(
m.planned.sets,
m.actual.sets,
m.recommendedRange?.setsMax ?? 0,
1,
);
const pct = Math.min(100, Math.round((m.actual.sets / scaleMax) * 100));
const tone = !m.recommendedRange
? 'bg-info'
: m.actual.sets < m.recommendedRange.setsMin
? 'bg-danger'
: m.actual.sets > m.recommendedRange.setsMax * 1.1
? 'bg-warn'
: 'bg-(image:--progress-grad)';
return (
<div key={m.muscle}>
<div className="grid grid-cols-[92px_1fr_auto] items-center gap-3 text-[0.8125rem]">
<span className="min-w-0 truncate font-semibold">
{MUSCLE_NAMES[m.muscle] || m.muscle}
</span>
<div className="h-2 overflow-hidden rounded-full bg-input">
<div className={`h-full rounded-full ${tone}`} style={{ width: `${pct}%` }} />
</div>
<span className="shrink-0 text-dim tabular-nums">
{m.actual.sets}/{m.planned.sets}
{m.recommendedRange
? ` · ${m.recommendedRange.setsMin}–${m.recommendedRange.setsMax}`
: ''}
</span>
</div>
{(m.extra.sets > 0 || m.missing.sets > 0 || m.outOfRange) && (
<div className="mt-1 flex flex-wrap items-center gap-1.5 sm:pl-[104px]">
{m.extra.sets > 0 && <Badge color="green">+{m.extra.sets} nadmiar</Badge>}
{m.missing.sets > 0 && <Badge color="red">-{m.missing.sets} deficyt</Badge>}
{m.outOfRange && <Badge color="yellow">poza zakresem</Badge>}
</div>
)}
</div>
);
})}
</div>
)}
</Card>
</>
);
}
type PlanAction = { type: 'delete' | 'abandon' | 'complete' | 'activate'; planId: string };
/**
* Zakładka „Plany" w panelu podopiecznego: lista planów podopiecznego + akcje
* (edytuj/aktywuj/usuń/porzuć/ukończ) + podgląd struktury inline + „Utwórz plan".
*/
function TraineePlansTab({ userId }: { userId: string }) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const { push } = useToast();
const { data, isLoading, error } = useTraineePlans(userId);
const { data: meData } = useMe();
const [selectedId, setSelectedId] = useState<string | null>(null);
const { data: detail, isLoading: detailLoading, error: detailError } = useTraineePlan(userId, selectedId ?? '');
const [startDate, setStartDate] = useState('');
const [actionError, setActionError] = useState('');
const [busy, setBusy] = useState(false);
const [confirm, setConfirm] = useState<PlanAction | null>(null);
const plans = data?.plans ?? [];
const selectedDetail = detail?.plan ?? null;
// Blokada aktywacji: podopieczny może mieć tylko jeden aktywny plan na raz.
const hasActivePlan = plans.some((p) => p.status === 'ACTIVE');
const invalidate = () =>
Promise.all([
queryClient.invalidateQueries({ queryKey: ['trainees', userId] }),
queryClient.invalidateQueries({ queryKey: ['trainees', userId, 'plans'] }),
]);
const act = async (fn: () => Promise<unknown>, msg: string) => {
setActionError('');
setBusy(true);
try {
await fn();
await invalidate();
push(msg, 'success');
} catch (e) {
setActionError(e instanceof Error ? e.message : 'Błąd');
} finally {
setBusy(false);
}
};
const creatorLabel = (p: Plan): string | null => {
if (!p.creator) return null;
if (meData?.user.id && p.creator.id === meData.user.id) return null;
const name = [p.creator.firstName, p.creator.lastName].filter(Boolean).join(' ') || 'trener';
return `utworzył: ${name}`;
};
return (
<>
<div className="flex items-center justify-between gap-3 mb-4">
<H2 className="mb-0">Plany podopiecznego</H2>
<Button size="sm" onClick={() => navigate(`/trainees/${userId}/plans/new`)}>
<Plus className="w-4 h-4" />
Utwórz plan
</Button>
</div>
{isLoading && <Loading />}
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
{!isLoading && !error && plans.length === 0 && (
<Card>
<p className="text-dim">Podopieczny nie ma żadnych planów.</p>
</Card>
)}
{!isLoading && !error && plans.length > 0 && (
<Card>
<div className="divide-y divide-line">
{plans.map((p) => {
const st = PLAN_STATUS[p.status];
const isSel = p.id === selectedId;
return (
<div key={p.id} className={isSel ? 'rounded-xl bg-accent/10 px-2 py-3' : 'px-1 py-3'}>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<button
type="button"
className="cursor-pointer font-semibold text-left text-[0.95rem]"
onClick={() => setSelectedId(isSel ? null : p.id)}
>
{p.title}
</button>
<Badge color={st.color}>{st.label}</Badge>
<Muted className="text-[0.875rem]">{p.weeksCount} tyg.</Muted>
{p.startDate && <Muted className="text-[0.875rem]">start {fmtDate(p.startDate)}</Muted>}
{creatorLabel(p) && <Muted className="text-[0.875rem]">{creatorLabel(p)}</Muted>}
</div>
{isSel && (
<div className="mt-3">
{detailLoading && <Loading />}
{detailError && <ErrorText>Błąd: {(detailError as Error).message}</ErrorText>}
{selectedDetail && (
<>
<div className="mb-3">
<PlanActions
plan={selectedDetail}
editTo={`/trainees/${userId}/plans/${selectedDetail.id}/edit`}
busy={busy}
actionError={actionError}
startDate={startDate}
onStartDateChange={setStartDate}
onActivate={() => setConfirm({ type: 'activate', planId: selectedDetail.id })}
onDelete={() => setConfirm({ type: 'delete', planId: selectedDetail.id })}
onComplete={() => setConfirm({ type: 'complete', planId: selectedDetail.id })}
onAbandon={() => setConfirm({ type: 'abandon', planId: selectedDetail.id })}
activateDisabled={hasActivePlan}
hint={
hasActivePlan
? 'Podopieczny ma już aktywny plan — tylko jeden plan może być aktywny. Aby aktywować ten plan, najpierw ukończ lub porzuć aktywny.'
: undefined
}
/>
</div>
{selectedDetail.weeks.map((w) => (
<div key={w.id} className="mb-3">
<H3 className="mb-1.5">Tydzień {w.index + 1}</H3>
{w.days.length === 0 && <p className="text-dim">Brak dni treningowych.</p>}
<div className="divide-y divide-line">
{w.days.map((d) => (
<PlanDayRow key={d.id} day={d} showDate />
))}
</div>
</div>
))}
</>
)}
</div>
)}
</div>
);
})}
</div>
</Card>
)}
<ConfirmDialog
open={confirm?.type === 'activate'}
onClose={() => setConfirm(null)}
onConfirm={() => {
const planId = confirm!.planId;
setConfirm(null);
void act(() => activateTraineePlan(userId, planId, startDate), 'Plan aktywowany');
}}
title="Aktywować plan?"
description="Plan zostanie aktywowany od poniedziałku zaznaczonego tygodnia."
confirmLabel="Aktywuj"
busy={busy}
/>
<ConfirmDialog
open={confirm?.type === 'delete'}
onClose={() => setConfirm(null)}
onConfirm={() => {
const planId = confirm!.planId;
setConfirm(null);
void act(() => deleteTraineePlan(userId, planId), 'Usunięto plan');
}}
title="Usunąć plan?"
description="Plan i wszystkie powiązane dni zostaną trwale usunięte."
confirmLabel="Usuń"
danger
busy={busy}
/>
<ConfirmDialog
open={confirm?.type === 'abandon'}
onClose={() => setConfirm(null)}
onConfirm={() => {
const planId = confirm!.planId;
setConfirm(null);
void act(() => abandonTraineePlan(userId, planId), 'Plan porzucony');
}}
title="Porzucić plan?"
description="Plan zostanie oznaczony jako porzucony — kolejne treningi z niego nie będą planowane."
confirmLabel="Porzuć"
danger
busy={busy}
/>
<ConfirmDialog
open={confirm?.type === 'complete'}
onClose={() => setConfirm(null)}
onConfirm={() => {
const planId = confirm!.planId;
setConfirm(null);
void act(() => completeTraineePlan(userId, planId), 'Plan ukończony');
}}
title="Oznaaczyć jako ukończony?"
description="Plan zostanie oznaczony jako ukończony."
confirmLabel="Ukończ"
busy={busy}
/>
</>
);
}

View File

@@ -22,9 +22,9 @@ import {
useMyGymClaims,
withdrawGymClaim,
withdrawGymInvitation,
} from '../api/queries';
import type { Gym, GymException } from '../api/types';
import { formatGymEquipment } from '../lib/equipment';
} from '../../api/queries';
import type { Gym, GymException } from '../../api/types';
import { formatGymEquipment } from '../../lib/equipment';
import {
BackButton,
Button,
@@ -37,15 +37,15 @@ import {
Modal,
SectionHeader,
Select,
} from '../components/ui';
import { useToast } from '../components/toast';
import { Avatar } from '../components/Avatar';
import { useTopbar, type TopbarAction, type TopbarCustomGroup } from '../topbar';
import { normalizeAvailability, TIME_SLOTS } from '../lib/availability';
import ClaimModal from '../components/ClaimModal';
import InviteGymModal from '../components/InviteGymModal';
import GymGallery from '../components/GymGallery';
import { EquipmentSection, GymEditForm } from './gym-sections';
} from '../../components/ui';
import { useToast } from '../../components/toast';
import { Avatar } from '../../components/Avatar';
import { useTopbar, type TopbarAction, type TopbarCustomGroup } from '../../topbar';
import { normalizeAvailability, TIME_SLOTS } from '../../lib/availability';
import ClaimModal from '../../components/gyms/ClaimModal';
import InviteGymModal from '../../components/gyms/InviteGymModal';
import GymGallery from '../../components/gyms/GymGallery';
import { EquipmentSection, GymEditForm } from './GymSections';
/* Lista godzin otwarcia: wiersz na dzień (czytelna w wąskiej kolumnie), „dziś” wyróżnione. */
function HoursList({ gym }: { gym: Gym }) {

View File

@@ -6,13 +6,13 @@ import {
updateGym,
updateGymEquipmentQuantity,
useEquipment,
} from '../api/queries';
import type { Availability, Gym } from '../api/types';
import { formatEquipmentSpec, formatGymEquipment } from '../lib/equipment';
import { Button, Chip, Field, Input, Loading, SectionHeader, Select } from '../components/ui';
import { useToast } from '../components/toast';
import { AvailabilityEditor } from '../components/AvailabilityEditor';
import { normalizeAvailability } from '../lib/availability';
} from '../../api/queries';
import type { Availability, Gym } from '../../api/types';
import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment';
import { Button, Chip, Field, Input, Loading, SectionHeader, Select } from '../../components/ui';
import { useToast } from '../../components/toast';
import { AvailabilityEditor } from '../../components/AvailabilityEditor';
import { normalizeAvailability } from '../../lib/availability';
/** Formularz edycji danych siłowni (nazwa/lokalizacja/pojemność/prywatność/dostępność). */
export function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void }) {

View File

@@ -14,16 +14,16 @@ import {
useVirtualGyms,
withdrawGymClaim,
withdrawGymInvitation,
} from '../api/queries';
import type { Gym, GymClaim, GymInvitation, VirtualGym } from '../api/types';
import { Badge, Button, Card, EmptyState, ErrorText, H3, ListRow, Loading, MetaItem, Tabs } from '../components/ui';
import { useToast } from '../components/toast';
import { useListSearch } from '../store/list-search';
import { useTopbar } from '../topbar';
import { DAY_NAMES, formatDayRange, normalizeAvailability } from '../lib/availability';
import GymCreateModal from '../components/GymCreateModal';
import ClaimModal from '../components/ClaimModal';
import InviteGymModal from '../components/InviteGymModal';
} from '../../api/queries';
import type { Gym, GymClaim, GymInvitation, VirtualGym } from '../../api/types';
import { Badge, Button, Card, EmptyState, ErrorText, H3, ListRow, Loading, MetaItem, Tabs } from '../../components/ui';
import { useToast } from '../../components/toast';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
import { DAY_NAMES, formatDayRange, normalizeAvailability } from '../../lib/availability';
import GymCreateModal from '../../components/gyms/GymCreateModal';
import ClaimModal from '../../components/gyms/ClaimModal';
import InviteGymModal from '../../components/gyms/InviteGymModal';
type Tab = 'mine' | 'virtual';

View File

@@ -1,17 +1,17 @@
import { Fragment, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { Paperclip, Send } from 'lucide-react';
import { Paperclip, Send, X } from 'lucide-react';
import {
sendMessage,
useHistory,
useMe,
useMessages,
useTraineeHistory,
} from '../api/queries';
import type { HistorySession, Message } from '../api/types';
import MessageAttachmentCard from '../components/MessageAttachmentCard';
import { displayName, fmtDate, fmtDateTime } from '../components/helpers';
} from '../../api/queries';
import type { HistorySession, Message } from '../../api/types';
import MessageAttachmentCard from '../../components/MessageAttachmentCard';
import { displayName, fmtDate, fmtDateTime } from '../../lib/format';
import {
BackButton,
Button,
@@ -23,11 +23,11 @@ import {
Select,
Skeleton,
Textarea,
} from '../components/ui';
import { useToast } from '../components/toast';
import { useTopbar } from '../topbar';
import { Avatar } from '../components/Avatar';
import { Badge } from '../components/ui';
} from '../../components/ui';
import { useToast } from '../../components/toast';
import { useTopbar } from '../../topbar';
import { Avatar } from '../../components/Avatar';
import { Badge } from '../../components/ui';
/* Bąbelek wiadomości: treść + załącznik + czas (mine = prawo, other = lewo). */
function MessageBubble({
@@ -58,10 +58,12 @@ function MessageBubble({
);
}
/* Pisanie wiadomości: textarea + „Załącz wynik” / „Wyślij”. */
/* Pisanie wiadomości: załącznik (opcjonalny) + textarea + „Załącz wynik” / „Wyślij”. */
function ComposerCard({
body,
onBodyChange,
staged,
onRemoveAttachment,
hasSessions,
onAttach,
onSend,
@@ -69,6 +71,8 @@ function ComposerCard({
}: {
body: string;
onBodyChange: (v: string) => void;
staged: { label: string } | null;
onRemoveAttachment: () => void;
hasSessions: boolean;
onAttach: () => void;
onSend: () => void;
@@ -76,6 +80,20 @@ function ComposerCard({
}) {
return (
<Card>
{staged && (
<div className="mb-2 flex items-center gap-2 rounded-[10px] border border-accent/40 bg-accent/10 px-3 py-2">
<Paperclip className="w-4 h-4 shrink-0 text-accent-text" />
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-semibold">{staged.label}</span>
<button
type="button"
aria-label="Usuń załącznik"
onClick={onRemoveAttachment}
className="shrink-0 cursor-pointer rounded p-1 text-dim transition-colors hover:text-danger"
>
<X className="w-4 h-4" />
</button>
</div>
)}
<Textarea
rows={2}
placeholder="Napisz wiadomość…"
@@ -97,7 +115,7 @@ function ComposerCard({
);
}
/* Wybór sesji/ćwiczenia do załączenia w wiadomości. */
/* Wybór sesji/ćwiczenia do załączenia w wiadomości (załącznik trafia do composera). */
function AttachmentPickerModal({
open,
onClose,
@@ -106,9 +124,8 @@ function AttachmentPickerModal({
onSessionChange,
exerciseId,
onExerciseChange,
onSend,
onAttach,
busy,
canSend,
}: {
open: boolean;
onClose: () => void;
@@ -117,9 +134,8 @@ function AttachmentPickerModal({
onSessionChange: (id: string) => void;
exerciseId: string;
onExerciseChange: (id: string) => void;
onSend: () => void;
onAttach: () => void;
busy: boolean;
canSend: boolean;
}) {
const selectedSession = sessions.find((s) => s.id === sessionId);
return (
@@ -157,10 +173,13 @@ function AttachmentPickerModal({
</Select>
</Field>
)}
<Button className="w-full" onClick={onSend} disabled={busy || !canSend}>
<Send className="w-4 h-4" />
Wyślij z załącznikiem
<Button className="w-full" onClick={onAttach} disabled={busy || !sessionId}>
<Paperclip className="w-4 h-4" />
Dodaj załącznik
</Button>
<p className="mt-2 text-dim text-[0.8125rem]">
Załącznik pojawi się nad polem wiadomości — treść możesz dopisać później.
</p>
</Modal>
);
}
@@ -179,6 +198,7 @@ export default function MessageThread() {
const [pickerOpen, setPickerOpen] = useState(false);
const [attachSessionId, setAttachSessionId] = useState('');
const [attachExerciseId, setAttachExerciseId] = useState('');
const [staged, setStaged] = useState<{ sessionId: string; exerciseId: string; label: string } | null>(null);
const [busy, setBusy] = useState(false);
const bottomRef = useRef<HTMLDivElement>(null);
@@ -199,7 +219,7 @@ export default function MessageThread() {
else navigate(`/profile/history?session=${sessionId}`);
};
const doSend = async (withAttachment: boolean) => {
const doSend = async () => {
const text = body.trim();
if (!text) return;
setBusy(true);
@@ -207,15 +227,15 @@ export default function MessageThread() {
await sendMessage(
coachingId,
text,
withAttachment
staged
? {
sessionId: attachSessionId,
...(attachExerciseId ? { sessionExerciseId: attachExerciseId } : {}),
sessionId: staged.sessionId,
...(staged.exerciseId ? { sessionExerciseId: staged.exerciseId } : {}),
}
: undefined,
);
setBody('');
setPickerOpen(false);
setStaged(null);
setAttachSessionId('');
setAttachExerciseId('');
await Promise.all([
@@ -229,6 +249,21 @@ export default function MessageThread() {
}
};
/* Załącznik można dodać przed napisaniem treści — trafia do composera jako etap. */
const stageAttachment = () => {
const session = sessions.find((s) => s.id === attachSessionId);
if (!session) return;
const exerciseName = attachExerciseId
? session.exercises.find((e) => e.id === attachExerciseId)?.name
: null;
setStaged({
sessionId: attachSessionId,
exerciseId: attachExerciseId,
label: `${session.date ? fmtDate(session.date) : '—'} · ${session.plan}${exerciseName ? ` · ${exerciseName}` : ''}`,
});
setPickerOpen(false);
};
if (isLoading) {
return (
<div className="space-y-4">
@@ -288,9 +323,15 @@ export default function MessageThread() {
<ComposerCard
body={body}
onBodyChange={setBody}
staged={staged}
onRemoveAttachment={() => setStaged(null)}
hasSessions={sessions.length > 0}
onAttach={() => setPickerOpen(true)}
onSend={() => void doSend(false)}
onAttach={() => {
setAttachSessionId(staged?.sessionId ?? '');
setAttachExerciseId(staged?.exerciseId ?? '');
setPickerOpen(true);
}}
onSend={() => void doSend()}
busy={busy}
/>
@@ -305,9 +346,8 @@ export default function MessageThread() {
}}
exerciseId={attachExerciseId}
onExerciseChange={setAttachExerciseId}
onSend={() => void doSend(true)}
onAttach={stageAttachment}
busy={busy}
canSend={Boolean(body.trim() && attachSessionId)}
/>
</>
);

View File

@@ -1,17 +1,19 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { MessageSquare } from 'lucide-react';
import { useConversations } from '../api/queries';
import { displayName, timeAgo } from '../components/helpers';
import { Card, EmptyState, ErrorText, Skeleton } from '../components/ui';
import { Avatar } from '../components/Avatar';
import { useListSearch } from '../store/list-search';
import { useTopbar } from '../topbar';
import { useConversations, useMe } from '../../api/queries';
import { displayName, timeAgo } from '../../lib/format';
import { Card, EmptyState, ErrorText, Skeleton } from '../../components/ui';
import { Avatar } from '../../components/Avatar';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
export default function Messages() {
useTopbar({ title: 'Komunikator', search: 'messages' });
const navigate = useNavigate();
const { data, isLoading, error } = useConversations();
const { data: meData } = useMe();
const myId = meData?.user.id;
const query = useListSearch((s) => s.queries.messages);
const setQuery = useListSearch((s) => s.setQuery);
useEffect(() => () => setQuery('messages', ''), [setQuery]);
@@ -27,7 +29,13 @@ export default function Messages() {
const conversations = data?.conversations ?? [];
const q = query.toLowerCase();
const filtered = conversations.filter((c) => !q || displayName(c.other).toLowerCase().includes(q));
const filtered = conversations
.filter((c) => !q || displayName(c.other).toLowerCase().includes(q))
.sort((a, b) => {
const ta = a.lastMessage?.createdAt ?? '';
const tb = b.lastMessage?.createdAt ?? '';
return tb.localeCompare(ta);
});
return (
<Card>
@@ -47,31 +55,49 @@ export default function Messages() {
{filtered.map((c) => {
const name = displayName(c.other);
const unread = c.unreadCount > 0;
const mine = c.lastMessage?.senderId === myId;
return (
<button
key={c.coachingId}
type="button"
onClick={() => navigate(`/messages/${c.coachingId}`)}
className="group flex w-full cursor-pointer items-center gap-3 rounded-lg px-2 py-3 text-left transition-colors hover:bg-line/20"
className="group flex w-full cursor-pointer items-center gap-3 rounded-lg px-2 py-3.5 text-left transition-colors hover:bg-line/20"
>
<Avatar name={name} size={38} />
<div className="relative shrink-0">
<Avatar name={name} size={44} />
{unread && (
<span
aria-hidden="true"
className="absolute -right-0.5 -top-0.5 h-3 w-3 rounded-full border-2 border-card bg-accent"
/>
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<span className={`min-w-0 truncate text-[0.95rem] ${unread ? 'font-bold' : 'font-semibold'}`}>
<div className="flex items-baseline justify-between gap-2">
<span
className={`min-w-0 truncate text-[0.95rem] ${unread ? 'font-bold text-ink' : 'font-semibold'}`}
>
{name}
</span>
{c.lastMessage && (
<span className="shrink-0 text-[0.7rem] tabular-nums text-dim">
<span
className={`shrink-0 text-[0.7rem] tabular-nums ${unread ? 'font-bold text-accent-text' : 'text-dim'}`}
>
{timeAgo(c.lastMessage.createdAt)}
</span>
)}
</div>
<div className="mt-0.5 flex items-center justify-between gap-2">
<span
className={`min-w-0 truncate text-[0.8125rem] ${unread ? 'font-semibold text-ink' : 'text-dim'}`}
>
{c.lastMessage ? c.lastMessage.body : 'Brak wiadomości'}
</span>
{c.lastMessage ? (
<span
className={`min-w-0 truncate text-[0.8125rem] ${unread ? 'font-semibold text-ink' : 'text-dim'}`}
>
{mine ? 'Ty: ' : ''}
{c.lastMessage.body}
</span>
) : (
<span className="min-w-0 truncate text-[0.8125rem] italic text-dim/70">Brak wiadomości</span>
)}
{unread && (
<span className="grid h-[18px] min-w-[18px] shrink-0 place-items-center rounded-full bg-accent px-1 text-[0.65rem] font-extrabold text-accent-ink">
{c.unreadCount}

View File

@@ -10,11 +10,12 @@ import {
useMe,
usePlan,
usePlans,
} from '../api/queries';
import { fmtDate, PLAN_STATUS } from '../components/helpers';
import { PlanWeeks } from '../components/plans/PlanWeeks';
import { useToast } from '../components/toast';
import { useTopbar } from '../topbar';
} from '../../api/queries';
import { fmtDate } from '../../lib/format';
import { PLAN_STATUS } from '../../lib/labels';
import { PlanWeeks } from '../../components/plans/PlanWeeks';
import { useToast } from '../../components/toast';
import { useTopbar } from '../../topbar';
import {
BackButton,
Badge,
@@ -26,7 +27,7 @@ import {
PageHeader,
Skeleton,
WeekPicker,
} from '../components/ui';
} from '../../components/ui';
export default function PlanDetail() {
const { id } = useParams();

View File

@@ -0,0 +1,382 @@
import { useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
createPlan,
createTraineePlan,
updatePlan,
updateTraineePlan,
usePlan,
useTraineePlan,
useTraineeExerciseProgress,
useTraineeLatestResults,
useExercises,
type PlanWeekInput,
} from '../../api/queries';
import type { Exercise, LatestExerciseResult } from '../../api/types';
import { BackButton, Button, ErrorText, isPastWeek, type BadgeColor } from '../../components/ui';
import { useTopbar } from '../../topbar';
import { DEFAULT_SET, displayedDaysOf, emptyWeek, weekFromApi, type EditorDay, type EditorSet, type EditorWeek } from './plan-editor/types';
import { PlanMetaForm } from './plan-editor/PlanMetaForm';
import { WeekAccordion } from './plan-editor/WeekAccordion';
import { DayPicker } from './plan-editor/DayPicker';
import { DayEditor } from './plan-editor/DayEditor';
export default function PlanEditor() {
const { id, userId, planId } = useParams();
const traineeUserId = userId ?? '';
const isTraineeMode = !!traineeUserId;
const planIdParam = id ?? planId ?? '';
const isEdit = !!planIdParam;
useTopbar({
title: isTraineeMode
? isEdit
? 'Edycja planu podopiecznego'
: 'Plan dla podopiecznego'
: isEdit
? 'Edycja planu'
: 'Nowy plan',
});
const navigate = useNavigate();
const ownerPlan = usePlan(isTraineeMode ? '' : planIdParam);
const traineePlan = useTraineePlan(traineeUserId, isTraineeMode ? planIdParam : '');
const planData = isTraineeMode ? traineePlan.data : ownerPlan.data;
const { data: exData } = useExercises();
const { data: latestData } = useTraineeLatestResults(traineeUserId);
const { data: progressData } = useTraineeExerciseProgress(traineeUserId);
const [title, setTitle] = useState('');
const [startDate, setStartDate] = useState('');
const [weeksCount, setWeeksCount] = useState(4);
const [weeks, setWeeks] = useState<EditorWeek[]>(Array.from({ length: 4 }, () => emptyWeek()));
const [expandedWeek, setExpandedWeek] = useState(0);
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const [initialized, setInitialized] = useState(!isEdit);
const [resultsOpenKey, setResultsOpenKey] = useState<string | null>(null);
const backPath = isTraineeMode ? `/trainees/${traineeUserId}?tab=plans` : '/plans';
const exercises = exData?.exercises ?? [];
// Initialize from API when editing
if (isEdit && planData && !initialized) {
setTitle(planData.plan.title);
setWeeksCount(planData.plan.weeksCount);
setWeeks(planData.plan.weeks.map((w) => weekFromApi(w)));
setInitialized(true);
}
const grouped = useMemo(() => {
const g = new Map<string, Exercise[]>();
for (const p of exercises) {
const list = g.get(p.primaryMuscle) ?? [];
list.push(p);
g.set(p.primaryMuscle, list);
}
return g;
}, [exercises]);
const latestByExercise = useMemo(
() => new Map((latestData?.results ?? []).map((r) => [r.exerciseId, r])),
[latestData],
);
const progressByExercise = useMemo(
() => new Map((progressData?.exercises ?? []).map((p) => [p.exerciseId, p])),
[progressData],
);
const editWeek = (wi: number, updater: (w: EditorWeek) => Partial<EditorWeek>) =>
setWeeks((ws) => {
const next = ws.map((w, i) => {
if (i !== wi) return w;
const base = i > 0 && !w.detached ? { ...w, days: JSON.parse(JSON.stringify(ws[0].days)) } : w;
return { ...base, ...updater(base), detached: true };
});
return next;
});
const addDay = (wi: number, dayOfWeek: number) =>
editWeek(wi, (w) => ({
days: [...w.days, { dayOfWeek, exercises: [] }].sort((a, b) => a.dayOfWeek - b.dayOfWeek),
}));
const removeDay = (wi: number, dayOfWeek: number) =>
editWeek(wi, (w) => ({ days: w.days.filter((d) => d.dayOfWeek !== dayOfWeek) }));
const addExercise = (wi: number, di: number, exerciseId: string) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di ? { ...d, exercises: [...d.exercises, { exerciseId, sets: [{ ...DEFAULT_SET }] }] } : d,
),
}));
const removeExercise = (wi: number, di: number, ei: number) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di ? { ...d, exercises: d.exercises.filter((_, x) => x !== ei) } : d,
),
}));
const setSetField = (wi: number, di: number, ei: number, si: number, field: keyof EditorSet, value: string) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di
? {
...d,
exercises: d.exercises.map((ex, x) =>
x === ei
? { ...ex, sets: ex.sets.map((s, y) => (y === si ? { ...s, [field]: value } : s)) }
: ex,
),
}
: d,
),
}));
const addSet = (wi: number, di: number, ei: number) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di
? {
...d,
exercises: d.exercises.map((ex, x) =>
x === ei ? { ...ex, sets: [...ex.sets, { ...DEFAULT_SET }] } : ex,
),
}
: d,
),
}));
const removeSet = (wi: number, di: number, ei: number, si: number) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) => {
if (idx !== di) return d;
const updated = d.exercises.map((ex, x) =>
x === ei ? { ...ex, sets: ex.sets.filter((_, y) => y !== si) } : ex,
);
// An exercise without sets is meaningless — drop it.
if (updated[ei].sets.length === 0) {
return { ...d, exercises: updated.filter((_, x) => x !== ei) };
}
return { ...d, exercises: updated };
}),
}));
/** Prefill serii z ostatniej sesji podopiecznego (reps/loadKg; brak danych → domyślne). */
const prefillExercise = (wi: number, di: number, ei: number, latest: LatestExerciseResult) =>
editWeek(wi, (w) => ({
days: w.days.map((d, idx) =>
idx === di
? {
...d,
exercises: d.exercises.map((ex, x) =>
x === ei
? {
...ex,
sets: latest.sets.map((ls) => ({
...DEFAULT_SET,
reps: ls.reps != null ? String(ls.reps) : DEFAULT_SET.reps,
loadKg: ls.loadKg != null ? String(ls.loadKg) : DEFAULT_SET.loadKg,
})),
}
: ex,
),
}
: d,
),
}));
const copyPrevWeek = (wi: number) => {
if (wi === 0) return;
setWeeks((ws) => {
const prevDays = displayedDaysOf(ws, wi - 1);
return ws.map((w, i) => (i === wi ? { days: JSON.parse(JSON.stringify(prevDays)), detached: true } : w));
});
};
const clearWeek = (wi: number) =>
setWeeks((ws) => ws.map((w, i) => (i === wi ? { ...w, days: [], detached: true } : w)));
const dayLabel = (n: number) => (n === 1 ? '1 dzień' : `${n} dni`);
const weekSummary = (wi: number, w: EditorWeek, days: EditorDay[]): { text: string; color: BadgeColor } => {
if (days.length === 0) {
if (wi === 0) return { text: 'pusty', color: 'gray' };
return w.detached ? { text: 'przerwa', color: 'blue' } : { text: 'odzwierciedla tyg. 1', color: 'yellow' };
}
return { text: dayLabel(days.length), color: 'green' };
};
const save = async () => {
setError('');
if (!title.trim()) {
setError('Podaj tytuł planu');
return;
}
if (weeks.length !== weeksCount) {
setError(`Plan ma ${weeksCount} tygodni — zdefiniuj je wszystkie`);
return;
}
const body: { title: string; weeksCount: number; weeks: PlanWeekInput[]; startDate?: string } = {
title: title.trim(),
weeksCount,
weeks: weeks.map((_, i) => ({
index: i,
days: displayedDaysOf(weeks, i).map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e, oi) => ({
exerciseId: e.exerciseId,
order: oi,
sets: e.sets.map((s, si) => ({
index: si,
reps: s.reps ? parseInt(s.reps) : null,
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
restSec: s.restSec ? parseInt(s.restSec) : null,
rir: s.rir !== '' ? parseInt(s.rir) : null,
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
})),
})),
})),
})),
};
// Data startu tylko przy tworzeniu — plan tworzony i aktywowany w jednym kroku.
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
if (!isEdit && startDate) {
if (isPastWeek(startDate)) {
setError('Tydzień startu nie może być w przeszłości');
return;
}
body.startDate = startDate;
}
setSaving(true);
try {
if (isTraineeMode) {
if (isEdit) await updateTraineePlan(traineeUserId, planIdParam, body);
else await createTraineePlan(traineeUserId, body);
navigate(backPath);
return;
}
if (isEdit) {
await updatePlan(planIdParam, body);
} else {
const res = await createPlan(body);
navigate(`/plans/${res.plan.id}`);
return;
}
navigate(`/plans/${planIdParam}`);
} catch (err) {
setError(err instanceof Error ? err.message : 'Błąd zapisu');
} finally {
setSaving(false);
}
};
const exerciseName = (eid: string) => exercises.find((p) => p.id === eid)?.name ?? eid;
return (
<>
<div className="flex justify-end mb-4">
<BackButton onClick={() => navigate(backPath)} />
</div>
<PlanMetaForm
title={title}
onTitleChange={setTitle}
weeksCount={weeksCount}
onWeeksCountChange={(n) => {
setWeeksCount(n);
setWeeks((ws) => {
const next = [...ws];
while (next.length < n) {
const prev = next[next.length - 1] ?? emptyWeek();
next.push({ days: JSON.parse(JSON.stringify(prev.days)), detached: true });
}
return next.slice(0, n);
});
}}
startDate={startDate}
onStartDateChange={setStartDate}
showStartWeek={!isEdit}
/>
{weeks.map((w, wi) => {
const days = displayedDaysOf(weeks, wi);
const summary = weekSummary(wi, w, days);
const expanded = expandedWeek === wi;
return (
<WeekAccordion
key={wi}
index={wi}
summary={summary}
expanded={expanded}
onToggle={() => setExpandedWeek(expanded ? -1 : wi)}
canCopy={wi > 0}
onCopyPrev={() => copyPrevWeek(wi)}
canClear={days.length > 0 || !w.detached}
onClear={() => clearWeek(wi)}
>
<DayPicker
days={days}
onToggleDay={(dow) =>
days.some((d) => d.dayOfWeek === dow) ? removeDay(wi, dow) : addDay(wi, dow)
}
/>
{days.length === 0 && (
<p className="text-dim mt-3">
{wi === 0
? 'Wybierz dni treningowe powyżej — pozostałe tygodnie będą je odzwierciedlać.'
: w.detached
? 'Tydzień wolny (przerwa) — pozostanie pusty.'
: 'Odzwierciedla tydzień 1. Kliknij dzień, aby edytować niezależnie.'}
</p>
)}
{days.length > 0 && (
<div className="mt-3 divide-y divide-line">
{days.map((d, di) => (
<DayEditor
key={d.dayOfWeek}
day={d}
weekIndex={wi}
dayIndex={di}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
grouped={grouped}
resultsOpenKey={resultsOpenKey}
onToggleResults={(ei) => {
const key = `${wi}:${di}:${ei}`;
setResultsOpenKey(resultsOpenKey === key ? null : key);
}}
onAddExercise={(exerciseId) => addExercise(wi, di, exerciseId)}
onRemoveExercise={(ei) => removeExercise(wi, di, ei)}
onSetField={(ei, si, field, value) => setSetField(wi, di, ei, si, field, value)}
onAddSet={(ei) => addSet(wi, di, ei)}
onRemoveSet={(ei, si) => removeSet(wi, di, ei, si)}
latestByExercise={latestByExercise}
progressByExercise={progressByExercise}
onPrefill={(ei) => {
const latest = latestByExercise.get(d.exercises[ei].exerciseId);
if (latest) prefillExercise(wi, di, ei, latest);
}}
/>
))}
</div>
)}
</WeekAccordion>
);
})}
<div className="sticky bottom-0 -mx-4 px-4 py-3 bg-bg/95 backdrop-blur border-t border-line mt-2 md:-mx-8 md:px-8">
{error && <ErrorText>{error}</ErrorText>}
<div className="flex flex-col sm:flex-row gap-3">
<Button onClick={save} disabled={saving} className="w-full sm:w-auto">
{saving ? 'Zapisywanie…' : isEdit ? 'Zapisz zmiany' : 'Utwórz plan'}
</Button>
<Button variant="secondary" onClick={() => navigate(backPath)} className="w-full sm:w-auto">
Anuluj
</Button>
</div>
</div>
</>
);
}

View File

@@ -1,13 +1,13 @@
import { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { CalendarPlus, Dumbbell, Plus } from 'lucide-react';
import { useMe, usePlans } from '../api/queries';
import { PLAN_STATUS } from '../components/helpers';
import { PlanCard } from '../components/plans/PlanCard';
import { Badge, Button, Card, EmptyState, ErrorText, H3, Skeleton } from '../components/ui';
import type { Plan } from '../api/types';
import { useListSearch } from '../store/list-search';
import { useTopbar } from '../topbar';
import { useMe, usePlans } from '../../api/queries';
import { PLAN_STATUS } from '../../lib/labels';
import { PlanCard } from '../../components/plans/PlanCard';
import { Badge, Button, Card, EmptyState, ErrorText, H3, Skeleton } from '../../components/ui';
import type { Plan } from '../../api/types';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
/** Kolejność kategorii (statusów) na liście planów. */
const STATUS_ORDER: Plan['status'][] = ['ACTIVE', 'DRAFT', 'COMPLETED', 'ABANDONED'];

View File

@@ -0,0 +1,95 @@
import { Badge, H3, Select } from '../../../components/ui';
import { DAY_NAMES, MUSCLE_NAMES } from '../../../lib/labels';
import type { Exercise, ExerciseProgress, LatestExerciseResult } from '../../../api/types';
import type { EditorDay, EditorSet } from './types';
import { ExerciseEditor } from './ExerciseEditor';
/* Dzień tygodnia: H3 + badge ćwiczeń + lista ćwiczeń + select „+ dodaj ćwiczenie…”. */
export function DayEditor({
day,
weekIndex,
dayIndex,
exerciseName,
isTraineeMode,
grouped,
resultsOpenKey,
onToggleResults,
onAddExercise,
onRemoveExercise,
onSetField,
onAddSet,
onRemoveSet,
latestByExercise,
progressByExercise,
onPrefill,
}: {
day: EditorDay;
weekIndex: number;
dayIndex: number;
exerciseName: (eid: string) => string;
isTraineeMode: boolean;
grouped: Map<string, Exercise[]>;
resultsOpenKey: string | null;
onToggleResults: (ei: number) => void;
onAddExercise: (exerciseId: string) => void;
onRemoveExercise: (ei: number) => void;
onSetField: (ei: number, si: number, field: keyof EditorSet, value: string) => void;
onAddSet: (ei: number) => void;
onRemoveSet: (ei: number, si: number) => void;
latestByExercise: Map<string, LatestExerciseResult>;
progressByExercise: Map<string, ExerciseProgress>;
onPrefill: (ei: number) => void;
}) {
return (
<div className="py-3">
<div className="mb-2 flex items-center justify-between gap-3">
<H3 className="mb-0">{DAY_NAMES[day.dayOfWeek]}</H3>
<Badge color={day.exercises.length > 0 ? 'green' : 'gray'}>
{day.exercises.length > 0
? `${day.exercises.length} ${day.exercises.length === 1 ? 'ćwiczenie' : 'ćwiczeń'}`
: 'brak ćwiczeń'}
</Badge>
</div>
<div className="flex flex-col gap-2">
{day.exercises.map((ex, ei) => (
<ExerciseEditor
key={ei}
exercise={ex}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
resultsOpen={resultsOpenKey === `${weekIndex}:${dayIndex}:${ei}`}
onToggleResults={() => onToggleResults(ei)}
onRemove={() => onRemoveExercise(ei)}
onSetField={(si, field, value) => onSetField(ei, si, field, value)}
onAddSet={() => onAddSet(ei)}
onRemoveSet={(si) => onRemoveSet(ei, si)}
latest={latestByExercise.get(ex.exerciseId)}
points={progressByExercise.get(ex.exerciseId)?.points ?? []}
onPrefill={() => onPrefill(ei)}
/>
))}
</div>
<Select
defaultValue=""
className="mt-3 sm:max-w-xs"
onChange={(e) => {
if (e.target.value) {
onAddExercise(e.target.value);
e.target.value = '';
}
}}
>
<option value="">+ dodaj ćwiczenie…</option>
{[...grouped.entries()].map(([muscle, list]) => (
<optgroup key={muscle} label={MUSCLE_NAMES[muscle] || muscle}>
{list.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</optgroup>
))}
</Select>
</div>
);
}

View File

@@ -0,0 +1,29 @@
import { DAY_NAMES } from '../../../lib/labels';
import type { EditorDay } from './types';
/* Wybór dni treningowych tygodnia: siatka 7 dni. */
export function DayPicker({ days, onToggleDay }: { days: EditorDay[]; onToggleDay: (dow: number) => void }) {
return (
<div className="grid grid-cols-7 gap-1.5" role="group" aria-label="Dni treningowe">
{[1, 2, 3, 4, 5, 6, 7].map((dow) => {
const selected = days.some((d) => d.dayOfWeek === dow);
return (
<button
key={dow}
type="button"
aria-pressed={selected}
onClick={() => onToggleDay(dow)}
title={DAY_NAMES[dow]}
className={`rounded-lg py-2 text-[0.8rem] font-semibold border transition-colors cursor-pointer ${
selected
? 'bg-accent text-accent-ink border-accent'
: 'bg-input border-line text-dim hover:border-accent hover:text-accent-text'
}`}
>
{DAY_NAMES[dow].slice(0, 3)}
</button>
);
})}
</div>
);
}

View File

@@ -0,0 +1,73 @@
import { Activity, Plus, X } from 'lucide-react';
import { Button } from '../../../components/ui';
import type { ExerciseProgressPoint, LatestExerciseResult } from '../../../api/types';
import type { EditorExercise, EditorSet } from './types';
import { SetEditor } from './SetEditor';
import { ExerciseResultsPanel } from './ExerciseResultsPanel';
/* Ćwiczenie dnia: nazwa + Wyniki/Usuń + serie + Dodaj serię (+ panel wyników). */
export function ExerciseEditor({
exercise,
exerciseName,
isTraineeMode,
resultsOpen,
onToggleResults,
onRemove,
onSetField,
onAddSet,
onRemoveSet,
latest,
points,
onPrefill,
}: {
exercise: EditorExercise;
exerciseName: (eid: string) => string;
isTraineeMode: boolean;
resultsOpen: boolean;
onToggleResults: () => void;
onRemove: () => void;
onSetField: (si: number, field: keyof EditorSet, value: string) => void;
onAddSet: () => void;
onRemoveSet: (si: number) => void;
latest: LatestExerciseResult | undefined;
points: ExerciseProgressPoint[];
onPrefill: () => void;
}) {
return (
<div className="rounded-lg border border-line bg-card/40 p-3">
<div className="mb-1 flex items-center justify-between gap-3">
<strong className="text-[0.95rem]">{exerciseName(exercise.exerciseId)}</strong>
<div className="flex items-center gap-2">
{isTraineeMode && (
<Button variant="secondary" size="sm" onClick={onToggleResults}>
<Activity className="w-4 h-4" />
Wyniki
</Button>
)}
<Button variant="danger" size="sm" onClick={onRemove}>
<X className="w-4 h-4" />
Usuń
</Button>
</div>
</div>
<div className="flex flex-col gap-1.5">
{exercise.sets.map((s, si) => (
<SetEditor
key={si}
set={s}
index={si}
onField={(field, value) => onSetField(si, field, value)}
onRemove={() => onRemoveSet(si)}
/>
))}
</div>
{isTraineeMode && resultsOpen && (
<ExerciseResultsPanel latest={latest} points={points} onPrefill={onPrefill} />
)}
<Button variant="secondary" size="sm" className="mt-3" onClick={onAddSet}>
<Plus className="w-4 h-4" />
Dodaj serię
</Button>
</div>
);
}

View File

@@ -0,0 +1,79 @@
import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { Button } from '../../../components/ui';
import { fmtDate } from '../../../lib/format';
import type { ExerciseProgressPoint, LatestExerciseResult } from '../../../api/types';
const TOOLTIP_STYLE = {
background: 'var(--bg-card)',
border: '1px solid var(--border)',
borderRadius: 12,
color: 'var(--text)',
};
/**
* Panel wyników podopiecznego (tylko tryb podopiecznego): wykres 1RM per sesja,
* ostatnia sesja (serie powt. @ kg) i przycisk „Wstaw wyniki" (prefill serii).
*/
export function ExerciseResultsPanel({
latest,
points,
onPrefill,
}: {
latest: LatestExerciseResult | undefined;
points: ExerciseProgressPoint[];
onPrefill: () => void;
}) {
const oneRmPoints = points.filter((p) => p.oneRm != null);
if (!latest && oneRmPoints.length === 0) {
return <p className="mt-3 text-dim text-[0.875rem]">Brak wyników dla tego ćwiczenia.</p>;
}
return (
<div className="mt-3">
<div className="mb-2 flex items-center justify-between gap-2">
<span className="text-[11px] font-bold text-dim uppercase tracking-[0.1em]">
Wyniki podopiecznego
</span>
{latest && (
<Button variant="secondary" size="sm" onClick={onPrefill}>
Wstaw wyniki
</Button>
)}
</div>
{oneRmPoints.length >= 2 ? (
<ResponsiveContainer width="100%" height={140}>
<LineChart data={oneRmPoints.map((p) => ({ date: fmtDate(p.date), oneRm: p.oneRm }))}>
<CartesianGrid stroke="var(--border)" />
<XAxis dataKey="date" stroke="var(--text-dim)" />
<YAxis stroke="var(--text-dim)" domain={['auto', 'auto']} />
<Tooltip contentStyle={TOOLTIP_STYLE} />
<Line
type="monotone"
dataKey="oneRm"
name="1RM (kg)"
stroke="var(--accent)"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
) : (
<p className="text-dim text-[0.875rem]">Za mało danych na wykres 1RM (min. 2 sesje).</p>
)}
{latest && (
<div className="mt-2">
<div className="mb-1.5 text-[0.875rem]">
Ostatnia sesja: <strong>{fmtDate(latest.date)}</strong>
{latest.oneRm != null && <span className="text-dim"> · 1RM {latest.oneRm} kg</span>}
</div>
<div className="flex flex-wrap gap-1.5">
{latest.sets.map((s, i) => (
<span key={i} className="rounded-lg border border-line bg-input px-2 py-1 text-[0.875rem]">
{s.reps ?? '?'} powt.{s.loadKg != null ? ` @ ${s.loadKg} kg` : ''}
</span>
))}
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,57 @@
import { Card, Field, Input, Select, WeekPicker } from '../../../components/ui';
/* Meta planu: tytuł, długość, tydzień startu (+ hint) — siatka pól. */
export function PlanMetaForm({
title,
onTitleChange,
weeksCount,
onWeeksCountChange,
startDate,
onStartDateChange,
showStartWeek,
}: {
title: string;
onTitleChange: (v: string) => void;
weeksCount: number;
onWeeksCountChange: (n: number) => void;
startDate: string;
onStartDateChange: (v: string) => void;
showStartWeek: boolean;
}) {
return (
<Card>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<Field label="Tytuł">
<Input
value={title}
onChange={(e) => onTitleChange(e.target.value)}
placeholder="np. Plan masowy 8-tygodniowy"
/>
</Field>
<Field label="Długość (tygodnie)">
<Select value={weeksCount} onChange={(e) => onWeeksCountChange(parseInt(e.target.value))}>
{[1, 2, 3, 4, 5, 6, 7, 8].map((n) => (
<option key={n} value={n}>
{n}
</option>
))}
</Select>
</Field>
</div>
{showStartWeek && (
<div className="mt-4">
<Field label="Tydzień startu">
<WeekPicker value={startDate} onChange={onStartDateChange} />
</Field>
</div>
)}
{showStartWeek && (
<p className="mt-3 text-dim text-[0.875rem]">
Opcjonalnie zaznacz tydzień startu — plan zostanie od razu aktywowany (start = poniedziałek
zaznaczonego tygodnia), a daty dni treningowych wyliczone automatycznie. Bez tygodnia plan
pozostanie szkicem.
</p>
)}
</Card>
);
}

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