Admin: konsola sirowni od nowa - panel KPI, godziny i logi w ukladzie dwukolumnowym (LogTable + podstrona Logi), menu czlonka z rolami i wyrzuceniem z powodem, wyszukiwarka w kafelku, lista sirowni bez naglowka, usuwanie bytnosci/heatmapy (unit + e2e)

This commit is contained in:
tisachi
2026-10-29 21:21:03 +01:00
parent 2305649493
commit cc2f0f9166
26 changed files with 2781 additions and 2001 deletions

View File

@@ -0,0 +1,150 @@
import type { ActivityLog } from '../api/types';
import { Badge, type BadgeColor } from './ui';
import i18n from '../i18n';
import { fmtDate, fmtDateTime, fmtTime } from '../lib/format';
const t = (key: string, options?: Record<string, unknown>): string =>
String(i18n.t(`logs:${key}`, options as never));
export function actionLabel(action: string) {
return t(`actions.${action}`, { defaultValue: action });
}
export 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';
// akcje security konta — tak samo wyraźne jak relacje trenerskie
if (action.startsWith('user.')) return 'red';
if (action.startsWith('membership.')) return 'blue';
return 'yellow';
}
export function formatLogDate(iso: string) {
return fmtDateTime(iso);
}
export 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;
}
/** 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 linie: `start: 2026-08-24`, `wartość: 82.5 kg` — jedna pod drugą. */
export function detailsLines(log: ActivityLog): string[] {
const d = log.details;
if (!d) return [];
return Object.entries(d)
.filter(([k]) => !HIDDEN_DETAIL_KEYS.has(k))
.map(([k, v]) => `${t(`details.${k}`, { defaultValue: k })}: ${formatDetailValue(log, k, v)}`);
}
/** Szczegóły jako jeden tekst: `start: 2026-08-24 · wartość: 82.5 kg`. */
export function detailsText(log: ActivityLog) {
const parts = detailsLines(log);
return parts.length > 0 ? parts.join(' · ') : null;
}
/** Tabela logów aktywności (wspólny rendering: globalne logi i logi pojedynczej siłowni). */
export function LogTable({ logs }: { logs: ActivityLog[] }) {
return (
<div className="overflow-x-auto rounded-[10px] 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]">
{t('colDate')}
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
{t('colUser')}
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
{t('colAction')}
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
{t('colEntity')}
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
{t('colDetails')}
</th>
</tr>
</thead>
<tbody>
{logs.map((log) => (
<tr
key={log.id}
className="border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20"
>
<td className="px-4 py-3 align-top font-display text-dim tabular-nums">
<div className="whitespace-nowrap">{fmtDate(log.createdAt)}</div>
<div className="whitespace-nowrap text-[0.875rem]">{fmtTime(log.createdAt)}</div>
</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 align-top">
<Badge
color={actionColor(log.action)}
className="h-auto max-w-[13rem] whitespace-normal"
>
{actionLabel(log.action)}
</Badge>
</td>
<td className="px-4 py-3">
<div>{t(`entities.${log.entityType}`, { defaultValue: log.entityType })}</div>
{entityName(log) && (
<div className="text-[0.875rem] text-dim">{entityName(log)}</div>
)}
</td>
<td className="px-4 py-3 text-dim">
{detailsLines(log).length > 0 ? (
<div className="space-y-1">
{detailsLines(log).map((line) => (
<div key={line}>{line}</div>
))}
</div>
) : (
'—'
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}

View File

@@ -0,0 +1,111 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../../api/client';
import { Button, ErrorText, Field, Input, Loading, Muted, Textarea } from '../ui';
import type { AdminAnnouncement, Gym } from '../../api/types';
/** Awaryjne ogłoszenia w imieniu siłowni (gdy właściciel nie może sam). */
export function GymAnnouncementsSection({ gym }: { gym: Gym }) {
const { t } = useTranslation('gyms');
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ['admin-announcements', gym.id],
queryFn: () =>
api<{ announcements: AdminAnnouncement[] }>(
`/admin/announcements?gymId=${encodeURIComponent(gym.id)}`,
),
});
const announcements = data?.announcements ?? [];
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const add = async () => {
setBusy(true);
setError(null);
try {
await api('/admin/announcements', {
method: 'POST',
body: { title: title.trim(), body: body.trim(), gymId: gym.id },
});
setTitle('');
setBody('');
await queryClient.invalidateQueries({ queryKey: ['admin-announcements', gym.id] });
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
} finally {
setBusy(false);
}
};
const remove = async (id: string) => {
setError(null);
try {
await api(`/admin/announcements/${id}`, { method: 'DELETE' });
await queryClient.invalidateQueries({ queryKey: ['admin-announcements', gym.id] });
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
}
};
return (
<div>
<div className="flex flex-col gap-2.5 rounded-xl border border-line bg-input/40 p-3.5">
<Muted className="block">{t('announcementSendTo', { name: gym.name })}</Muted>
<Field label={t('announcementTitleLabel')}>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
maxLength={120}
placeholder={t('announcementTitlePh')}
/>
</Field>
<Field label={t('announcementBodyLabel')}>
<Textarea
value={body}
onChange={(e) => setBody(e.target.value)}
maxLength={2000}
rows={3}
placeholder={t('announcementBodyPh')}
/>
</Field>
{error && <ErrorText>{error}</ErrorText>}
<div>
<Button onClick={() => void add()} disabled={busy || !title.trim() || !body.trim()}>
{busy ? t('publishing') : t('publish')}
</Button>
</div>
</div>
<div className="mt-4">
{isLoading ? (
<Loading />
) : announcements.length === 0 ? (
<Muted className="block">{t('noAnnouncements')}</Muted>
) : (
<div className="flex flex-col gap-2">
{announcements.map((a) => (
<div key={a.id} className="rounded-[10px] border border-line bg-card/50 px-3 py-2.5">
<div className="flex items-center justify-between gap-3">
<span className="min-w-0 truncate text-[0.9rem] font-bold">{a.title}</span>
{a.kind === 'MANUAL' && (
<Button
variant="danger"
size="sm"
onClick={() => void remove(a.id)}
aria-label={t('removeAria', { name: a.title })}
>
{t('common:remove')}
</Button>
)}
</div>
<p className="mt-1 whitespace-pre-wrap text-dim text-[0.8125rem]">{a.body}</p>
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,299 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { Trash2 } from 'lucide-react';
import { api } from '../../api/client';
import type { Equipment, EquipmentSpec, Gym } from '../../api/types';
import {
EMPTY_SPEC_FIELDS,
LOAD_RANGE_KINDS,
MAX_LOAD_KINDS,
formatGymEquipment,
hasSpecFields,
specFromFields,
type SpecFields,
} from '../../lib/equipment';
import { localizedName } from '../../lib/localizedName';
import { Button, ErrorText, Field, Input, Loading, Select } from '../../components/ui';
/** Pola specyfikacji zależne od rodzaju urządzenia (wzorzec: katalog admina). */
function AddSpecFields({
kind,
values,
onChange,
}: {
kind: Equipment['kind'];
values: SpecFields;
onChange: (patch: Partial<SpecFields>) => void;
}) {
const { t } = useTranslation('gyms');
if (LOAD_RANGE_KINDS.includes(kind)) {
return (
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
<Field label={t('minLoad')}>
<Input
type="number"
min={0}
max={500}
step="any"
aria-label={t('minLoad')}
value={values.minKg}
onChange={(e) => onChange({ minKg: e.target.value })}
/>
</Field>
<Field label={t('maxLoad')}>
<Input
type="number"
min={0}
max={500}
step="any"
aria-label={t('maxLoad')}
value={values.maxKg}
onChange={(e) => onChange({ maxKg: e.target.value })}
/>
</Field>
</div>
);
}
if (MAX_LOAD_KINDS.includes(kind)) {
return (
<Field label={t('maxLoadFull')}>
<Input
type="number"
min={0}
max={1000}
step="any"
aria-label={t('maxLoadFull')}
value={values.maxLoadKg}
onChange={(e) => onChange({ maxLoadKg: e.target.value })}
/>
</Field>
);
}
if (kind === 'CARDIO') {
return (
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
<Field label={t('maxSpeed')}>
<Input
type="number"
min={0}
max={50}
step="any"
aria-label={t('maxSpeed')}
value={values.maxSpeedKmh}
onChange={(e) => onChange({ maxSpeedKmh: e.target.value })}
/>
</Field>
<Field label={t('maxIncline')}>
<Input
type="number"
min={0}
max={40}
step="any"
aria-label={t('maxIncline')}
value={values.maxInclinePct}
onChange={(e) => onChange({ maxInclinePct: e.target.value })}
/>
</Field>
</div>
);
}
return null;
}
export function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) {
const { t } = useTranslation('gyms');
const { i18n } = useTranslation();
const { data: eqData, isLoading } = useQuery({
queryKey: ['equipment'],
queryFn: () => api<{ equipment: Equipment[] }>('/admin/equipment'),
});
const catalog = eqData?.equipment ?? [];
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const [addId, setAddId] = useState('');
const [addQty, setAddQty] = useState('1');
const [addFields, setAddFields] = useState<SpecFields>(EMPTY_SPEC_FIELDS);
const addItem = catalog.find((e) => e.id === addId) ?? null;
// Parametry każdej pozycji admin wpisuje zawsze sam — bez podpowiedzi z katalogu.
const selectAdd = (id: string) => {
setAddId(id);
setAddFields(EMPTY_SPEC_FIELDS);
setError('');
};
const add = async () => {
if (!addItem) return;
const quantity = parseInt(addQty, 10) || 1;
setError('');
let spec: EquipmentSpec | null = null;
if (hasSpecFields(addItem.kind)) {
const result = specFromFields(addItem.kind, addFields);
if ('error' in result) {
setError(result.error);
return;
}
if (result.spec == null) {
setError(t('specRequired'));
return;
}
spec = result.spec;
}
setBusy(true);
try {
await api(`/admin/gyms/${gym.id}/equipment`, {
method: 'POST',
body: { equipmentId: addItem.id, quantity, ...(spec ? { spec } : {}) },
});
setAddId('');
setAddQty('1');
setAddFields(EMPTY_SPEC_FIELDS);
onChanged();
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
} finally {
setBusy(false);
}
};
const changeQty = async (instanceId: string, quantity: number) => {
try {
await api(`/admin/gyms/${gym.id}/equipment/${instanceId}`, {
method: 'PATCH',
body: { quantity },
});
onChanged();
} catch (err) {
alert(err instanceof Error ? err.message : t('common:error'));
}
};
const remove = async (instanceId: string) => {
try {
await api(`/admin/gyms/${gym.id}/equipment/${instanceId}`, { method: 'DELETE' });
onChanged();
} catch (err) {
alert(err instanceof Error ? err.message : t('common:error'));
}
};
const totalQty = (equipmentId: string) =>
gym.equipment
.filter((e) => e.equipmentId === equipmentId)
.reduce((sum, e) => sum + e.quantity, 0);
return (
<div className="space-y-5">
{/* POZYCJE NA STANIE: wiersz = nazwa/spec + ilość + usuwanie */}
<div>
<div className="mb-2 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
{t('positionsInStock', { count: gym.equipment.length })}
</div>
{gym.equipment.length === 0 ? (
<div className="rounded-[10px] border border-dashed border-line px-4 py-6 text-center text-[0.875rem] text-dim">
{t('noStockDesc')}
</div>
) : (
<div className="flex flex-col gap-2">
{gym.equipment.map((e) => (
<div
key={e.id}
className="flex items-center gap-2.5 rounded-[10px] border border-line bg-card/50 px-3 py-2"
>
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-semibold">
{formatGymEquipment(e, i18n.language)}
</span>
<input
type="number"
min={1}
max={10000}
defaultValue={e.quantity}
aria-label={t('qtyAria', { name: localizedName(e.equipment, i18n.language) })}
className="w-16 shrink-0 rounded-[10px] border border-line bg-input px-2 py-1 text-center text-[0.875rem] text-ink focus:border-accent-text focus:outline-none"
onBlur={(ev) => {
const value = parseInt(ev.target.value, 10);
if (Number.isFinite(value) && value >= 1 && value !== e.quantity) {
void changeQty(e.id, value);
} else {
ev.target.value = String(e.quantity);
}
}}
onKeyDown={(ev) => {
if (ev.key === 'Enter') (ev.target as HTMLInputElement).blur();
}}
/>
<button
type="button"
onClick={() => void remove(e.id)}
aria-label={t('removeAria', { name: localizedName(e.equipment, i18n.language) })}
title={t('removeAria', { name: localizedName(e.equipment, i18n.language) })}
className="shrink-0 cursor-pointer rounded-lg p-1.5 text-dim transition-colors hover:bg-danger/10 hover:text-danger"
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
</button>
</div>
))}
</div>
)}
</div>
{/* DODAWANIE z katalogu: pozycja zawsze z własnymi parametrami (zdjęcia pozycji zarządza właściciel w apce) */}
<div className="rounded-xl border border-line bg-input/40 p-3.5">
<div className="mb-2.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
{t('addFromCatalog')}
</div>
<div className="flex flex-wrap items-end gap-2.5">
<div className="min-w-0 flex-1 basis-52">
<Select
value={addId}
onChange={(e) => selectAdd(e.target.value)}
aria-label={t('addDeviceAria')}
>
<option value="">{t('chooseDevice')}</option>
{catalog.map((e) => {
const qty = totalQty(e.id);
return (
<option key={e.id} value={e.id}>
{localizedName(e, i18n.language)}
{qty > 0 ? ` ${t('inStockOption', { count: qty })}` : ''}
</option>
);
})}
</Select>
</div>
<Field label={t('qty')} className="w-20 shrink-0">
<Input
type="number"
size="sm"
min={1}
max={10000}
value={addQty}
onChange={(e) => setAddQty(e.target.value)}
aria-label={t('qty')}
/>
</Field>
<Button onClick={add} disabled={!addId || busy} className="shrink-0">
{busy ? t('adding') : t('add')}
</Button>
</div>
{addItem && hasSpecFields(addItem.kind) && (
<div className="mt-3.5 border-t border-line pt-3.5">
<div className="mb-2 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
{t('parameters')}
</div>
<AddSpecFields
kind={addItem.kind}
values={addFields}
onChange={(patch) => setAddFields({ ...addFields, ...patch })}
/>
</div>
)}
</div>
{error && <ErrorText>{error}</ErrorText>}
{isLoading && <Loading />}
</div>
);
}

View File

@@ -0,0 +1,192 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '../../api/client';
import { Button, ErrorText, Input, Loading, Select } from '../ui';
import { TIME_SLOTS } from '../../lib/availability';
import { fmtDate } from '../../lib/format';
import type { GymException } from '../../api/types';
/** Wyjątki (admin): komposer (data + tryb + godziny) — jak w apce. */
export function ExceptionsComposer({ gymId }: { gymId: string }) {
const { t } = useTranslation('gyms');
const queryClient = useQueryClient();
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 () => {
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 : t('common:error'));
} finally {
setBusy(false);
}
};
return (
<div className="rounded-xl border border-line bg-input/40 p-3.5">
<div className="mb-2.5 text-[11px] font-bold uppercase tracking-[0.1em] text-dim">
{t('addExceptionTitle')}
</div>
{/* wiersz 1: data + tryb; na wąskich ekranach każde przechodzi na pełną szerokość */}
<div className="flex flex-wrap gap-2.5">
<Input
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
aria-label={t('exceptionDateAria')}
className="w-full min-w-0 sm:w-44 sm:flex-none"
required
/>
<div className="flex h-10 w-full items-center gap-1 rounded-[10px] border border-line bg-card p-1 sm:w-auto">
<button
type="button"
aria-pressed={closed}
onClick={() => setClosed(true)}
className={`h-full flex-1 whitespace-nowrap rounded-[10px] px-3 text-[0.8125rem] font-semibold transition-colors sm:flex-none ${
closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
{t('closedBtn')}
</button>
<button
type="button"
aria-pressed={!closed}
onClick={() => setClosed(false)}
className={`h-full flex-1 whitespace-nowrap rounded-[10px] px-3 text-[0.8125rem] font-semibold transition-colors sm:flex-none ${
!closed ? 'bg-accent text-accent-ink' : 'text-dim hover:text-ink'
}`}
>
{t('otherHours')}
</button>
</div>
</div>
{/* wiersz 2: godziny + akcja; selecty dzielą miejsce po równo, nigdy się nie łamią */}
{!closed && (
<div className="mt-2.5 flex flex-wrap items-center gap-2.5">
<Select
value={start}
onChange={(e) => setStart(e.target.value)}
aria-label={t('fromHourAria')}
className="min-w-0 flex-1 sm:flex-none sm:basis-28"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
<Select
value={end}
onChange={(e) => setEnd(e.target.value)}
aria-label={t('toHourAria')}
className="min-w-0 flex-1 sm:flex-none sm:basis-28"
>
{TIME_SLOTS.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</Select>
<Button
type="button"
onClick={() => void add()}
disabled={busy || !date}
className="w-full sm:ml-auto sm:w-auto"
>
{busy ? t('adding') : t('add')}
</Button>
</div>
)}
{closed && (
<div className="mt-2.5">
<Button
type="button"
onClick={() => void add()}
disabled={busy || !date}
className="w-full sm:w-auto"
>
{busy ? t('adding') : t('add')}
</Button>
</div>
)}
{error && <ErrorText>{error}</ErrorText>}
</div>
);
}
/** Lista wyjątków z usuwaniem (admin może zarządzać każdym dniem). */
export function ExceptionsList({ gymId }: { gymId: string }) {
const { t } = useTranslation('gyms');
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ['gym-exceptions', gymId],
queryFn: () => api<{ exceptions: GymException[] }>(`/admin/gyms/${gymId}/exceptions`),
});
const exceptions = data?.exceptions ?? [];
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 : t('common:error'));
}
};
if (isLoading) return <Loading />;
if (exceptions.length === 0) {
return <p className="text-[0.875rem] text-dim">{t('noExceptions')}</p>;
}
return (
<div className="flex flex-col gap-2">
{exceptions.map((ex) => (
<div
key={ex.id}
className="flex items-center gap-3 rounded-[10px] border border-dashed border-danger/40 bg-danger/7 px-3 py-2"
>
<span className="font-display text-[0.85rem] font-bold tabular-nums">
{fmtDate(ex.date)}
</span>
<span className="min-w-0 flex-1 truncate text-dim text-[0.8125rem]">
{ex.availability ? `${ex.availability.start}–${ex.availability.end}` : t('closed')}
</span>
<Button variant="danger" size="sm" type="button" onClick={() => void remove(ex.id)}>
{t('common:remove')}
</Button>
</div>
))}
</div>
);
}
/** Komposer + lista istniejących wyjątków (modal „Informacje", jak w apce). */
export function ExceptionsEditor({ gymId }: { gymId: string }) {
const { data } = useQuery({
queryKey: ['gym-exceptions', gymId],
queryFn: () => api<{ exceptions: GymException[] }>(`/admin/gyms/${gymId}/exceptions`),
});
const has = (data?.exceptions ?? []).length > 0;
return (
<>
<ExceptionsComposer gymId={gymId} />
{has && (
<div className="mt-4">
<ExceptionsList gymId={gymId} />
</div>
)}
</>
);
}

View File

@@ -0,0 +1,135 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Image as ImageIcon, Star, X } from 'lucide-react';
import { api } from '../../api/client';
import { AuthImage } from '../AuthImage';
import { ErrorText, SectionHeader } from '../ui';
import type { Gym, GymPhoto } from '../../api/types';
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);
return api(`/gyms/${gymId}/photos`, { method: 'POST', body: form });
}
export function GallerySection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) {
const { t } = useTranslation('gyms');
const photos = gym.photos ?? [];
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
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(t('photoTypesError'));
return;
}
if (valid.length > MAX_PHOTO_FILES) {
setError(t('photoMaxFilesError', { count: MAX_PHOTO_FILES }));
return;
}
setError('');
setBusy(true);
try {
await uploadGymPhotos(gym.id, valid);
onChanged();
} catch (err) {
setError(err instanceof Error ? err.message : t('common:error'));
} finally {
setBusy(false);
}
};
const remove = async (photo: GymPhoto) => {
if (!confirm(t('confirmDeletePhoto'))) return;
try {
await api(`/gyms/${gym.id}/photos/${photo.id}`, { method: 'DELETE' });
onChanged();
} catch (err) {
alert(err instanceof Error ? err.message : t('common:error'));
}
};
const setCover = async (photo: GymPhoto) => {
try {
await api(`/gyms/${gym.id}/photos/${photo.id}/cover`, { method: 'PATCH' });
onChanged();
} catch (err) {
alert(err instanceof Error ? err.message : t('common:error'));
}
};
return (
<>
<SectionHeader title={t('gallerySection')} description={t('galleryDesc')} />
<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">{t('noPhotos')}</span>
)}
{photos.map((photo, i) => (
<div key={photo.id} className="relative overflow-hidden rounded-xl border border-line">
<AuthImage
src={photo.url}
alt={t('photoAlt', { n: 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">
{t('coverBadge')}
</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" />
{t('coverLabel')}
</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" />
{t('setCover')}
</button>
)}
<button
type="button"
onClick={() => remove(photo)}
aria-label={t('removePhotoAria')}
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">
<ImageIcon className="w-4 w-4" />
{busy ? t('uploading') : t('addPhotos')}
<input
type="file"
accept={PHOTO_MIME_TYPES.join(',')}
multiple
hidden
onChange={onPick}
disabled={busy}
/>
</label>
</div>
{error && <ErrorText>{error}</ErrorText>}
</>
);
}

View File

@@ -1,74 +0,0 @@
import { useTranslation } from 'react-i18next';
import { dayName } from '../../lib/format';
import { dayShort } from '../../lib/availability';
export interface PresenceHeatCell {
day: number;
hour: number;
count: number;
}
/* Mapa ciepła bytności 7 (dzień 0=pon) × 24 (godzina) — natężenie ~ udział w szczycie,
styl kafli jak mapa urządzeń. Lustrzana kopia komponentu z app (identyczny widok
w obu pakietach). Etykiety dni skrócone (pełna nazwa w tytulu wiersza), siatka
skaluje się do szerokosci kolumny — bez minimalnej szerokosci i przewijania. */
export function PresenceHeatmapGrid({ cells }: { cells: PresenceHeatCell[] }) {
const max = cells.reduce((m, c) => Math.max(m, c.count), 0);
return (
<div className="min-w-0">
<div
className="grid gap-[3px]"
style={{ gridTemplateColumns: 'minmax(2.4rem, 3.4rem) repeat(24, minmax(0, 1fr))' }}
>
<span />
{Array.from({ length: 24 }, (_, hour) => (
<span
key={hour}
className="min-w-0 truncate text-center text-[0.6rem] font-bold tabular-nums text-dim"
>
{hour % 3 === 0 ? String(hour).padStart(2, '0') : ''}
</span>
))}
{Array.from({ length: 7 }, (_, day) => (
<HeatmapRow key={day} day={day} cells={cells} max={max} />
))}
</div>
</div>
);
}
function HeatmapRow({ day, cells, max }: { day: number; cells: PresenceHeatCell[]; max: number }) {
const { t } = useTranslation('gyms');
return (
<>
<span
title={dayName(day + 1)}
className="flex min-w-0 items-center pr-1 text-[0.68rem] font-semibold text-dim"
>
<span className="truncate">{dayShort(day)}</span>
</span>
{Array.from({ length: 24 }, (_, hour) => {
const cell = cells.find((c) => c.day === day && c.hour === hour);
const count = cell?.count ?? 0;
const intensity = max > 0 ? count / max : 0;
return (
<span
key={hour}
title={t('stats.cellTitle', {
day: dayName(day + 1),
hour: String(hour).padStart(2, '0'),
count,
})}
className="aspect-square rounded-[2px] border border-line/40"
style={{
background:
intensity > 0
? `color-mix(in srgb, var(--accent) ${Math.round(18 + intensity * 82)}%, var(--bg-input))`
: 'var(--bg-input)',
}}
/>
);
})}
</>
);
}