Baseline: stan przed refaktoryzacja struktury

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

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

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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

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

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

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

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

View File

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

View File

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

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

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

View File

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

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

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

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

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

View File

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