Silownie: instancje wyposazenia z nadpisywanym spec i zdjeciami per instancja (koniec unikalnosci typu katalogowego; parametry i galeria zdjec na pozycji sprzetu, PATCH/DELETE po id instancji)
This commit is contained in:
@@ -100,13 +100,26 @@ export interface Equipment {
|
||||
gymsCount?: number;
|
||||
}
|
||||
|
||||
/** A gym's equipment instance: how many units of a catalog item the gym has. */
|
||||
/** Zdjęcie instancji urządzenia siłowni; `url` = ścieżka względna API. */
|
||||
export interface EquipmentPhoto {
|
||||
id: string;
|
||||
url: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A gym's equipment instance: a concrete set of units of a catalog type.
|
||||
* `spec` overrides the catalog spec; null = inherit it.
|
||||
*/
|
||||
export interface GymEquipment {
|
||||
id: string;
|
||||
gymId: string;
|
||||
equipmentId: string;
|
||||
quantity: number;
|
||||
spec: EquipmentSpec | null;
|
||||
equipment: Equipment;
|
||||
/** Zdjęcia (detal siłowni /admin/gyms/:id); listy mogą ich nie zawierać. */
|
||||
photos?: EquipmentPhoto[];
|
||||
}
|
||||
|
||||
export interface Exercise {
|
||||
|
||||
@@ -18,7 +18,7 @@ function fmtKg(value: number): string {
|
||||
|
||||
/**
|
||||
* Human-readable summary of a type-specific spec payload:
|
||||
* DUMBBELL/KETTLEBELL/CABLE/MACHINE → "2.5–25 kg"
|
||||
* DUMBBELL/KETTLEBELL/CABLE/MACHINE → "2.5–25 kg" ("5 kg" dla stałego ciężaru)
|
||||
* BARBELL/BENCH → "do 100 kg"
|
||||
* CARDIO → "do 16 km/h" (+ "nachylenie do 15%")
|
||||
* BODYWEIGHT/OTHER or no spec → null
|
||||
@@ -27,8 +27,13 @@ export function formatEquipmentSpec(spec: EquipmentSpec | null | undefined): str
|
||||
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`);
|
||||
if (spec.minKg != null && spec.maxKg != null) {
|
||||
parts.push(
|
||||
spec.minKg === spec.maxKg
|
||||
? `${fmtKg(spec.minKg)} kg`
|
||||
: `${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`);
|
||||
@@ -37,9 +42,95 @@ export function formatEquipmentSpec(spec: EquipmentSpec | null | undefined): str
|
||||
return parts.length ? parts.join(', ') : null;
|
||||
}
|
||||
|
||||
/** Kinds z zakresem obciążeń { minKg, maxKg }. */
|
||||
export const LOAD_RANGE_KINDS: EquipmentKind[] = ['DUMBBELL', 'KETTLEBELL', 'CABLE', 'MACHINE'];
|
||||
/** Kinds z maksymalnym obciążeniem { maxLoadKg }. */
|
||||
export const MAX_LOAD_KINDS: EquipmentKind[] = ['BARBELL', 'BENCH'];
|
||||
|
||||
/** Pola formularza spec (stringi = wartość inputa). */
|
||||
export interface SpecFields {
|
||||
minKg: string;
|
||||
maxKg: string;
|
||||
maxLoadKg: string;
|
||||
maxSpeedKmh: string;
|
||||
maxInclinePct: string;
|
||||
}
|
||||
|
||||
export const EMPTY_SPEC_FIELDS: SpecFields = {
|
||||
minKg: '',
|
||||
maxKg: '',
|
||||
maxLoadKg: '',
|
||||
maxSpeedKmh: '',
|
||||
maxInclinePct: '',
|
||||
};
|
||||
|
||||
export function specFieldsFrom(spec: EquipmentSpec | null | undefined): SpecFields {
|
||||
const s = spec ?? {};
|
||||
return {
|
||||
minKg: s.minKg != null ? String(s.minKg) : '',
|
||||
maxKg: s.maxKg != null ? String(s.maxKg) : '',
|
||||
maxLoadKg: s.maxLoadKg != null ? String(s.maxLoadKg) : '',
|
||||
maxSpeedKmh: s.maxSpeedKmh != null ? String(s.maxSpeedKmh) : '',
|
||||
maxInclinePct: s.maxInclinePct != null ? String(s.maxInclinePct) : '',
|
||||
};
|
||||
}
|
||||
|
||||
function parseNum(value: string): number | undefined {
|
||||
if (value.trim() === '') return undefined;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
}
|
||||
|
||||
/** Buduje payload spec z pól formularza wg rodzaju urządzenia; błąd = komunikat PL. */
|
||||
export function specFromFields(
|
||||
kind: EquipmentKind,
|
||||
f: SpecFields,
|
||||
): { spec: EquipmentSpec | null } | { error: string } {
|
||||
if (LOAD_RANGE_KINDS.includes(kind)) {
|
||||
const minKg = parseNum(f.minKg);
|
||||
const maxKg = parseNum(f.maxKg);
|
||||
if (minKg == null || maxKg == null) return { error: 'Podaj zakres obciążeń (min i max w kg).' };
|
||||
return { spec: { minKg, maxKg } };
|
||||
}
|
||||
if (MAX_LOAD_KINDS.includes(kind)) {
|
||||
const maxLoadKg = parseNum(f.maxLoadKg);
|
||||
if (maxLoadKg == null) return { error: 'Podaj maksymalne obciążenie (kg).' };
|
||||
return { spec: { maxLoadKg } };
|
||||
}
|
||||
if (kind === 'CARDIO') {
|
||||
const maxSpeedKmh = parseNum(f.maxSpeedKmh);
|
||||
const maxInclinePct = parseNum(f.maxInclinePct);
|
||||
if (maxSpeedKmh == null && maxInclinePct == null) return { spec: null };
|
||||
return {
|
||||
spec: {
|
||||
...(maxSpeedKmh != null ? { maxSpeedKmh } : {}),
|
||||
...(maxInclinePct != null ? { maxInclinePct } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
return { spec: null };
|
||||
}
|
||||
|
||||
/** Czy dla danego rodzaju formularz pokazuje jakiekolwiek pola spec. */
|
||||
export function hasSpecFields(kind: EquipmentKind): boolean {
|
||||
return LOAD_RANGE_KINDS.includes(kind) || MAX_LOAD_KINDS.includes(kind) || kind === 'CARDIO';
|
||||
}
|
||||
|
||||
/** Efektywny spec instancji: nadpisanie siłowni, inaczej spec z katalogu. */
|
||||
export function effectiveSpec(item: {
|
||||
spec?: EquipmentSpec | null;
|
||||
equipment: { spec: EquipmentSpec | null };
|
||||
}): EquipmentSpec | null {
|
||||
return item.spec ?? item.equipment.spec ?? 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);
|
||||
export function formatGymEquipment(item: {
|
||||
quantity: number;
|
||||
spec?: EquipmentSpec | null;
|
||||
equipment: Equipment;
|
||||
}): string {
|
||||
const spec = formatEquipmentSpec(effectiveSpec(item));
|
||||
const qty = item.quantity > 1 ? ` ×${item.quantity}` : '';
|
||||
return spec ? `${item.equipment.name}${qty} · ${spec}` : `${item.equipment.name}${qty}`;
|
||||
}
|
||||
|
||||
@@ -25,12 +25,23 @@ import { useAdminUsers } from '../users/user-queries';
|
||||
import type {
|
||||
AdminAnnouncement,
|
||||
Equipment,
|
||||
EquipmentSpec,
|
||||
Gym,
|
||||
GymException,
|
||||
GymOwner,
|
||||
GymPhoto,
|
||||
} from '../../api/types';
|
||||
import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment';
|
||||
import {
|
||||
EMPTY_SPEC_FIELDS,
|
||||
LOAD_RANGE_KINDS,
|
||||
MAX_LOAD_KINDS,
|
||||
formatEquipmentSpec,
|
||||
formatGymEquipment,
|
||||
hasSpecFields,
|
||||
specFieldsFrom,
|
||||
specFromFields,
|
||||
type SpecFields,
|
||||
} from '../../lib/equipment';
|
||||
import {
|
||||
BackButton,
|
||||
Button,
|
||||
@@ -918,39 +929,140 @@ function GymAnnouncementsSection({ gym }: { gym: Gym }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}) {
|
||||
if (LOAD_RANGE_KINDS.includes(kind)) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<Field label="Min. obciążenie (kg)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={500}
|
||||
step="any"
|
||||
aria-label="Min. obciążenie (kg)"
|
||||
value={values.minKg}
|
||||
onChange={(e) => onChange({ minKg: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Max. obciążenie (kg)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={500}
|
||||
step="any"
|
||||
aria-label="Max. obciążenie (kg)"
|
||||
value={values.maxKg}
|
||||
onChange={(e) => onChange({ maxKg: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (MAX_LOAD_KINDS.includes(kind)) {
|
||||
return (
|
||||
<Field label="Maksymalne obciążenie (kg)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={1000}
|
||||
step="any"
|
||||
aria-label="Maksymalne obciążenie (kg)"
|
||||
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="Maks. prędkość (km/h)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={50}
|
||||
step="any"
|
||||
aria-label="Maks. prędkość (km/h)"
|
||||
value={values.maxSpeedKmh}
|
||||
onChange={(e) => onChange({ maxSpeedKmh: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Maks. nachylenie (%)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={40}
|
||||
step="any"
|
||||
aria-label="Maks. nachylenie (%)"
|
||||
value={values.maxInclinePct}
|
||||
onChange={(e) => onChange({ maxInclinePct: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void }) {
|
||||
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 [addCustom, setAddCustom] = useState(false);
|
||||
const [addFields, setAddFields] = useState<SpecFields>(EMPTY_SPEC_FIELDS);
|
||||
|
||||
const addItem = catalog.find((e) => e.id === addId) ?? null;
|
||||
|
||||
const selectAdd = (id: string) => {
|
||||
setAddId(id);
|
||||
const item = catalog.find((e) => e.id === id);
|
||||
setAddFields(item ? specFieldsFrom(item.spec) : EMPTY_SPEC_FIELDS);
|
||||
setAddCustom(false);
|
||||
};
|
||||
|
||||
const add = async () => {
|
||||
if (!addId) return;
|
||||
if (!addItem) return;
|
||||
const quantity = parseInt(addQty, 10) || 1;
|
||||
setError('');
|
||||
let spec: EquipmentSpec | null = null;
|
||||
if (addCustom && hasSpecFields(addItem.kind)) {
|
||||
const result = specFromFields(addItem.kind, addFields);
|
||||
if ('error' in result) {
|
||||
setError(result.error);
|
||||
return;
|
||||
}
|
||||
if (result.spec == null) {
|
||||
setError('Uzupełnij parametry lub wyłącz ich własną wartość.');
|
||||
return;
|
||||
}
|
||||
spec = result.spec;
|
||||
}
|
||||
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 },
|
||||
});
|
||||
}
|
||||
await api(`/admin/gyms/${gym.id}/equipment`, {
|
||||
method: 'POST',
|
||||
body: { equipmentId: addItem.id, quantity, ...(spec ? { spec } : {}) },
|
||||
});
|
||||
setAddId('');
|
||||
setAddQty('1');
|
||||
setAddCustom(false);
|
||||
setAddFields(EMPTY_SPEC_FIELDS);
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Błąd');
|
||||
@@ -959,9 +1071,9 @@ function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void
|
||||
}
|
||||
};
|
||||
|
||||
const changeQty = async (equipmentId: string, quantity: number) => {
|
||||
const changeQty = async (instanceId: string, quantity: number) => {
|
||||
try {
|
||||
await api(`/admin/gyms/${gym.id}/equipment/${equipmentId}`, {
|
||||
await api(`/admin/gyms/${gym.id}/equipment/${instanceId}`, {
|
||||
method: 'PATCH',
|
||||
body: { quantity },
|
||||
});
|
||||
@@ -971,31 +1083,32 @@ function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (equipmentId: string) => {
|
||||
const remove = async (instanceId: string) => {
|
||||
try {
|
||||
await api(`/admin/gyms/${gym.id}/equipment/${equipmentId}`, { method: 'DELETE' });
|
||||
await api(`/admin/gyms/${gym.id}/equipment/${instanceId}`, { method: 'DELETE' });
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
alert(err instanceof Error ? err.message : 'Błąd');
|
||||
}
|
||||
};
|
||||
|
||||
const totalQty = (equipmentId: string) =>
|
||||
gym.equipment
|
||||
.filter((e) => e.equipmentId === equipmentId)
|
||||
.reduce((sum, e) => sum + e.quantity, 0);
|
||||
|
||||
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ść."
|
||||
description="Maszyny i urządzenia dostępne w tej siłowni (z katalogu). Każde dodanie tworzy osobną pozycję — możesz ustawić jej parametry (np. stały ciężar lub zakres regulacji)."
|
||||
/>
|
||||
<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}`}
|
||||
>
|
||||
<Chip key={e.id} onRemove={() => remove(e.id)} removeLabel={`Usuń ${e.equipment.name}`}>
|
||||
{formatGymEquipment(e)}
|
||||
<input
|
||||
type="number"
|
||||
@@ -1007,7 +1120,7 @@ function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void
|
||||
onBlur={(ev) => {
|
||||
const value = parseInt(ev.target.value, 10);
|
||||
if (Number.isFinite(value) && value >= 1 && value !== e.quantity) {
|
||||
void changeQty(e.equipmentId, value);
|
||||
void changeQty(e.id, value);
|
||||
} else {
|
||||
ev.target.value = String(e.quantity);
|
||||
}
|
||||
@@ -1022,19 +1135,19 @@ function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
<Select
|
||||
value={addId}
|
||||
onChange={(e) => setAddId(e.target.value)}
|
||||
onChange={(e) => selectAdd(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 qty = totalQty(e.id);
|
||||
const spec = formatEquipmentSpec(e.spec);
|
||||
return (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
{spec ? ` · ${spec}` : ''}
|
||||
{qty != null ? ` (${qty} szt.)` : ''}
|
||||
{qty > 0 ? ` (${qty} szt.)` : ''}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
@@ -1052,6 +1165,26 @@ function EquipmentSection({ gym, onChanged }: { gym: Gym; onChanged: () => void
|
||||
{busy ? 'Dodawanie…' : 'Dodaj'}
|
||||
</Button>
|
||||
</div>
|
||||
{addItem && hasSpecFields(addItem.kind) && (
|
||||
<div className="mt-3">
|
||||
<label className="mb-2 flex cursor-pointer items-center gap-2 text-[0.875rem]">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={addCustom}
|
||||
onChange={(e) => setAddCustom(e.target.checked)}
|
||||
className="h-4 w-4 accent-accent"
|
||||
/>
|
||||
Ustaw własne parametry (domyślne: {formatEquipmentSpec(addItem.spec) ?? 'brak'})
|
||||
</label>
|
||||
{addCustom && (
|
||||
<AddSpecFields
|
||||
kind={addItem.kind}
|
||||
values={addFields}
|
||||
onChange={(patch) => setAddFields({ ...addFields, ...patch })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
{isLoading && <Loading />}
|
||||
</>
|
||||
|
||||
@@ -83,7 +83,13 @@ function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) {
|
||||
if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] });
|
||||
if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] });
|
||||
if (url.includes('/admin/users')) return jsonResponse(200, { users: [U1] });
|
||||
if (url.includes('/admin/gyms/g1/equipment/eq-2') && method === 'PATCH') {
|
||||
if (url.endsWith('/admin/gyms/g1/equipment') && method === 'POST') {
|
||||
return jsonResponse(200, {
|
||||
gym: G1_EQ,
|
||||
instance: { id: 'ge-9', gymId: 'g1', equipmentId: 'eq-2', quantity: 1, spec: null },
|
||||
});
|
||||
}
|
||||
if (url.includes('/admin/gyms/g1/equipment/ge-2') && method === 'PATCH') {
|
||||
return jsonResponse(200, { gym: G1_EQ });
|
||||
}
|
||||
if (url.includes('/admin/gyms/g1/owners') && method === 'POST') {
|
||||
@@ -169,14 +175,16 @@ describe('admin GymDetail page', () => {
|
||||
});
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Dodaj urządzenie' }));
|
||||
|
||||
// każde dodanie = POST tworzący NOWĄ instancję (bez PATCH-a ilości istniejącej)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
calls.find((c) => c.method === 'PATCH' && c.url.includes('/equipment/eq-2')),
|
||||
calls.find((c) => c.method === 'POST' && c.url.endsWith('/admin/gyms/g1/equipment')),
|
||||
).toBeTruthy(),
|
||||
);
|
||||
expect(
|
||||
calls.find((c) => c.method === 'PATCH' && c.url.includes('/equipment/eq-2'))?.body,
|
||||
).toEqual({ quantity: 3 });
|
||||
calls.find((c) => c.method === 'POST' && c.url.endsWith('/admin/gyms/g1/equipment'))?.body,
|
||||
).toEqual({ equipmentId: 'eq-2', quantity: 1 });
|
||||
expect(calls.some((c) => c.method === 'PATCH')).toBe(false);
|
||||
});
|
||||
|
||||
it('grants and revokes gym owners via admin-only owner endpoints', async () => {
|
||||
|
||||
@@ -29,7 +29,9 @@ test('kliknięcie w siłownię otwiera podstronę z detalami', async ({ page })
|
||||
await expect(page.getByRole('button', { name: 'Dodawanie' })).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('dodawanie już dodanego sprzętu zwiększa jego ilość', async ({ page }) => {
|
||||
test('ponowne dodanie tego samego typu tworzy osobną instancję (bez inkrementacji ilości)', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
@@ -38,10 +40,37 @@ test('dodawanie już dodanego sprzętu zwiększa jego ilość', async ({ page })
|
||||
|
||||
// zarządzanie urządzeniami w modalu z grupy „Urządzenia" menu kontekstowego
|
||||
await page.locator('button[data-slot="button"]', { hasText: 'Urządzenia' }).click();
|
||||
const addReq = page.waitForRequest(
|
||||
(req) => req.url().endsWith('/admin/gyms/gym-1/equipment') && req.method() === 'POST',
|
||||
);
|
||||
await page.getByRole('combobox', { name: 'Dodaj urządzenie' }).selectOption('eq-2');
|
||||
await page.getByRole('button', { name: 'Dodaj urządzenie' }).click();
|
||||
// ilość widoczna zarówno w modalu, jak i na kafelkach urządzenia pod spodem
|
||||
await expect(page.getByText('Dywan ×4').first()).toBeVisible();
|
||||
expect((await addReq).postDataJSON()).toMatchObject({ equipmentId: 'eq-2', quantity: 1 });
|
||||
|
||||
// dotychczasowa instancja bez zmian, nowa instancja to osobny chip (×1 = bez licznika)
|
||||
await expect(page.getByText('Dywan ×4')).toHaveCount(0);
|
||||
await expect(page.getByText('Dywan ×3').first()).toBeVisible();
|
||||
await expect(page.getByText('Dywan', { exact: true })).toHaveCount(2);
|
||||
});
|
||||
|
||||
test('dodanie urządzenia z własnymi parametrami wysyła spec w POST', async ({ page }) => {
|
||||
mockApi(page, { gyms: { gyms: [TEST_GYM] } });
|
||||
await loginAsAdmin(page);
|
||||
await page.getByRole('link', { name: 'Fit Factory' }).click();
|
||||
await page.locator('button[data-slot="button"]', { hasText: 'Urządzenia' }).click();
|
||||
|
||||
const addReq = page.waitForRequest(
|
||||
(req) => req.url().endsWith('/admin/gyms/gym-1/equipment') && req.method() === 'POST',
|
||||
);
|
||||
await page.getByRole('combobox', { name: 'Dodaj urządzenie' }).selectOption('eq-1');
|
||||
await page.getByRole('checkbox', { name: /Ustaw własne parametry/ }).check();
|
||||
await page.getByLabel('Maksymalne obciążenie (kg)').fill('80');
|
||||
await page.getByRole('button', { name: 'Dodaj urządzenie' }).click();
|
||||
expect((await addReq).postDataJSON()).toEqual({
|
||||
equipmentId: 'eq-1',
|
||||
quantity: 1,
|
||||
spec: { maxLoadKg: 80 },
|
||||
});
|
||||
});
|
||||
|
||||
test('admin zarządza właścicielami siłowni z menu kontekstowego', async ({ page }) => {
|
||||
|
||||
@@ -373,8 +373,13 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
}),
|
||||
);
|
||||
|
||||
// Stateful: quantities of TEST_GYM equipment persist across refetches (PATCH/DELETE).
|
||||
const gymEquipmentState = TEST_GYM.equipment.map((e) => ({ ...e }));
|
||||
// Stateful: instancje wyposażenia TEST_GYM (POST/PATCH/DELETE trwają do odświeżenia).
|
||||
const gymEquipmentState = TEST_GYM.equipment.map((e) => ({
|
||||
...e,
|
||||
spec: null,
|
||||
photos: [] as { id: string; url: string; createdAt: string }[],
|
||||
}));
|
||||
let eqInstanceSeq = gymEquipmentState.length;
|
||||
|
||||
// Stateful: galeria zdjęć siłowni REAL (gym-1) — upload/delete/cover.
|
||||
const gymPhotosState = TEST_GYM_PHOTOS.map((p) => ({ ...p }));
|
||||
@@ -462,13 +467,46 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
});
|
||||
});
|
||||
|
||||
// POST = zawsze NOWA instancja; PATCH/DELETE po id instancji (GymEquipment.id).
|
||||
page.route('**/api/v1/admin/gyms/*/equipment', (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const body = JSON.parse(req.postData() || '{}');
|
||||
const item = TEST_EQUIPMENT.find((e) => e.id === body.equipmentId);
|
||||
if (item) {
|
||||
eqInstanceSeq += 1;
|
||||
const instance = {
|
||||
id: `ge-${eqInstanceSeq}`,
|
||||
gymId: TEST_GYM.id,
|
||||
equipmentId: item.id,
|
||||
quantity: typeof body.quantity === 'number' ? body.quantity : 1,
|
||||
spec: body.spec ?? null,
|
||||
photos: [],
|
||||
equipment: item,
|
||||
};
|
||||
gymEquipmentState.push(instance);
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ gym: { ...TEST_GYM, equipment: gymEquipmentState }, instance }),
|
||||
});
|
||||
}
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ gym: { ...TEST_GYM, equipment: gymEquipmentState } }),
|
||||
});
|
||||
});
|
||||
|
||||
page.route('**/api/v1/admin/gyms/*/equipment/*', (route) => {
|
||||
const req = route.request();
|
||||
const eqId = req.url().match(/equipment\/([^/]+)$/)?.[1];
|
||||
const instanceId = req.url().match(/equipment\/([^/]+)$/)?.[1];
|
||||
if (req.method() === 'PATCH') {
|
||||
const body = JSON.parse(req.postData() || '{}');
|
||||
const link = gymEquipmentState.find((e) => e.equipmentId === eqId);
|
||||
const link = gymEquipmentState.find((e) => e.id === instanceId);
|
||||
if (link && typeof body.quantity === 'number') link.quantity = body.quantity;
|
||||
if (link && 'spec' in body) link.spec = body.spec ?? null;
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
@@ -476,7 +514,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
});
|
||||
}
|
||||
if (req.method() === 'DELETE') {
|
||||
const idx = gymEquipmentState.findIndex((e) => e.equipmentId === eqId);
|
||||
const idx = gymEquipmentState.findIndex((e) => e.id === instanceId);
|
||||
if (idx >= 0) gymEquipmentState.splice(idx, 1);
|
||||
return route.fulfill({ status: 204 });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
-- DropIndex
|
||||
DROP INDEX "GymEquipment_gymId_equipmentId_key";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "GymEquipment" ADD COLUMN "spec" JSONB;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "EquipmentPhoto" (
|
||||
"id" TEXT NOT NULL,
|
||||
"gymEquipmentId" TEXT NOT NULL,
|
||||
"storedName" TEXT NOT NULL,
|
||||
"mimeType" TEXT NOT NULL,
|
||||
"sizeBytes" INTEGER NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "EquipmentPhoto_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "EquipmentPhoto_gymEquipmentId_createdAt_idx" ON "EquipmentPhoto"("gymEquipmentId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "GymEquipment_gymId_equipmentId_idx" ON "GymEquipment"("gymId", "equipmentId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EquipmentPhoto" ADD CONSTRAINT "EquipmentPhoto_gymEquipmentId_fkey" FOREIGN KEY ("gymEquipmentId") REFERENCES "GymEquipment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -431,18 +431,36 @@ model GymInvitation {
|
||||
@@index([invitedById, status])
|
||||
}
|
||||
|
||||
/// Gym ↔ equipment instance: how many units of a catalog item a gym has
|
||||
/// (e.g. two pairs of dumbbells).
|
||||
/// Gym ↔ equipment instance: a concrete set of units of a catalog type the gym owns
|
||||
/// (e.g. four fixed 5 kg dumbbells AND two adjustable 2–24 kg dumbbells = two instances).
|
||||
/// `spec` overrides the catalog spec for this instance (validated against the catalog
|
||||
/// item's `kind`); null = inherit the catalog spec.
|
||||
model GymEquipment {
|
||||
id String @id @default(cuid())
|
||||
gymId String
|
||||
equipmentId String
|
||||
quantity Int @default(1)
|
||||
spec Json?
|
||||
|
||||
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
|
||||
equipment Equipment @relation(fields: [equipmentId], references: [id], onDelete: Cascade)
|
||||
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
|
||||
equipment Equipment @relation(fields: [equipmentId], references: [id], onDelete: Cascade)
|
||||
photos EquipmentPhoto[]
|
||||
|
||||
@@unique([gymId, equipmentId])
|
||||
@@index([gymId, equipmentId])
|
||||
}
|
||||
|
||||
/// Photo of a gym's equipment instance (stored under UPLOAD_DIR/gyms/<gymId>/equipment/<instanceId>/).
|
||||
model EquipmentPhoto {
|
||||
id String @id @default(cuid())
|
||||
gymEquipmentId String
|
||||
storedName String
|
||||
mimeType String
|
||||
sizeBytes Int
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
gymEquipment GymEquipment @relation(fields: [gymEquipmentId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([gymEquipmentId, createdAt])
|
||||
}
|
||||
|
||||
/// One-off override for a specific date (null = closed, { start, end } = different hours).
|
||||
|
||||
@@ -16,6 +16,8 @@ export const MAX_PHOTO_FILES = 10;
|
||||
export const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024;
|
||||
/** Max photos per gym (total, across uploads). */
|
||||
export const MAX_GYM_PHOTOS = 20;
|
||||
/** Max photos per gym equipment instance. */
|
||||
export const MAX_EQUIPMENT_PHOTOS = 5;
|
||||
|
||||
const EXT_BY_MIME: Record<string, string> = {
|
||||
'image/jpeg': '.jpg',
|
||||
@@ -88,6 +90,61 @@ export const gymPhotoUpload = multer({
|
||||
},
|
||||
});
|
||||
|
||||
/** Katalog zdjęć instancji urządzenia: pod drzewem siłowni (cleanup przy usuwaniu siłowni). */
|
||||
export function equipmentPhotoDir(gymId: string, gymEquipmentId: string): string {
|
||||
return path.join(config.uploadDir, 'gyms', gymId, 'equipment', gymEquipmentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Multer for equipment instance photos: files land in a temp dir first; the
|
||||
* service moves them into UPLOAD_DIR/gyms/<gymId>/equipment/<instanceId>/.
|
||||
*/
|
||||
export const equipmentPhotoUpload = multer({
|
||||
storage: multer.diskStorage({
|
||||
destination: (_req, _file, cb) => {
|
||||
try {
|
||||
fs.mkdirSync(tmpDir, { recursive: true });
|
||||
cb(null, tmpDir);
|
||||
} catch (e) {
|
||||
cb(e as Error, tmpDir);
|
||||
}
|
||||
},
|
||||
filename: (_req, file, cb) => {
|
||||
cb(null, storedFileName(file.mimetype));
|
||||
},
|
||||
}),
|
||||
limits: { fileSize: MAX_PHOTO_FILE_SIZE, files: MAX_EQUIPMENT_PHOTOS },
|
||||
fileFilter: (_req, file, cb) => {
|
||||
if ((PHOTO_MIME_TYPES as readonly string[]).includes(file.mimetype)) cb(null, true);
|
||||
else cb(new Error(`Unsupported file type: ${file.mimetype}`));
|
||||
},
|
||||
});
|
||||
|
||||
/** Remove one equipment photo file (best-effort — errors are logged only). */
|
||||
export function removeEquipmentPhotoFile(
|
||||
gymId: string,
|
||||
gymEquipmentId: string,
|
||||
storedName: string,
|
||||
): void {
|
||||
try {
|
||||
fs.rmSync(path.join(equipmentPhotoDir(gymId, gymEquipmentId), storedName), { force: true });
|
||||
} catch (e) {
|
||||
logger.warn(
|
||||
{ err: e, gymId, gymEquipmentId, storedName },
|
||||
'Failed to remove equipment photo file',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove all photos of an equipment instance (best-effort — errors are logged only). */
|
||||
export function removeEquipmentPhotoFiles(gymId: string, gymEquipmentId: string): void {
|
||||
try {
|
||||
fs.rmSync(equipmentPhotoDir(gymId, gymEquipmentId), { recursive: true, force: true });
|
||||
} catch (e) {
|
||||
logger.warn({ err: e, gymId, gymEquipmentId }, 'Failed to remove equipment photo files');
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove one gym photo file (best-effort — errors are logged only). */
|
||||
export function removeGymPhotoFile(gymId: string, storedName: string): void {
|
||||
try {
|
||||
|
||||
@@ -42,7 +42,7 @@ import {
|
||||
removeGymOwner,
|
||||
removeMembership,
|
||||
updateGym,
|
||||
updateGymEquipmentQuantity,
|
||||
updateGymEquipment,
|
||||
updateMembership,
|
||||
updateUser,
|
||||
} from '../services/admin.js';
|
||||
@@ -361,54 +361,57 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
const gymEquipmentSchema = z.object({
|
||||
equipmentId: z.string().min(1),
|
||||
quantity: z.number().int().min(1).max(10000).optional(),
|
||||
spec: z.unknown().optional(),
|
||||
});
|
||||
|
||||
const gymEquipmentQuantitySchema = z.object({
|
||||
quantity: z.number().int().min(1).max(10000),
|
||||
const gymEquipmentInstanceSchema = z.object({
|
||||
quantity: z.number().int().min(1).max(10000).optional(),
|
||||
spec: z.unknown().optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /admin/gyms/{id}/equipment:
|
||||
* post:
|
||||
* summary: Add a catalog equipment item to a gym with a quantity (admin)
|
||||
* summary: Create an equipment instance in a gym (admin); repeats of a catalog type are new instances
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 200: { description: OK, returns { gym, instance } }
|
||||
* 400: { description: Invalid spec for the catalog kind }
|
||||
* 404: { description: Gym or equipment not found }
|
||||
* 409: { description: Equipment already exists (update its quantity instead) }
|
||||
*/
|
||||
router.post(
|
||||
'/gyms/:id/equipment',
|
||||
validate(gymEquipmentSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { equipmentId, quantity } = req.body as z.infer<typeof gymEquipmentSchema>;
|
||||
const result = await addGymEquipment(prisma, req.params.id, equipmentId, quantity ?? 1);
|
||||
const { equipmentId, quantity, spec } = req.body as z.infer<typeof gymEquipmentSchema>;
|
||||
const result = await addGymEquipment(prisma, req.params.id, equipmentId, quantity ?? 1, spec);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /admin/gyms/{id}/equipment/{equipmentId}:
|
||||
* /admin/gyms/{id}/equipment/{instanceId}:
|
||||
* patch:
|
||||
* summary: Change the quantity of a gym's equipment item (admin)
|
||||
* summary: Change quantity and/or spec override of an equipment instance (admin); spec:null clears the override
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 400: { description: Equipment not in gym }
|
||||
* 400: { description: Equipment not in gym or invalid spec }
|
||||
* 404: { description: Gym not found }
|
||||
*/
|
||||
router.patch(
|
||||
'/gyms/:id/equipment/:equipmentId',
|
||||
validate(gymEquipmentQuantitySchema),
|
||||
'/gyms/:id/equipment/:instanceId',
|
||||
validate(gymEquipmentInstanceSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { quantity } = req.body as z.infer<typeof gymEquipmentQuantitySchema>;
|
||||
const result = await updateGymEquipmentQuantity(
|
||||
const body = req.body as z.infer<typeof gymEquipmentInstanceSchema>;
|
||||
const result = await updateGymEquipment(
|
||||
prisma,
|
||||
req.params.id,
|
||||
req.params.equipmentId,
|
||||
quantity,
|
||||
req.params.instanceId,
|
||||
body,
|
||||
Object.hasOwn(body, 'spec'),
|
||||
);
|
||||
res.json(result);
|
||||
}),
|
||||
@@ -416,9 +419,9 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /admin/gyms/{id}/equipment/{equipmentId}:
|
||||
* /admin/gyms/{id}/equipment/{instanceId}:
|
||||
* delete:
|
||||
* summary: Remove a catalog equipment item from a gym (admin)
|
||||
* summary: Remove an equipment instance (and its photos) from a gym (admin)
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 204: { description: Removed }
|
||||
@@ -426,9 +429,9 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* 404: { description: Gym not found }
|
||||
*/
|
||||
router.delete(
|
||||
'/gyms/:id/equipment/:equipmentId',
|
||||
'/gyms/:id/equipment/:instanceId',
|
||||
asyncHandler(async (req, res) => {
|
||||
await removeGymEquipment(prisma, req.params.id, req.params.equipmentId);
|
||||
await removeGymEquipment(prisma, req.params.id, req.params.instanceId);
|
||||
res.status(204).end();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -20,6 +20,7 @@ import { createGymSchema, rateGymSchema, updateGymSchema } from './gyms/schemas.
|
||||
import { createGymClaimRoutes } from './gyms/claims.js';
|
||||
import { createGymInvitationRoutes } from './gyms/invitations.js';
|
||||
import { createGymPhotoRoutes } from './gyms/photos.js';
|
||||
import { createEquipmentPhotoRoutes } from './gyms/equipmentPhotos.js';
|
||||
import { createGymManagementRoutes } from './gyms/management.js';
|
||||
|
||||
export function createGymRoutes(deps: AppDeps) {
|
||||
@@ -110,8 +111,9 @@ export function createGymRoutes(deps: AppDeps) {
|
||||
}),
|
||||
);
|
||||
|
||||
// Per-gym sub-routes: gallery photos, then equipment/exceptions.
|
||||
// Per-gym sub-routes: gallery photos, equipment instance photos, then equipment/exceptions.
|
||||
router.use('/:gymId/photos', createGymPhotoRoutes(deps));
|
||||
router.use('/:gymId/equipment/:equipmentInstanceId/photos', createEquipmentPhotoRoutes(deps));
|
||||
router.use('/:gymId', createGymManagementRoutes(deps));
|
||||
|
||||
/**
|
||||
|
||||
156
api/src/routes/gyms/equipmentPhotos.ts
Normal file
156
api/src/routes/gyms/equipmentPhotos.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Router } from 'express';
|
||||
import type { AppDeps } from '../../deps.js';
|
||||
import { addEquipmentPhotos, canManageGym, deleteEquipmentPhoto } from '../../services/gyms.js';
|
||||
import { logActivity } from '../../services/audit.js';
|
||||
import {
|
||||
MAX_EQUIPMENT_PHOTOS,
|
||||
equipmentPhotoDir,
|
||||
equipmentPhotoUpload,
|
||||
removeTmpFiles,
|
||||
} from '../../lib/uploads.js';
|
||||
import { badRequest, forbidden, notFound } from '../../lib/errors.js';
|
||||
import { asyncHandler } from '../../lib/asyncHandler.js';
|
||||
|
||||
type Params = { gymId: string; equipmentInstanceId: string };
|
||||
|
||||
/** Mounted at /gyms/:gymId/equipment/:equipmentInstanceId/photos (mergeParams). */
|
||||
export function createEquipmentPhotoRoutes({ prisma }: AppDeps) {
|
||||
const router = Router({ mergeParams: true });
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{id}/photos:
|
||||
* post:
|
||||
* summary: Add photos to an equipment instance (owner or admin; multipart field `photos`, max 5)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 400: { description: Validation failed (file type/size/count or photo limit) }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Equipment instance not found }
|
||||
*/
|
||||
router.post(
|
||||
'/',
|
||||
(req, res, next) =>
|
||||
equipmentPhotoUpload.array('photos', MAX_EQUIPMENT_PHOTOS)(req, res, (err) => {
|
||||
if (err) {
|
||||
// część plików mogła już trafić do tmp (np. LIMIT_FILE_SIZE w połowie)
|
||||
removeTmpFiles(
|
||||
((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })),
|
||||
);
|
||||
const message =
|
||||
err.code === 'LIMIT_FILE_SIZE'
|
||||
? 'File too large (max 5 MB)'
|
||||
: err.code === 'LIMIT_FILE_COUNT'
|
||||
? `Too many files (max ${MAX_EQUIPMENT_PHOTOS})`
|
||||
: err.message;
|
||||
return next(badRequest(message));
|
||||
}
|
||||
next();
|
||||
}),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { gymId, equipmentInstanceId } = req.params as Params;
|
||||
try {
|
||||
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
|
||||
mimeType: f.mimetype,
|
||||
sizeBytes: f.size,
|
||||
path: f.path,
|
||||
}));
|
||||
const result = await addEquipmentPhotos(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
gymId,
|
||||
equipmentInstanceId,
|
||||
files,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.equipment.photos.added',
|
||||
entityType: 'gym',
|
||||
entityId: gymId,
|
||||
details: { instanceId: equipmentInstanceId, count: files.length },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
removeTmpFiles(
|
||||
((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })),
|
||||
);
|
||||
throw e;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{id}/photos/{photoId}:
|
||||
* delete:
|
||||
* summary: Remove a photo from an equipment instance (owner or admin)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Photo not found }
|
||||
*/
|
||||
router.delete(
|
||||
'/:photoId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { gymId, equipmentInstanceId } = req.params as Params;
|
||||
const { photoId } = req.params as { photoId: string };
|
||||
const result = await deleteEquipmentPhoto(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
gymId,
|
||||
equipmentInstanceId,
|
||||
photoId,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.equipment.photo.deleted',
|
||||
entityType: 'gym',
|
||||
entityId: gymId,
|
||||
details: { instanceId: equipmentInstanceId, photoId },
|
||||
});
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{id}/photos/{photoId}:
|
||||
* get:
|
||||
* summary: Serve an equipment photo (REAL visible to all logged-in users; VIRTUAL to managers)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: Image bytes with the stored Content-Type }
|
||||
* 403: { description: VIRTUAL gym and the caller is not a manager }
|
||||
* 404: { description: Photo not found or file missing }
|
||||
*/
|
||||
router.get(
|
||||
'/:photoId',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { gymId, equipmentInstanceId } = req.params as Params;
|
||||
const { photoId } = req.params as { photoId: string };
|
||||
const photo = await prisma.equipmentPhoto.findUnique({ where: { id: photoId } });
|
||||
if (!photo || photo.gymEquipmentId !== equipmentInstanceId) throw notFound('Photo not found');
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (
|
||||
gym.kind !== 'REAL' &&
|
||||
!(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin))
|
||||
)
|
||||
throw forbidden('You do not have access to this gym');
|
||||
const filePath = path.join(equipmentPhotoDir(gymId, equipmentInstanceId), photo.storedName);
|
||||
if (!fs.existsSync(filePath)) throw notFound('Photo file not found');
|
||||
res.type(photo.mimeType);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
res.sendFile(filePath, (err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
deleteOwnedGymException,
|
||||
listOwnedGymExceptions,
|
||||
removeEquipment,
|
||||
updateEquipmentQuantity,
|
||||
updateEquipment,
|
||||
} from '../../services/gyms.js';
|
||||
import {
|
||||
createGymAnnouncement,
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from '../../services/announcements.js';
|
||||
import {
|
||||
announcementSchema,
|
||||
equipmentQuantitySchema,
|
||||
equipmentInstanceSchema,
|
||||
equipmentSchema,
|
||||
gymExceptionSchema,
|
||||
} from './schemas.js';
|
||||
@@ -34,48 +34,27 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment:
|
||||
* post:
|
||||
* summary: Add a catalog equipment item to a gym with a quantity (owner only)
|
||||
* summary: Create an equipment instance in a gym (owner only); repeats of a catalog type are new instances
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 200: { description: OK, returns { gym, instance } }
|
||||
* 400: { description: Invalid spec for the catalog kind }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Equipment not found }
|
||||
* 409: { description: Equipment already exists (update its quantity instead) }
|
||||
*/
|
||||
router.post(
|
||||
'/equipment',
|
||||
validate(equipmentSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { equipmentId, quantity } = req.body as z.infer<typeof equipmentSchema>;
|
||||
const { equipmentId, quantity, spec } = req.body as z.infer<typeof equipmentSchema>;
|
||||
const { gymId } = req.params as GymParams;
|
||||
const result = await addEquipment(prisma, gymId, req.user!.id, equipmentId, quantity ?? 1);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{equipmentId}:
|
||||
* patch:
|
||||
* summary: Change the quantity of a gym's equipment item (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 400: { description: Equipment not in the gym }
|
||||
*/
|
||||
router.patch(
|
||||
'/equipment/:equipmentId',
|
||||
validate(equipmentQuantitySchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { quantity } = req.body as z.infer<typeof equipmentQuantitySchema>;
|
||||
const { gymId } = req.params as GymParams;
|
||||
const result = await updateEquipmentQuantity(
|
||||
const result = await addEquipment(
|
||||
prisma,
|
||||
gymId,
|
||||
req.user!.id,
|
||||
req.params.equipmentId,
|
||||
quantity,
|
||||
equipmentId,
|
||||
quantity ?? 1,
|
||||
spec,
|
||||
);
|
||||
res.json(result);
|
||||
}),
|
||||
@@ -83,19 +62,49 @@ export function createGymManagementRoutes({ prisma }: AppDeps) {
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{equipmentId}:
|
||||
* /gyms/{gymId}/equipment/{id}:
|
||||
* patch:
|
||||
* summary: Change quantity and/or spec override of an equipment instance (owner only); spec:null clears the override
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 400: { description: Equipment not in the gym or invalid spec }
|
||||
* 403: { description: Not the gym owner }
|
||||
*/
|
||||
router.patch(
|
||||
'/equipment/:id',
|
||||
validate(equipmentInstanceSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const body = req.body as z.infer<typeof equipmentInstanceSchema>;
|
||||
const { gymId, id } = req.params as GymParams & { id: string };
|
||||
const result = await updateEquipment(
|
||||
prisma,
|
||||
gymId,
|
||||
req.user!.id,
|
||||
id,
|
||||
body,
|
||||
Object.hasOwn(body, 'spec'),
|
||||
);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{id}:
|
||||
* delete:
|
||||
* summary: Remove a catalog equipment item from a gym (owner only)
|
||||
* summary: Remove an equipment instance (and its photos) from a gym (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Removed }
|
||||
* 400: { description: Equipment not in the gym }
|
||||
* 403: { description: Not the gym owner }
|
||||
*/
|
||||
router.delete(
|
||||
'/equipment/:equipmentId',
|
||||
'/equipment/:id',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { gymId, equipmentId } = req.params as GymParams & { equipmentId: string };
|
||||
await removeEquipment(prisma, gymId, req.user!.id, equipmentId);
|
||||
const { gymId, id } = req.params as GymParams & { id: string };
|
||||
await removeEquipment(prisma, gymId, req.user!.id, id);
|
||||
res.status(204).end();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -76,13 +76,16 @@ export const gymExceptionSchema = z.object({
|
||||
.optional(),
|
||||
});
|
||||
|
||||
/** `spec` = nadpisanie specyfikacji katalogowej (walidowane w serwisie względem `kind`). */
|
||||
export const equipmentSchema = z.object({
|
||||
equipmentId: z.string().min(1),
|
||||
quantity: z.number().int().min(1).max(10000).optional(),
|
||||
spec: z.unknown().optional(),
|
||||
});
|
||||
|
||||
export const equipmentQuantitySchema = z.object({
|
||||
quantity: z.number().int().min(1).max(10000),
|
||||
export const equipmentInstanceSchema = z.object({
|
||||
quantity: z.number().int().min(1).max(10000).optional(),
|
||||
spec: z.unknown().optional(),
|
||||
});
|
||||
|
||||
export const announcementSchema = z.object({
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { Prisma, type GymRole, type PrismaClient } from '@prisma/client';
|
||||
import { isPrismaNotFound, isPrismaUnique } from '../lib/prisma.js';
|
||||
import { validateEquipmentSpec } from '../lib/equipmentSpec.js';
|
||||
import { isPrismaNotFound } from '../lib/prisma.js';
|
||||
import { publicUser } from '../lib/publicUser.js';
|
||||
import { badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
|
||||
import { removeGymClaimFiles, removeGymPhotoFiles } from '../lib/uploads.js';
|
||||
import { availabilityChanged, gymPhotoUrl, listGymClaimIds } from './gyms.js';
|
||||
import {
|
||||
removeEquipmentPhotoFiles,
|
||||
removeGymClaimFiles,
|
||||
removeGymPhotoFiles,
|
||||
} from '../lib/uploads.js';
|
||||
import {
|
||||
availabilityChanged,
|
||||
gymPhotoUrl,
|
||||
listGymClaimIds,
|
||||
mapEquipmentPhotoDtos,
|
||||
} from './gyms.js';
|
||||
import { announceHoursChange } from './announcements.js';
|
||||
import { notifyGymDeleted } from './feed.js';
|
||||
import { formatAddress, type AddressParts } from '../lib/address.js';
|
||||
@@ -108,7 +118,10 @@ export async function getGym(prisma: PrismaClient, gymId: string) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: {
|
||||
equipment: { include: { equipment: true }, orderBy: { equipment: { name: 'asc' } } },
|
||||
equipment: {
|
||||
include: { equipment: true, photos: { orderBy: { createdAt: 'asc' } } },
|
||||
orderBy: { equipment: { name: 'asc' } },
|
||||
},
|
||||
photos: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] },
|
||||
_count: { select: { memberships: true } },
|
||||
memberships: {
|
||||
@@ -119,8 +132,12 @@ export async function getGym(prisma: PrismaClient, gymId: string) {
|
||||
},
|
||||
});
|
||||
if (!gym) throw Object.assign(new Error('Nie znaleziono siłowni'), { status: 404 });
|
||||
const { memberships, ...rest } = gym;
|
||||
return { ...rest, owners: memberships.map((m) => m.user) };
|
||||
const { memberships, equipment, ...rest } = gym;
|
||||
return {
|
||||
...rest,
|
||||
equipment: mapEquipmentPhotoDtos(gymId, equipment),
|
||||
owners: memberships.map((m) => m.user),
|
||||
};
|
||||
}
|
||||
|
||||
/** Nadaje użytkownikowi rolę OWNER (admin): tworzy członkostwo albo dopisuje rolę. */
|
||||
@@ -234,51 +251,72 @@ export async function deleteGym(prisma: PrismaClient, id: string) {
|
||||
removeGymPhotoFiles(id);
|
||||
}
|
||||
|
||||
/** Add a catalog equipment item to a gym with a quantity (admin, no owner check). */
|
||||
/**
|
||||
* Tworzy NOWĄ instancję wyposażenia siłowni (admin). `spec` = nadpisanie
|
||||
* specyfikacji katalogowej, walidowane względem `kind`; null/brak = dziedziczy.
|
||||
*/
|
||||
export async function addGymEquipment(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
equipmentId: string,
|
||||
quantity = 1,
|
||||
spec?: unknown,
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { equipment: true },
|
||||
});
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
const item = await prisma.equipment.findUnique({ where: { id: equipmentId } });
|
||||
if (!item) throw notFound('Equipment not found');
|
||||
if (gym.equipment.some((e) => e.equipmentId === equipmentId))
|
||||
throw conflict('Equipment already exists in this gym — update its quantity instead');
|
||||
try {
|
||||
await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } });
|
||||
} catch (e) {
|
||||
if (isPrismaUnique(e))
|
||||
throw conflict('Equipment already exists in this gym — update its quantity instead');
|
||||
throw e;
|
||||
}
|
||||
// Brak / null = instancja dziedziczy spec z katalogu; podana wartość musi pasować do `kind`.
|
||||
const validated =
|
||||
spec === undefined || spec === null
|
||||
? ({ ok: true, spec: null } as const)
|
||||
: validateEquipmentSpec(item.kind, spec);
|
||||
if (!validated.ok) throw badRequest(validated.error);
|
||||
const created = await prisma.gymEquipment.create({
|
||||
data: { gymId, equipmentId, quantity, spec: toPrismaJson(validated.spec) },
|
||||
});
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { equipment: { include: { equipment: true } } },
|
||||
});
|
||||
return { gym: updated };
|
||||
return { gym: updated, instance: created };
|
||||
}
|
||||
|
||||
/** Change the quantity of a gym's equipment item (admin, no owner check). */
|
||||
export async function updateGymEquipmentQuantity(
|
||||
/**
|
||||
* Zmiana ilości / specyfikacji instancji wyposażenia (admin).
|
||||
* `spec: null` czyści nadpisanie; brak klucza `spec` = bez zmian.
|
||||
*/
|
||||
export async function updateGymEquipment(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
equipmentId: string,
|
||||
quantity: number,
|
||||
instanceId: string,
|
||||
data: { quantity?: number; spec?: unknown },
|
||||
specProvided: boolean,
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { equipment: true },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
|
||||
const link = gym.equipment.find((e) => e.id === instanceId);
|
||||
if (!link) throw badRequest('Equipment not found in this gym');
|
||||
await prisma.gymEquipment.update({ where: { id: link.id }, data: { quantity } });
|
||||
const payload: Prisma.GymEquipmentUpdateInput = {};
|
||||
if (data.quantity !== undefined) payload.quantity = data.quantity;
|
||||
if (specProvided) {
|
||||
if (data.spec === null || data.spec === undefined) {
|
||||
payload.spec = Prisma.DbNull;
|
||||
} else {
|
||||
const item = await prisma.equipment.findUnique({
|
||||
where: { id: link.equipmentId },
|
||||
select: { kind: true },
|
||||
});
|
||||
if (!item) throw notFound('Equipment not found');
|
||||
const validated = validateEquipmentSpec(item.kind, data.spec);
|
||||
if (!validated.ok) throw badRequest(validated.error);
|
||||
payload.spec = toPrismaJson(validated.spec);
|
||||
}
|
||||
}
|
||||
await prisma.gymEquipment.update({ where: { id: instanceId }, data: payload });
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { equipment: { include: { equipment: true } } },
|
||||
@@ -286,16 +324,17 @@ export async function updateGymEquipmentQuantity(
|
||||
return { gym: updated };
|
||||
}
|
||||
|
||||
/** Remove a catalog equipment item from a gym (admin, no owner check). */
|
||||
export async function removeGymEquipment(prisma: PrismaClient, gymId: string, equipmentId: string) {
|
||||
/** Usuwa instancję wyposażenia wraz z plikami zdjęć (admin). */
|
||||
export async function removeGymEquipment(prisma: PrismaClient, gymId: string, instanceId: string) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { equipment: true },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
|
||||
const link = gym.equipment.find((e) => e.id === instanceId);
|
||||
if (!link) throw badRequest('Equipment not found in this gym');
|
||||
await prisma.gymEquipment.delete({ where: { id: link.id } });
|
||||
await prisma.gymEquipment.delete({ where: { id: instanceId } });
|
||||
removeEquipmentPhotoFiles(gymId, instanceId);
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { equipment: { include: { equipment: true } } },
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from './gyms/core.js';
|
||||
export * from './gyms/exceptions.js';
|
||||
export * from './gyms/photos.js';
|
||||
export * from './gyms/equipmentPhotos.js';
|
||||
export * from './gyms/claims.js';
|
||||
export * from './gyms/invitations.js';
|
||||
|
||||
77
api/src/services/gyms/equipmentPhotos.ts
Normal file
77
api/src/services/gyms/equipmentPhotos.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { AppError, badRequest, forbidden, notFound } from '../../lib/errors.js';
|
||||
import { logger } from '../../lib/logger.js';
|
||||
import {
|
||||
MAX_EQUIPMENT_PHOTOS,
|
||||
equipmentPhotoDir,
|
||||
removeEquipmentPhotoFile,
|
||||
storedFileName,
|
||||
} from '../../lib/uploads.js';
|
||||
import { canManageGym, loadGymDto, type UploadedPhotoFile } from './photos.js';
|
||||
|
||||
async function loadInstance(prisma: PrismaClient, gymId: string, instanceId: string) {
|
||||
const instance = await prisma.gymEquipment.findUnique({ where: { id: instanceId } });
|
||||
if (!instance || instance.gymId !== gymId) throw notFound('Equipment not found in this gym');
|
||||
return instance;
|
||||
}
|
||||
|
||||
/** Add photos to a gym equipment instance (owner or admin). */
|
||||
export async function addEquipmentPhotos(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
isAdmin: boolean,
|
||||
gymId: string,
|
||||
instanceId: string,
|
||||
files: UploadedPhotoFile[],
|
||||
) {
|
||||
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
|
||||
throw forbidden('Only the gym owner or an admin can manage equipment photos');
|
||||
await loadInstance(prisma, gymId, instanceId);
|
||||
const existing = await prisma.equipmentPhoto.count({ where: { gymEquipmentId: instanceId } });
|
||||
if (existing + files.length > MAX_EQUIPMENT_PHOTOS)
|
||||
throw badRequest(`An equipment item can have at most ${MAX_EQUIPMENT_PHOTOS} photos`);
|
||||
const dir = equipmentPhotoDir(gymId, instanceId);
|
||||
const moved: string[] = [];
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
for (const f of files) {
|
||||
const storedName = storedFileName(f.mimeType);
|
||||
fs.renameSync(f.path, path.join(dir, storedName));
|
||||
moved.push(path.join(dir, storedName));
|
||||
await prisma.equipmentPhoto.create({
|
||||
data: {
|
||||
gymEquipmentId: instanceId,
|
||||
storedName,
|
||||
mimeType: f.mimeType,
|
||||
sizeBytes: f.sizeBytes,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
for (const p of moved) fs.rmSync(p, { force: true });
|
||||
logger.error({ err: e, gymId, instanceId }, 'Failed to store equipment photos');
|
||||
throw new AppError(500, 'UPLOAD_FAILED', 'Failed to store uploaded photos');
|
||||
}
|
||||
return { gym: await loadGymDto(prisma, gymId) };
|
||||
}
|
||||
|
||||
/** Remove a photo from a gym equipment instance (owner or admin). */
|
||||
export async function deleteEquipmentPhoto(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
isAdmin: boolean,
|
||||
gymId: string,
|
||||
instanceId: string,
|
||||
photoId: string,
|
||||
) {
|
||||
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
|
||||
throw forbidden('Only the gym owner or an admin can manage equipment photos');
|
||||
await loadInstance(prisma, gymId, instanceId);
|
||||
const photo = await prisma.equipmentPhoto.findUnique({ where: { id: photoId } });
|
||||
if (!photo || photo.gymEquipmentId !== instanceId) throw notFound('Photo not found');
|
||||
await prisma.equipmentPhoto.delete({ where: { id: photoId } });
|
||||
removeEquipmentPhotoFile(gymId, instanceId, photo.storedName);
|
||||
return { gym: await loadGymDto(prisma, gymId) };
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { Prisma, type PrismaClient } from '@prisma/client';
|
||||
import { badRequest, conflict, notFound } from '../../lib/errors.js';
|
||||
import { validateEquipmentSpec } from '../../lib/equipmentSpec.js';
|
||||
import { isPrismaUnique } from '../../lib/prisma.js';
|
||||
import { removeEquipmentPhotoFiles } from '../../lib/uploads.js';
|
||||
import { toPrismaJson, type DayAvailability } from '../me.js';
|
||||
import { assertGymOwner } from './core.js';
|
||||
import { gymEquipmentInclude } from './includes.js';
|
||||
@@ -62,45 +64,72 @@ export async function deleteOwnedGymException(
|
||||
await prisma.gymException.delete({ where: { id: exceptionId } });
|
||||
}
|
||||
|
||||
/** Add a catalog equipment item to a gym with a quantity (owner only). */
|
||||
/**
|
||||
* Tworzy NOWĄ instancję wyposażenia siłowni (właściciel). Wielokrotne dodanie
|
||||
* tego samego typu = kolejne instancje (różne parametry/ilości), nie błąd.
|
||||
* `spec` = nadpisanie specyfikacji katalogowej, walidowane względem `kind`.
|
||||
*/
|
||||
export async function addEquipment(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
equipmentId: string,
|
||||
quantity = 1,
|
||||
spec?: unknown,
|
||||
) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
await assertGymOwner(prisma, gymId, userId);
|
||||
const item = await prisma.equipment.findUnique({ where: { id: equipmentId } });
|
||||
if (!item) throw notFound('Equipment not found');
|
||||
if (gym.equipment.some((e) => e.equipmentId === equipmentId))
|
||||
throw conflict('Equipment already exists in this gym — update its quantity instead');
|
||||
try {
|
||||
await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } });
|
||||
} catch (e) {
|
||||
if (isPrismaUnique(e))
|
||||
throw conflict('Equipment already exists in this gym — update its quantity instead');
|
||||
throw e;
|
||||
}
|
||||
// Brak / null = instancja dziedziczy spec z katalogu (bez walidacji);
|
||||
// podana wartość musi pasować do `kind`.
|
||||
const validated =
|
||||
spec === undefined || spec === null
|
||||
? ({ ok: true, spec: null } as const)
|
||||
: validateEquipmentSpec(item.kind, spec);
|
||||
if (!validated.ok) throw badRequest(validated.error);
|
||||
const created = await prisma.gymEquipment.create({
|
||||
data: { gymId, equipmentId, quantity, spec: toPrismaJson(validated.spec) },
|
||||
});
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: gymEquipmentInclude,
|
||||
});
|
||||
return { gym: updated };
|
||||
return { gym: updated, instance: created };
|
||||
}
|
||||
|
||||
/** Change the quantity of a gym's equipment item (owner only). */
|
||||
export async function updateEquipmentQuantity(
|
||||
/**
|
||||
* Zmiana ilości / specyfikacji instancji wyposażenia (właściciel).
|
||||
* `spec: null` czyści nadpisanie (instancja dziedziczy spec z katalogu);
|
||||
* brak klucza `spec` = bez zmian.
|
||||
*/
|
||||
export async function updateEquipment(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
equipmentId: string,
|
||||
quantity: number,
|
||||
instanceId: string,
|
||||
data: { quantity?: number; spec?: unknown },
|
||||
specProvided: boolean,
|
||||
) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
|
||||
const link = gym.equipment.find((e) => e.id === instanceId);
|
||||
if (!link) throw badRequest('Equipment not found in this gym');
|
||||
await prisma.gymEquipment.update({ where: { id: link.id }, data: { quantity } });
|
||||
const payload: Prisma.GymEquipmentUpdateInput = {};
|
||||
if (data.quantity !== undefined) payload.quantity = data.quantity;
|
||||
if (specProvided) {
|
||||
if (data.spec === null || data.spec === undefined) {
|
||||
payload.spec = Prisma.DbNull;
|
||||
} else {
|
||||
const item = await prisma.equipment.findUnique({
|
||||
where: { id: link.equipmentId },
|
||||
select: { kind: true },
|
||||
});
|
||||
if (!item) throw notFound('Equipment not found');
|
||||
const validated = validateEquipmentSpec(item.kind, data.spec);
|
||||
if (!validated.ok) throw badRequest(validated.error);
|
||||
payload.spec = toPrismaJson(validated.spec);
|
||||
}
|
||||
}
|
||||
await prisma.gymEquipment.update({ where: { id: instanceId }, data: payload });
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: gymEquipmentInclude,
|
||||
@@ -108,17 +137,18 @@ export async function updateEquipmentQuantity(
|
||||
return { gym: updated };
|
||||
}
|
||||
|
||||
/** Remove a catalog equipment item from a gym (owner only). */
|
||||
/** Usuwa instancję wyposażenia wraz z plikami zdjęć (właściciel). */
|
||||
export async function removeEquipment(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
equipmentId: string,
|
||||
instanceId: string,
|
||||
) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
|
||||
const link = gym.equipment.find((e) => e.id === instanceId);
|
||||
if (!link) throw badRequest('Equipment not found in this gym');
|
||||
await prisma.gymEquipment.delete({ where: { id: link.id } });
|
||||
await prisma.gymEquipment.delete({ where: { id: instanceId } });
|
||||
removeEquipmentPhotoFiles(gymId, instanceId);
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: gymEquipmentInclude,
|
||||
|
||||
@@ -6,6 +6,14 @@ export const gymEquipmentInclude = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Equipment instances with the catalog item and photos (detail views). */
|
||||
export const gymEquipmentWithPhotosInclude = {
|
||||
equipment: {
|
||||
include: { equipment: true, photos: { orderBy: { createdAt: 'asc' as const } } },
|
||||
orderBy: { equipment: { name: 'asc' as const } },
|
||||
},
|
||||
};
|
||||
|
||||
/** Gallery photos, cover first (smallest order, tie → oldest). */
|
||||
export const gymPhotosInclude = {
|
||||
photos: { orderBy: [{ order: 'asc' as const }, { createdAt: 'asc' as const }] },
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
removeGymPhotoFile,
|
||||
storedFileName,
|
||||
} from '../../lib/uploads.js';
|
||||
import { gymEquipmentInclude, gymPhotosInclude } from './includes.js';
|
||||
import { gymEquipmentWithPhotosInclude, gymPhotosInclude } from './includes.js';
|
||||
|
||||
export interface GymPhotoDto {
|
||||
id: string;
|
||||
@@ -23,15 +23,34 @@ export function gymPhotoUrl(gymId: string, photoId: string): string {
|
||||
return `/gyms/${gymId}/photos/${photoId}`;
|
||||
}
|
||||
|
||||
/** Photo URL of an equipment instance (served by GET /gyms/:gymId/equipment/:id/photos/:photoId). */
|
||||
export function equipmentPhotoUrl(gymId: string, gymEquipmentId: string, photoId: string): string {
|
||||
return `/gyms/${gymId}/equipment/${gymEquipmentId}/photos/${photoId}`;
|
||||
}
|
||||
|
||||
export function coverUrlOf(gymId: string, photos: { id: string }[]): string | null {
|
||||
return photos[0] ? gymPhotoUrl(gymId, photos[0].id) : null;
|
||||
}
|
||||
|
||||
/** Replace raw EquipmentPhoto rows on instances with { id, url, createdAt } DTOs. */
|
||||
export function mapEquipmentPhotoDtos<
|
||||
T extends { id: string; photos: { id: string; createdAt: Date }[] },
|
||||
>(gymId: string, items: T[]) {
|
||||
return items.map((item) => {
|
||||
const { photos, ...rest } = item;
|
||||
return {
|
||||
...rest,
|
||||
photos: photos.map((p) => ({
|
||||
id: p.id,
|
||||
url: equipmentPhotoUrl(gymId, item.id, p.id),
|
||||
createdAt: p.createdAt.toISOString(),
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
type GymWithPhotos = Prisma.GymGetPayload<{
|
||||
include: {
|
||||
equipment: { include: { equipment: true } };
|
||||
photos: true;
|
||||
};
|
||||
include: typeof gymEquipmentWithPhotosInclude & typeof gymPhotosInclude;
|
||||
}>;
|
||||
|
||||
function gymToDto(g: GymWithPhotos) {
|
||||
@@ -49,16 +68,16 @@ function gymToDto(g: GymWithPhotos) {
|
||||
capacity: g.capacity,
|
||||
kind: g.kind,
|
||||
isPrivate: g.isPrivate,
|
||||
equipment: g.equipment,
|
||||
equipment: mapEquipmentPhotoDtos(g.id, g.equipment),
|
||||
photos,
|
||||
coverPhoto: coverUrlOf(g.id, g.photos),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadGymDto(prisma: PrismaClient, gymId: string) {
|
||||
export async function loadGymDto(prisma: PrismaClient, gymId: string) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
|
||||
include: { ...gymEquipmentWithPhotosInclude, ...gymPhotosInclude },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
return gymToDto(gym);
|
||||
@@ -91,7 +110,7 @@ export async function getGymPublic(
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
|
||||
include: { ...gymEquipmentWithPhotosInclude, ...gymPhotosInclude },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, userId, isAdmin)))
|
||||
|
||||
@@ -270,7 +270,8 @@ export const openapi: Record<string, unknown> = {
|
||||
'/gyms/{gymId}/equipment': {
|
||||
post: {
|
||||
tags: ['Gyms'],
|
||||
summary: 'Add a catalog equipment item to a gym (owner only)',
|
||||
summary:
|
||||
'Create an equipment instance in a gym (owner only); repeats of a catalog type create new instances. Optional spec overrides the catalog spec (validated against its kind)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
requestBody: {
|
||||
@@ -280,21 +281,92 @@ export const openapi: Record<string, unknown> = {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['equipmentId'],
|
||||
properties: { equipmentId: { type: 'string' } },
|
||||
properties: {
|
||||
equipmentId: { type: 'string' },
|
||||
quantity: { type: 'integer', minimum: 1, maximum: 10000 },
|
||||
spec: {
|
||||
type: 'object',
|
||||
nullable: true,
|
||||
description: 'Override of the catalog spec, e.g. {minKg,maxKg} / {maxLoadKg}',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/gyms/{gymId}/equipment/{equipmentId}': {
|
||||
delete: {
|
||||
'/gyms/{gymId}/equipment/{id}': {
|
||||
patch: {
|
||||
tags: ['Gyms'],
|
||||
summary: 'Remove a catalog equipment item from a gym (owner only)',
|
||||
summary:
|
||||
'Change quantity and/or spec override of an equipment instance (owner only); spec:null clears the override',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'equipmentId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
quantity: { type: 'integer', minimum: 1, maximum: 10000 },
|
||||
spec: { type: 'object', nullable: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
tags: ['Gyms'],
|
||||
summary: 'Remove an equipment instance (and its photos) from a gym (owner only)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
'/gyms/{gymId}/equipment/{id}/photos': {
|
||||
post: {
|
||||
tags: ['Gyms'],
|
||||
summary:
|
||||
"Add photos to an equipment instance (owner or admin; multipart field 'photos', max 5, 5 MB)",
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: { 'multipart/form-data': { schema: { type: 'object' } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/gyms/{gymId}/equipment/{id}/photos/{photoId}': {
|
||||
get: {
|
||||
tags: ['Gyms'],
|
||||
summary:
|
||||
'Serve an equipment photo (REAL visible to all logged-in users; VIRTUAL to managers)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'photoId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
},
|
||||
delete: {
|
||||
tags: ['Gyms'],
|
||||
summary: 'Remove a photo from an equipment instance (owner or admin)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'photoId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
@@ -701,7 +773,8 @@ export const openapi: Record<string, unknown> = {
|
||||
'/admin/gyms/{id}/equipment': {
|
||||
post: {
|
||||
tags: ['Admin'],
|
||||
summary: 'Add a catalog equipment item to a gym (admin)',
|
||||
summary:
|
||||
'Create an equipment instance in a gym (admin); repeats of a catalog type create new instances. Optional spec overrides the catalog spec (validated against its kind)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
requestBody: {
|
||||
@@ -711,21 +784,49 @@ export const openapi: Record<string, unknown> = {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['equipmentId'],
|
||||
properties: { equipmentId: { type: 'string' } },
|
||||
properties: {
|
||||
equipmentId: { type: 'string' },
|
||||
quantity: { type: 'integer', minimum: 1, maximum: 10000 },
|
||||
spec: { type: 'object', nullable: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/admin/gyms/{id}/equipment/{equipmentId}': {
|
||||
delete: {
|
||||
'/admin/gyms/{id}/equipment/{instanceId}': {
|
||||
patch: {
|
||||
tags: ['Admin'],
|
||||
summary: 'Remove a catalog equipment item from a gym (admin)',
|
||||
summary:
|
||||
'Change quantity and/or spec override of an equipment instance (admin); spec:null clears the override',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'equipmentId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'instanceId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
quantity: { type: 'integer', minimum: 1, maximum: 10000 },
|
||||
spec: { type: 'object', nullable: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
tags: ['Admin'],
|
||||
summary: 'Remove an equipment instance (and its photos) from a gym (admin)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'instanceId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
@@ -168,7 +168,9 @@ describe('equipment catalog (kind + spec)', () => {
|
||||
|
||||
// sprzątanie
|
||||
await app.delete(`/api/v1/admin/exercises/${exercise.body.exercise.id}`).set('Authorization', `Bearer ${adminToken}`);
|
||||
await app.delete(`/api/v1/admin/gyms/${gym.id}/equipment/${equipmentId}`).set('Authorization', `Bearer ${adminToken}`);
|
||||
await app
|
||||
.delete(`/api/v1/admin/gyms/${gym.id}/equipment/${linked.body.instance.id}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
await prisma.gym.delete({ where: { id: gym.id } });
|
||||
});
|
||||
|
||||
@@ -194,7 +196,7 @@ describe('equipment catalog (kind + spec)', () => {
|
||||
expect(addedDumbbells.status).toBe(200);
|
||||
|
||||
const updated = await app
|
||||
.patch(`/api/v1/admin/gyms/${gym.id}/equipment/${dumbbells.id}`)
|
||||
.patch(`/api/v1/admin/gyms/${gym.id}/equipment/${addedDumbbells.body.instance.id}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ quantity: 6 });
|
||||
expect(updated.status).toBe(200);
|
||||
|
||||
344
api/test/integration/gym-equipment-instances.test.ts
Normal file
344
api/test/integration/gym-equipment-instances.test.ts
Normal file
@@ -0,0 +1,344 @@
|
||||
import fs from 'node:fs';
|
||||
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||
import { prisma } from '../../src/lib/prisma.js';
|
||||
import { buildApp, createUserWithToken, rand } from '../helpers.js';
|
||||
import { equipmentPhotoDir, removeGymPhotoFiles } from '../../src/lib/uploads.js';
|
||||
|
||||
/** Minimal 1x1 transparent PNG. */
|
||||
const PNG_BUFFER = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
);
|
||||
|
||||
describe('gym equipment — instances, spec overrides, photos', () => {
|
||||
let ownerToken: string;
|
||||
let ownerId: string;
|
||||
let strangerToken: string;
|
||||
let adminToken: string;
|
||||
|
||||
const gymIds: string[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
const owner = await createUserWithToken();
|
||||
ownerId = owner.user.id;
|
||||
ownerToken = owner.token;
|
||||
const stranger = await createUserWithToken();
|
||||
strangerToken = stranger.token;
|
||||
const admin = await createUserWithToken({ isAdmin: true });
|
||||
adminToken = admin.token;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of gymIds) removeGymPhotoFiles(id);
|
||||
await prisma.equipmentPhoto
|
||||
.deleteMany({ where: { gymEquipment: { gymId: { in: gymIds } } } })
|
||||
.catch(() => undefined);
|
||||
await prisma.gymEquipment
|
||||
.deleteMany({ where: { gymId: { in: gymIds } } })
|
||||
.catch(() => undefined);
|
||||
await prisma.gymMembership.deleteMany({ where: { gymId: { in: gymIds } } }).catch(() => undefined);
|
||||
await prisma.gym.deleteMany({ where: { id: { in: gymIds } } }).catch(() => undefined);
|
||||
});
|
||||
|
||||
async function createOwnedGym(name?: string) {
|
||||
const gym = await prisma.gym.create({
|
||||
data: { name: name ?? `Equip Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
|
||||
});
|
||||
gymIds.push(gym.id);
|
||||
await prisma.gymMembership.create({
|
||||
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
|
||||
});
|
||||
return gym;
|
||||
}
|
||||
|
||||
async function createCatalogItem(kind: string, spec: unknown = null) {
|
||||
return prisma.equipment.create({
|
||||
data: { name: `Test Equip ${rand()}`, kind: kind as never, spec: spec as never },
|
||||
});
|
||||
}
|
||||
|
||||
it('POST /gyms/:id/equipment stores a spec override validated against the catalog kind', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const dumbbell = await createCatalogItem('DUMBBELL', { minKg: 2, maxKg: 40 });
|
||||
const res = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: dumbbell.id, quantity: 4, spec: { minKg: 5, maxKg: 5 } });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.instance).toMatchObject({ quantity: 4, spec: { minKg: 5, maxKg: 5 } });
|
||||
expect(res.body.gym.equipment).toEqual([
|
||||
expect.objectContaining({
|
||||
equipmentId: dumbbell.id,
|
||||
quantity: 4,
|
||||
spec: { minKg: 5, maxKg: 5 },
|
||||
equipment: expect.objectContaining({ spec: { minKg: 2, maxKg: 40 } }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('POST /gyms/:id/equipment rejects a spec invalid for the kind with 400', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const dumbbell = await createCatalogItem('DUMBBELL', { minKg: 2, maxKg: 40 });
|
||||
const res = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: dumbbell.id, spec: { maxLoadKg: 100 } });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('allows two instances of the same catalog type with different specs', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const dumbbell = await createCatalogItem('DUMBBELL', { minKg: 2, maxKg: 40 });
|
||||
const first = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: dumbbell.id, quantity: 4, spec: { minKg: 5, maxKg: 5 } });
|
||||
const second = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: dumbbell.id, quantity: 2, spec: { minKg: 2, maxKg: 24 } });
|
||||
expect(first.status).toBe(200);
|
||||
expect(second.status).toBe(200);
|
||||
const specs = second.body.gym.equipment
|
||||
.map((e: { spec: { minKg: number } }) => e.spec.minKg)
|
||||
.sort((a: number, b: number) => a - b);
|
||||
expect(specs).toEqual([2, 5]);
|
||||
});
|
||||
|
||||
it('PATCH spec:null clears the override (instance inherits the catalog spec)', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const dumbbell = await createCatalogItem('DUMBBELL', { minKg: 2, maxKg: 40 });
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: dumbbell.id, spec: { minKg: 5, maxKg: 5 } });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
const res = await app
|
||||
.patch(`/api/v1/gyms/${gym.id}/equipment/${instanceId}`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ spec: null });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.gym.equipment[0]).toMatchObject({ spec: null });
|
||||
});
|
||||
|
||||
it('PATCH without the spec key keeps the override', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const dumbbell = await createCatalogItem('DUMBBELL', { minKg: 2, maxKg: 40 });
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: dumbbell.id, spec: { minKg: 5, maxKg: 5 } });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
const res = await app
|
||||
.patch(`/api/v1/gyms/${gym.id}/equipment/${instanceId}`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ quantity: 9 });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.gym.equipment[0]).toMatchObject({ quantity: 9, spec: { minKg: 5, maxKg: 5 } });
|
||||
});
|
||||
|
||||
it('equipment photo lifecycle: upload, serve, delete (owner)', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const item = await createCatalogItem('MACHINE', { minKg: 10, maxKg: 100 });
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: item.id });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
|
||||
const uploaded = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: 'a.png', contentType: 'image/png' })
|
||||
.attach('photos', PNG_BUFFER, { filename: 'b.png', contentType: 'image/png' });
|
||||
expect(uploaded.status).toBe(200);
|
||||
const photos = uploaded.body.gym.equipment.find((e: { id: string }) => e.id === instanceId)
|
||||
.photos as { id: string; url: string }[];
|
||||
expect(photos).toHaveLength(2);
|
||||
expect(photos[0].url).toBe(`/gyms/${gym.id}/equipment/${instanceId}/photos/${photos[0].id}`);
|
||||
|
||||
const served = await app
|
||||
.get(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos/${photos[0].id}`)
|
||||
.set('Authorization', `Bearer ${strangerToken}`);
|
||||
expect(served.status).toBe(200);
|
||||
expect(served.headers['content-type']).toContain('image/png');
|
||||
expect(served.body.length).toBe(PNG_BUFFER.length);
|
||||
|
||||
const removed = await app
|
||||
.delete(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos/${photos[0].id}`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`);
|
||||
expect(removed.status).toBe(200);
|
||||
const left = removed.body.gym.equipment
|
||||
.find((e: { id: string }) => e.id === instanceId)
|
||||
.photos as unknown[];
|
||||
expect(left).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('equipment photos reject non-image files (400) and a sixth photo (400)', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const item = await createCatalogItem('OTHER');
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: item.id });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
|
||||
const bad = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.attach('photos', Buffer.from('hello'), { filename: 'a.txt', contentType: 'text/plain' });
|
||||
expect(bad.status).toBe(400);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const ok = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: `p${i}.png`, contentType: 'image/png' });
|
||||
expect(ok.status).toBe(200);
|
||||
}
|
||||
const over = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: 'p6.png', contentType: 'image/png' })
|
||||
.attach('photos', PNG_BUFFER, { filename: 'p7.png', contentType: 'image/png' });
|
||||
expect(over.status).toBe(400);
|
||||
});
|
||||
|
||||
it('equipment photos: non-owner gets 403, admin may manage', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const item = await createCatalogItem('OTHER');
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: item.id });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
|
||||
const denied = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${strangerToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: 'a.png', contentType: 'image/png' });
|
||||
expect(denied.status).toBe(403);
|
||||
|
||||
const adminAdded = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: 'a.png', contentType: 'image/png' });
|
||||
expect(adminAdded.status).toBe(200);
|
||||
});
|
||||
|
||||
it('deleting an instance removes its photo rows and files', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const item = await createCatalogItem('OTHER');
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: item.id });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: 'a.png', contentType: 'image/png' });
|
||||
expect(fs.existsSync(equipmentPhotoDir(gym.id, instanceId))).toBe(true);
|
||||
|
||||
const res = await app
|
||||
.delete(`/api/v1/gyms/${gym.id}/equipment/${instanceId}`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`);
|
||||
expect(res.status).toBe(204);
|
||||
expect(await prisma.equipmentPhoto.count({ where: { gymEquipmentId: instanceId } })).toBe(0);
|
||||
expect(fs.existsSync(equipmentPhotoDir(gym.id, instanceId))).toBe(false);
|
||||
});
|
||||
|
||||
it('admin: create instance with spec, patch quantity, delete by instance id', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await prisma.gym.create({
|
||||
data: { name: `Admin Equip ${rand()}`, kind: 'REAL', location: 'Warszawa' },
|
||||
});
|
||||
gymIds.push(gym.id);
|
||||
const kettlebell = await createCatalogItem('KETTLEBELL', { minKg: 4, maxKg: 48 });
|
||||
|
||||
const created = await app
|
||||
.post(`/api/v1/admin/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ equipmentId: kettlebell.id, quantity: 6, spec: { minKg: 8, maxKg: 8 } });
|
||||
expect(created.status).toBe(200);
|
||||
expect(created.body.instance).toMatchObject({ quantity: 6, spec: { minKg: 8, maxKg: 8 } });
|
||||
|
||||
const bad = await app
|
||||
.post(`/api/v1/admin/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ equipmentId: kettlebell.id, spec: { minKg: 40, maxKg: 8 } });
|
||||
expect(bad.status).toBe(400);
|
||||
|
||||
const instanceId = created.body.instance.id as string;
|
||||
const patched = await app
|
||||
.patch(`/api/v1/admin/gyms/${gym.id}/equipment/${instanceId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ quantity: 2 });
|
||||
expect(patched.status).toBe(200);
|
||||
expect(patched.body.gym.equipment[0]).toMatchObject({ quantity: 2, spec: { minKg: 8, maxKg: 8 } });
|
||||
|
||||
const removed = await app
|
||||
.delete(`/api/v1/admin/gyms/${gym.id}/equipment/${instanceId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(removed.status).toBe(204);
|
||||
const after = await prisma.gymEquipment.count({ where: { gymId: gym.id } });
|
||||
expect(after).toBe(0);
|
||||
});
|
||||
|
||||
it('admin detail GET /admin/gyms/:id exposes instance spec and photo urls', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const item = await createCatalogItem('OTHER');
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: item.id });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: 'a.png', contentType: 'image/png' });
|
||||
|
||||
const res = await app
|
||||
.get(`/api/v1/admin/gyms/${gym.id}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
const instance = res.body.equipment.find((e: { id: string }) => e.id === instanceId);
|
||||
expect(instance).toMatchObject({ spec: null });
|
||||
expect(instance.photos).toHaveLength(1);
|
||||
expect(instance.photos[0].url).toContain(`/equipment/${instanceId}/photos/`);
|
||||
expect(instance.photos[0].storedName).toBeUndefined();
|
||||
});
|
||||
|
||||
it('public detail GET /gyms/:id exposes instance spec and photo urls', async () => {
|
||||
const app = buildApp();
|
||||
const gym = await createOwnedGym();
|
||||
const item = await createCatalogItem('OTHER');
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.send({ equipmentId: item.id });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
await app
|
||||
.post(`/api/v1/gyms/${gym.id}/equipment/${instanceId}/photos`)
|
||||
.set('Authorization', `Bearer ${ownerToken}`)
|
||||
.attach('photos', PNG_BUFFER, { filename: 'a.png', contentType: 'image/png' });
|
||||
|
||||
const res = await app
|
||||
.get(`/api/v1/gyms/${gym.id}`)
|
||||
.set('Authorization', `Bearer ${strangerToken}`);
|
||||
expect(res.status).toBe(200);
|
||||
const instance = res.body.gym.equipment.find((e: { id: string }) => e.id === instanceId);
|
||||
expect(instance.photos).toHaveLength(1);
|
||||
expect(instance.photos[0].storedName).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -116,7 +116,7 @@ describe('gyms — selection and management', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('lets the owner change the equipment quantity', async () => {
|
||||
it('lets the owner change the equipment instance quantity', async () => {
|
||||
const app = buildApp();
|
||||
const created = await app
|
||||
.post('/api/v1/gyms')
|
||||
@@ -124,12 +124,14 @@ describe('gyms — selection and management', () => {
|
||||
.send({ name: `Qty Gym ${rand()}`, location: 'Warsaw' });
|
||||
const gymId = created.body.gym.id as string;
|
||||
const dumbbells = await createEquipment('Hantle');
|
||||
await app
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gymId}/equipment`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ equipmentId: dumbbells.id, quantity: 3 });
|
||||
expect(added.status).toBe(200);
|
||||
const instanceId = added.body.instance.id as string;
|
||||
const res = await app
|
||||
.patch(`/api/v1/gyms/${gymId}/equipment/${dumbbells.id}`)
|
||||
.patch(`/api/v1/gyms/${gymId}/equipment/${instanceId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ quantity: 5 });
|
||||
expect(res.status).toBe(200);
|
||||
@@ -152,7 +154,7 @@ describe('gyms — selection and management', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects duplicate equipment with 409', async () => {
|
||||
it('creates a second instance when the same catalog type is added again', async () => {
|
||||
const app = buildApp();
|
||||
const created = await app
|
||||
.post('/api/v1/gyms')
|
||||
@@ -167,8 +169,13 @@ describe('gyms — selection and management', () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/gyms/${gymId}/equipment`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ equipmentId: barbell.id });
|
||||
expect(res.status).toBe(409);
|
||||
.send({ equipmentId: barbell.id, quantity: 2 });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.gym.equipment).toHaveLength(2);
|
||||
const quantities = res.body.gym.equipment
|
||||
.map((e: { quantity: number }) => e.quantity)
|
||||
.sort();
|
||||
expect(quantities).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it('rejects adding unknown equipment with 404', async () => {
|
||||
@@ -218,12 +225,13 @@ describe('gyms — selection and management', () => {
|
||||
});
|
||||
const gymId = created.body.gym.id as string;
|
||||
const kettlebell = await createEquipment('Kettlebell');
|
||||
await app
|
||||
const added = await app
|
||||
.post(`/api/v1/gyms/${gymId}/equipment`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ equipmentId: kettlebell.id });
|
||||
const instanceId = added.body.instance.id as string;
|
||||
const res = await app
|
||||
.delete(`/api/v1/gyms/${gymId}/equipment/${kettlebell.id}`)
|
||||
.delete(`/api/v1/gyms/${gymId}/equipment/${instanceId}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(res.status).toBe(204);
|
||||
const after = await app.get(`/api/v1/gyms/all`).set('Authorization', `Bearer ${token}`);
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
ConversationThread,
|
||||
Dashboard,
|
||||
Equipment,
|
||||
EquipmentSpec,
|
||||
FeedItem,
|
||||
GymAnnouncement,
|
||||
ExerciseComment,
|
||||
@@ -192,22 +193,50 @@ export function rateGym(gymId: string, vote: 'UP' | 'DOWN') {
|
||||
});
|
||||
}
|
||||
|
||||
export function addGymEquipment(gymId: string, equipmentId: string, quantity = 1) {
|
||||
return api<{ gym: Gym }>(`/gyms/${gymId}/equipment`, {
|
||||
/** Tworzy NOWĄ instancję wyposażenia (powtórki typu katalogowego = nowe instancje). */
|
||||
export function addGymEquipment(
|
||||
gymId: string,
|
||||
equipmentId: string,
|
||||
quantity = 1,
|
||||
spec?: EquipmentSpec | null,
|
||||
) {
|
||||
return api<{ gym: Gym; instance: { id: string } }>(`/gyms/${gymId}/equipment`, {
|
||||
method: 'POST',
|
||||
body: { equipmentId, quantity },
|
||||
body: { equipmentId, quantity, ...(spec ? { spec } : {}) },
|
||||
});
|
||||
}
|
||||
|
||||
export function updateGymEquipmentQuantity(gymId: string, equipmentId: string, quantity: number) {
|
||||
return api<{ gym: Gym }>(`/gyms/${gymId}/equipment/${encodeURIComponent(equipmentId)}`, {
|
||||
/** Zmiana ilości / nadpisania spec instancji; `spec: null` czyści nadpisanie. */
|
||||
export function updateGymEquipment(
|
||||
gymId: string,
|
||||
instanceId: string,
|
||||
body: { quantity?: number; spec?: EquipmentSpec | null },
|
||||
) {
|
||||
return api<{ gym: Gym }>(`/gyms/${gymId}/equipment/${encodeURIComponent(instanceId)}`, {
|
||||
method: 'PATCH',
|
||||
body: { quantity },
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
export function removeGymEquipment(gymId: string, equipmentId: string) {
|
||||
return api(`/gyms/${gymId}/equipment/${encodeURIComponent(equipmentId)}`, { method: 'DELETE' });
|
||||
export function removeGymEquipment(gymId: string, instanceId: string) {
|
||||
return api(`/gyms/${gymId}/equipment/${encodeURIComponent(instanceId)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
/** Dodaje zdjęcia instancji urządzenia (multipart, pole `photos`, max 5). */
|
||||
export function addEquipmentPhotos(gymId: string, instanceId: string, files: File[]) {
|
||||
const form = new FormData();
|
||||
for (const f of files) form.append('photos', f);
|
||||
return api<{ gym: Gym }>(`/gyms/${gymId}/equipment/${encodeURIComponent(instanceId)}/photos`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteEquipmentPhoto(gymId: string, instanceId: string, photoId: string) {
|
||||
return api<{ gym: Gym }>(
|
||||
`/gyms/${gymId}/equipment/${encodeURIComponent(instanceId)}/photos/${encodeURIComponent(photoId)}`,
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
}
|
||||
|
||||
export function updateGym(
|
||||
|
||||
@@ -87,13 +87,27 @@ export interface Equipment {
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
/** A gym's equipment instance: how many units of a catalog item the gym has. */
|
||||
/** Zdjęcie instancji urządzenia siłowni; `url` = ścieżka względna API. */
|
||||
export interface EquipmentPhoto {
|
||||
id: string;
|
||||
url: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A gym's equipment instance: a concrete set of units of a catalog type
|
||||
* (e.g. fixed 5 kg dumbbells ×4 AND adjustable 2–24 kg ×2 = two instances).
|
||||
* `spec` overrides the catalog spec; null = inherit it.
|
||||
*/
|
||||
export interface GymEquipment {
|
||||
id: string;
|
||||
gymId: string;
|
||||
equipmentId: string;
|
||||
quantity: number;
|
||||
spec: EquipmentSpec | null;
|
||||
equipment: Equipment;
|
||||
/** Zdjęcia (tylko widoki detalu siłowni; listy mogą ich nie zawierać). */
|
||||
photos?: EquipmentPhoto[];
|
||||
}
|
||||
|
||||
export type GymKind = 'VIRTUAL' | 'REAL';
|
||||
|
||||
@@ -18,7 +18,7 @@ function fmtKg(value: number): string {
|
||||
|
||||
/**
|
||||
* Human-readable summary of a type-specific spec payload:
|
||||
* DUMBBELL/KETTLEBELL/CABLE/MACHINE → "2.5–25 kg"
|
||||
* DUMBBELL/KETTLEBELL/CABLE/MACHINE → "2.5–25 kg" ("5 kg" dla stałego ciężaru)
|
||||
* BARBELL/BENCH → "do 100 kg"
|
||||
* CARDIO → "do 16 km/h" (+ "nachylenie do 15%")
|
||||
* BODYWEIGHT/OTHER or no spec → null
|
||||
@@ -27,9 +27,13 @@ export function formatEquipmentSpec(spec: EquipmentSpec | null | undefined): str
|
||||
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`);
|
||||
if (spec.minKg != null && spec.maxKg != null) {
|
||||
parts.push(
|
||||
spec.minKg === spec.maxKg
|
||||
? `${fmtKg(spec.minKg)} kg`
|
||||
: `${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`);
|
||||
@@ -38,9 +42,95 @@ export function formatEquipmentSpec(spec: EquipmentSpec | null | undefined): str
|
||||
return parts.length ? parts.join(', ') : null;
|
||||
}
|
||||
|
||||
/** Kinds z zakresem obciążeń { minKg, maxKg }. */
|
||||
export const LOAD_RANGE_KINDS: EquipmentKind[] = ['DUMBBELL', 'KETTLEBELL', 'CABLE', 'MACHINE'];
|
||||
/** Kinds z maksymalnym obciążeniem { maxLoadKg }. */
|
||||
export const MAX_LOAD_KINDS: EquipmentKind[] = ['BARBELL', 'BENCH'];
|
||||
|
||||
/** Pola formularza spec (stringi = wartość inputa). */
|
||||
export interface SpecFields {
|
||||
minKg: string;
|
||||
maxKg: string;
|
||||
maxLoadKg: string;
|
||||
maxSpeedKmh: string;
|
||||
maxInclinePct: string;
|
||||
}
|
||||
|
||||
export const EMPTY_SPEC_FIELDS: SpecFields = {
|
||||
minKg: '',
|
||||
maxKg: '',
|
||||
maxLoadKg: '',
|
||||
maxSpeedKmh: '',
|
||||
maxInclinePct: '',
|
||||
};
|
||||
|
||||
export function specFieldsFrom(spec: EquipmentSpec | null | undefined): SpecFields {
|
||||
const s = spec ?? {};
|
||||
return {
|
||||
minKg: s.minKg != null ? String(s.minKg) : '',
|
||||
maxKg: s.maxKg != null ? String(s.maxKg) : '',
|
||||
maxLoadKg: s.maxLoadKg != null ? String(s.maxLoadKg) : '',
|
||||
maxSpeedKmh: s.maxSpeedKmh != null ? String(s.maxSpeedKmh) : '',
|
||||
maxInclinePct: s.maxInclinePct != null ? String(s.maxInclinePct) : '',
|
||||
};
|
||||
}
|
||||
|
||||
function parseNum(value: string): number | undefined {
|
||||
if (value.trim() === '') return undefined;
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : undefined;
|
||||
}
|
||||
|
||||
/** Buduje payload spec z pól formularza wg rodzaju urządzenia; błąd = komunikat PL. */
|
||||
export function specFromFields(
|
||||
kind: EquipmentKind,
|
||||
f: SpecFields,
|
||||
): { spec: EquipmentSpec | null } | { error: string } {
|
||||
if (LOAD_RANGE_KINDS.includes(kind)) {
|
||||
const minKg = parseNum(f.minKg);
|
||||
const maxKg = parseNum(f.maxKg);
|
||||
if (minKg == null || maxKg == null) return { error: 'Podaj zakres obciążeń (min i max w kg).' };
|
||||
return { spec: { minKg, maxKg } };
|
||||
}
|
||||
if (MAX_LOAD_KINDS.includes(kind)) {
|
||||
const maxLoadKg = parseNum(f.maxLoadKg);
|
||||
if (maxLoadKg == null) return { error: 'Podaj maksymalne obciążenie (kg).' };
|
||||
return { spec: { maxLoadKg } };
|
||||
}
|
||||
if (kind === 'CARDIO') {
|
||||
const maxSpeedKmh = parseNum(f.maxSpeedKmh);
|
||||
const maxInclinePct = parseNum(f.maxInclinePct);
|
||||
if (maxSpeedKmh == null && maxInclinePct == null) return { spec: null };
|
||||
return {
|
||||
spec: {
|
||||
...(maxSpeedKmh != null ? { maxSpeedKmh } : {}),
|
||||
...(maxInclinePct != null ? { maxInclinePct } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
return { spec: null };
|
||||
}
|
||||
|
||||
/** Czy dla danego rodzaju formularz pokazuje jakiekolwiek pola spec. */
|
||||
export function hasSpecFields(kind: EquipmentKind): boolean {
|
||||
return LOAD_RANGE_KINDS.includes(kind) || MAX_LOAD_KINDS.includes(kind) || kind === 'CARDIO';
|
||||
}
|
||||
|
||||
/** Efektywny spec instancji: nadpisanie siłowni, inaczej spec z katalogu. */
|
||||
export function effectiveSpec(item: {
|
||||
spec?: EquipmentSpec | null;
|
||||
equipment: { spec: EquipmentSpec | null };
|
||||
}): EquipmentSpec | null {
|
||||
return item.spec ?? item.equipment.spec ?? 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);
|
||||
export function formatGymEquipment(item: {
|
||||
quantity: number;
|
||||
spec?: EquipmentSpec | null;
|
||||
equipment: Equipment;
|
||||
}): string {
|
||||
const spec = formatEquipmentSpec(effectiveSpec(item));
|
||||
const qty = item.quantity > 1 ? ` ×${item.quantity}` : '';
|
||||
return spec ? `${item.equipment.name}${qty} · ${spec}` : `${item.equipment.name}${qty}`;
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
withdrawGymClaim,
|
||||
withdrawGymInvitation,
|
||||
} from '../../api/queries';
|
||||
import type { Gym, GymException } from '../../api/types';
|
||||
import type { Gym, GymEquipment, GymException } from '../../api/types';
|
||||
import { fmtDateTime } from '../../lib/format';
|
||||
import { formatGymEquipment } from '../../lib/equipment';
|
||||
import {
|
||||
@@ -115,22 +115,69 @@ function GalleryMosaic({ gym }: { gym: Gym & { photos: { id: string; url: string
|
||||
);
|
||||
}
|
||||
|
||||
/* Kafle urządzeń (read-only): pełna specyfikacja z katalogu. */
|
||||
/* Kafle urządzeń (read-only): specyfikacja efektywna + miniatura zdjęcia; klik = podgląd zdjęć. */
|
||||
function EquipmentTiles({ gym }: { gym: Gym }) {
|
||||
const [preview, setPreview] = useState<GymEquipment | null>(null);
|
||||
if (gym.equipment.length === 0) {
|
||||
return <p className="text-[0.875rem] text-dim">Brak urządzeń.</p>;
|
||||
}
|
||||
const photos = preview?.photos ?? [];
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
{gym.equipment.map((e) => (
|
||||
<div
|
||||
key={e.id}
|
||||
className="flex items-center justify-between gap-2 rounded-[10px] border border-line bg-card/50 px-3 py-2.5 text-[0.85rem] font-semibold"
|
||||
>
|
||||
<span className="min-w-0 truncate">{formatGymEquipment(e)}</span>
|
||||
<>
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
{gym.equipment.map((e) => {
|
||||
const hasPhotos = (e.photos?.length ?? 0) > 0;
|
||||
const content = (
|
||||
<>
|
||||
{hasPhotos ? (
|
||||
<AuthImage
|
||||
src={e.photos![0].url}
|
||||
alt={e.equipment.name}
|
||||
className="h-9 w-9 shrink-0 rounded-[8px] border border-line object-cover"
|
||||
/>
|
||||
) : (
|
||||
<Dumbbell className="h-4 w-4 shrink-0 text-dim" aria-hidden="true" />
|
||||
)}
|
||||
<span className="min-w-0 truncate">{formatGymEquipment(e)}</span>
|
||||
</>
|
||||
);
|
||||
return hasPhotos ? (
|
||||
<button
|
||||
key={e.id}
|
||||
type="button"
|
||||
onClick={() => setPreview(e)}
|
||||
aria-label={`Zdjęcia: ${e.equipment.name}`}
|
||||
className="flex cursor-pointer items-center gap-2 rounded-[10px] border border-line bg-card/50 px-3 py-2.5 text-left text-[0.85rem] font-semibold hover:border-accent/55"
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
) : (
|
||||
<div
|
||||
key={e.id}
|
||||
className="flex items-center gap-2 rounded-[10px] border border-line bg-card/50 px-3 py-2.5 text-[0.85rem] font-semibold"
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Modal
|
||||
open={preview != null}
|
||||
onClose={() => setPreview(null)}
|
||||
title={preview ? `Zdjęcia: ${preview.equipment.name}` : ''}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{photos.map((p) => (
|
||||
<AuthImage
|
||||
key={p.id}
|
||||
src={p.url}
|
||||
alt={preview?.equipment.name ?? ''}
|
||||
className="w-full rounded-[10px] border border-line object-cover"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -398,9 +445,7 @@ export default function GymDetail() {
|
||||
id: 'announcements',
|
||||
label: 'Ogłoszenia',
|
||||
icon: Megaphone,
|
||||
actions: [
|
||||
{ label: 'Ogłoszenia', onClick: () => setAnnouncementsOpen(true) },
|
||||
],
|
||||
actions: [{ label: 'Ogłoszenia', onClick: () => setAnnouncementsOpen(true) }],
|
||||
},
|
||||
...(gym.kind === 'VIRTUAL' && gym.isPrivate
|
||||
? [
|
||||
@@ -601,12 +646,7 @@ export default function GymDetail() {
|
||||
{/* MODALE właściciela (otwierane z grup menu kontekstowego) */}
|
||||
{gym && (
|
||||
<>
|
||||
<Modal
|
||||
wide
|
||||
open={editOpen}
|
||||
onClose={() => setEditOpen(false)}
|
||||
title="Informacje"
|
||||
>
|
||||
<Modal wide open={editOpen} onClose={() => setEditOpen(false)} title="Informacje">
|
||||
<GymEditForm
|
||||
key={gym.id}
|
||||
gym={gym}
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
import { useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
addEquipmentPhotos,
|
||||
addGymEquipment,
|
||||
deleteEquipmentPhoto,
|
||||
removeGymEquipment,
|
||||
updateGym,
|
||||
updateGymEquipmentQuantity,
|
||||
updateGymEquipment,
|
||||
useEquipment,
|
||||
} from '../../api/queries';
|
||||
import type { Availability, Gym } from '../../api/types';
|
||||
import { formatEquipmentSpec, formatGymEquipment } from '../../lib/equipment';
|
||||
import type { Availability, Equipment, EquipmentSpec, Gym, GymEquipment } from '../../api/types';
|
||||
import {
|
||||
EMPTY_SPEC_FIELDS,
|
||||
LOAD_RANGE_KINDS,
|
||||
MAX_LOAD_KINDS,
|
||||
formatEquipmentSpec,
|
||||
formatGymEquipment,
|
||||
hasSpecFields,
|
||||
specFieldsFrom,
|
||||
specFromFields,
|
||||
type SpecFields,
|
||||
} from '../../lib/equipment';
|
||||
import { Button, Chip, Field, Input, Loading, SectionHeader, Select } from '../../components/ui';
|
||||
import { AuthImage } from '../../components/AuthImage';
|
||||
import { useToast } from '../../components/toast';
|
||||
import { AvailabilityEditor } from '../../components/AvailabilityEditor';
|
||||
import { AddressFields, addressPayload, isAddressComplete } from '../../components/AddressFields';
|
||||
@@ -122,17 +135,160 @@ export function GymEditForm({ gym, onSaved }: { gym: Gym; onSaved: () => void })
|
||||
);
|
||||
}
|
||||
|
||||
/** Zarządzanie urządzeniami siłowni (katalog + ilości + usuwanie). */
|
||||
const MAX_EQUIPMENT_PHOTO_FILES = 5;
|
||||
const MAX_EQUIPMENT_PHOTO_SIZE = 5 * 1024 * 1024;
|
||||
const EQUIPMENT_PHOTO_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
|
||||
|
||||
/** Wybór plików zdjęć urządzeń (jpeg/png/webp, ≤5 × 5 MB) z walidacją po stronie klienta. */
|
||||
function PhotoPicker({
|
||||
files,
|
||||
onChange,
|
||||
label,
|
||||
}: {
|
||||
files: File[];
|
||||
onChange: (files: File[]) => void;
|
||||
label: string;
|
||||
}) {
|
||||
const { push } = useToast();
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
aria-label={label}
|
||||
className="text-[0.8125rem] text-dim"
|
||||
onChange={(e) => {
|
||||
const picked = Array.from(e.target.files ?? []);
|
||||
e.target.value = '';
|
||||
if (picked.length === 0) return;
|
||||
if (files.length + picked.length > MAX_EQUIPMENT_PHOTO_FILES) {
|
||||
push(`Maksymalnie ${MAX_EQUIPMENT_PHOTO_FILES} zdjęć na urządzenie`, 'error');
|
||||
return;
|
||||
}
|
||||
if (picked.some((f) => !EQUIPMENT_PHOTO_TYPES.includes(f.type))) {
|
||||
push('Dozwolone formaty: JPG, PNG, WebP', 'error');
|
||||
return;
|
||||
}
|
||||
if (picked.some((f) => f.size > MAX_EQUIPMENT_PHOTO_SIZE)) {
|
||||
push('Maksymalny rozmiar zdjęcia to 5 MB', 'error');
|
||||
return;
|
||||
}
|
||||
onChange([...files, ...picked]);
|
||||
}}
|
||||
/>
|
||||
{files.length > 0 && (
|
||||
<span className="text-[0.8125rem] text-dim">{files.map((f) => f.name).join(', ')}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Pola specyfikacji zależne od rodzaju urządzenia (zakres kg / maks. obciążenie / cardio). */
|
||||
function SpecFieldsEditor({
|
||||
kind,
|
||||
values,
|
||||
onChange,
|
||||
}: {
|
||||
kind: Equipment['kind'];
|
||||
values: SpecFields;
|
||||
onChange: (patch: Partial<SpecFields>) => void;
|
||||
}) {
|
||||
if (LOAD_RANGE_KINDS.includes(kind)) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
|
||||
<Field label="Min. obciążenie (kg)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={500}
|
||||
step="any"
|
||||
aria-label="Min. obciążenie (kg)"
|
||||
value={values.minKg}
|
||||
onChange={(e) => onChange({ minKg: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Max. obciążenie (kg)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={500}
|
||||
step="any"
|
||||
aria-label="Max. obciążenie (kg)"
|
||||
value={values.maxKg}
|
||||
onChange={(e) => onChange({ maxKg: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (MAX_LOAD_KINDS.includes(kind)) {
|
||||
return (
|
||||
<Field label="Maksymalne obciążenie (kg)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={1000}
|
||||
step="any"
|
||||
aria-label="Maksymalne obciążenie (kg)"
|
||||
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="Maks. prędkość (km/h)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={50}
|
||||
step="any"
|
||||
aria-label="Maks. prędkość (km/h)"
|
||||
value={values.maxSpeedKmh}
|
||||
onChange={(e) => onChange({ maxSpeedKmh: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Maks. nachylenie (%)">
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
max={40}
|
||||
step="any"
|
||||
aria-label="Maks. nachylenie (%)"
|
||||
value={values.maxInclinePct}
|
||||
onChange={(e) => onChange({ maxInclinePct: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Zarządzanie urządzeniami siłowni: instancje (katalog + parametry + ilość) + zdjęcia. */
|
||||
export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
const queryClient = useQueryClient();
|
||||
const { push } = useToast();
|
||||
const { data: eqData, isLoading } = useEquipment();
|
||||
const catalog = eqData?.equipment ?? [];
|
||||
const quantities = new Map(gym.equipment.map((e) => [e.equipmentId, e.quantity]));
|
||||
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [addId, setAddId] = useState('');
|
||||
const [addQty, setAddQty] = useState('1');
|
||||
const [addCustom, setAddCustom] = useState(false);
|
||||
const [addFields, setAddFields] = useState<SpecFields>(EMPTY_SPEC_FIELDS);
|
||||
const [addFiles, setAddFiles] = useState<File[]>([]);
|
||||
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editCustom, setEditCustom] = useState(false);
|
||||
const [editFields, setEditFields] = useState<SpecFields>(EMPTY_SPEC_FIELDS);
|
||||
const [editFiles, setEditFiles] = useState<File[]>([]);
|
||||
const [savingEdit, setSavingEdit] = useState(false);
|
||||
|
||||
const addItem = catalog.find((e) => e.id === addId) ?? null;
|
||||
|
||||
const invalidate = () =>
|
||||
Promise.all([
|
||||
@@ -140,21 +296,45 @@ export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
queryClient.invalidateQueries({ queryKey: ['gym', gym.id] }),
|
||||
]);
|
||||
|
||||
const selectAdd = (id: string) => {
|
||||
setAddId(id);
|
||||
const item = catalog.find((e) => e.id === id);
|
||||
setAddFields(item ? specFieldsFrom(item.spec) : EMPTY_SPEC_FIELDS);
|
||||
setAddCustom(false);
|
||||
};
|
||||
|
||||
const add = async () => {
|
||||
if (!addId) return;
|
||||
if (!addItem) return;
|
||||
const quantity = parseInt(addQty, 10) || 1;
|
||||
let spec: EquipmentSpec | null = null;
|
||||
if (addCustom && hasSpecFields(addItem.kind)) {
|
||||
const result = specFromFields(addItem.kind, addFields);
|
||||
if ('error' in result) {
|
||||
push(result.error, 'error');
|
||||
return;
|
||||
}
|
||||
if (result.spec == null) {
|
||||
push('Uzupełnij parametry lub wyłącz ich własną wartość.', 'error');
|
||||
return;
|
||||
}
|
||||
spec = result.spec;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const existing = quantities.get(addId);
|
||||
if (existing != null) {
|
||||
await updateGymEquipmentQuantity(gym.id, addId, existing + quantity);
|
||||
push(`Dodano ${quantity} szt. (łącznie ${existing + quantity})`, 'success');
|
||||
} else {
|
||||
await addGymEquipment(gym.id, addId, quantity);
|
||||
push('Sprzęt dodany', 'success');
|
||||
const { instance } = await addGymEquipment(gym.id, addItem.id, quantity, spec);
|
||||
if (addFiles.length > 0) {
|
||||
try {
|
||||
await addEquipmentPhotos(gym.id, instance.id, addFiles);
|
||||
} catch {
|
||||
push('Urządzenie dodane, ale nie udało się wgrać zdjęć', 'error');
|
||||
}
|
||||
}
|
||||
push('Sprzęt dodany', 'success');
|
||||
setAddId('');
|
||||
setAddQty('1');
|
||||
setAddCustom(false);
|
||||
setAddFields(EMPTY_SPEC_FIELDS);
|
||||
setAddFiles([]);
|
||||
await invalidate();
|
||||
} catch (err) {
|
||||
push((err as Error).message, 'error');
|
||||
@@ -163,18 +343,19 @@ export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
}
|
||||
};
|
||||
|
||||
const changeQty = async (equipmentId: string, quantity: number) => {
|
||||
const changeQty = async (instanceId: string, quantity: number) => {
|
||||
try {
|
||||
await updateGymEquipmentQuantity(gym.id, equipmentId, quantity);
|
||||
await updateGymEquipment(gym.id, instanceId, { quantity });
|
||||
await invalidate();
|
||||
} catch (err) {
|
||||
push((err as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (equipmentId: string, name: string) => {
|
||||
const remove = async (instanceId: string, name: string) => {
|
||||
try {
|
||||
await removeGymEquipment(gym.id, equipmentId);
|
||||
await removeGymEquipment(gym.id, instanceId);
|
||||
if (editingId === instanceId) closeEdit();
|
||||
await invalidate();
|
||||
push(`Usunięto: ${name}`, 'success');
|
||||
} catch (err) {
|
||||
@@ -182,11 +363,78 @@ export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
}
|
||||
};
|
||||
|
||||
const editing = gym.equipment.find((e) => e.id === editingId) ?? null;
|
||||
|
||||
const openEdit = (ge: GymEquipment) => {
|
||||
setEditingId(ge.id);
|
||||
setEditCustom(ge.spec != null);
|
||||
setEditFields(specFieldsFrom(ge.spec ?? ge.equipment.spec));
|
||||
setEditFiles([]);
|
||||
};
|
||||
|
||||
const closeEdit = () => {
|
||||
setEditingId(null);
|
||||
setEditFiles([]);
|
||||
};
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!editing) return;
|
||||
let specBody: EquipmentSpec | null | undefined;
|
||||
if (editCustom && hasSpecFields(editing.equipment.kind)) {
|
||||
const result = specFromFields(editing.equipment.kind, editFields);
|
||||
if ('error' in result) {
|
||||
push(result.error, 'error');
|
||||
return;
|
||||
}
|
||||
if (result.spec == null) {
|
||||
push('Uzupełnij parametry lub wróć do specyfikacji katalogu.', 'error');
|
||||
return;
|
||||
}
|
||||
specBody = result.spec;
|
||||
} else if (!editCustom && editing.spec != null) {
|
||||
specBody = null;
|
||||
}
|
||||
setSavingEdit(true);
|
||||
try {
|
||||
if (specBody !== undefined) {
|
||||
await updateGymEquipment(gym.id, editing.id, { spec: specBody });
|
||||
}
|
||||
if (editFiles.length > 0) {
|
||||
try {
|
||||
await addEquipmentPhotos(gym.id, editing.id, editFiles);
|
||||
} catch {
|
||||
push('Nie udało się wgrać zdjęć', 'error');
|
||||
}
|
||||
}
|
||||
push('Zapisano zmiany', 'success');
|
||||
closeEdit();
|
||||
await invalidate();
|
||||
} catch (err) {
|
||||
push((err as Error).message, 'error');
|
||||
} finally {
|
||||
setSavingEdit(false);
|
||||
}
|
||||
};
|
||||
|
||||
const removePhoto = async (ge: GymEquipment, photoId: string) => {
|
||||
try {
|
||||
await deleteEquipmentPhoto(gym.id, ge.id, photoId);
|
||||
await invalidate();
|
||||
} catch (err) {
|
||||
push((err as Error).message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const totalQty = (equipmentId: string) =>
|
||||
gym.equipment
|
||||
.filter((e) => e.equipmentId === equipmentId)
|
||||
.reduce((sum, e) => sum + e.quantity, 0);
|
||||
|
||||
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ść."
|
||||
description="Maszyny i urządzenia dostępne w tej siłowni (z katalogu). Każde dodanie tworzy osobną pozycję — możesz ustawić jej parametry (np. stały ciężar lub zakres regulacji) i dodać zdjęcia. Kliknij pozycję, aby ją edytować."
|
||||
/>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{gym.equipment.length === 0 && (
|
||||
@@ -195,10 +443,25 @@ export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
{gym.equipment.map((e) => (
|
||||
<Chip
|
||||
key={e.id}
|
||||
onRemove={() => remove(e.equipmentId, e.equipment.name)}
|
||||
onRemove={() => remove(e.id, e.equipment.name)}
|
||||
removeLabel={`Usuń ${e.equipment.name}`}
|
||||
className={editingId === e.id ? 'border-accent' : undefined}
|
||||
>
|
||||
{formatGymEquipment(e)}
|
||||
{e.photos && e.photos.length > 0 && (
|
||||
<AuthImage
|
||||
src={e.photos[0].url}
|
||||
alt={e.equipment.name}
|
||||
className="h-6 w-6 rounded-full object-cover"
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (editingId === e.id ? closeEdit() : openEdit(e))}
|
||||
aria-label={`Edytuj ${e.equipment.name}`}
|
||||
className="cursor-pointer text-inherit hover:text-accent-text"
|
||||
>
|
||||
{formatGymEquipment(e)}
|
||||
</button>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
@@ -209,7 +472,7 @@ export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
onBlur={(ev) => {
|
||||
const value = parseInt(ev.target.value, 10);
|
||||
if (Number.isFinite(value) && value >= 1 && value !== e.quantity) {
|
||||
void changeQty(e.equipmentId, value);
|
||||
void changeQty(e.id, value);
|
||||
} else {
|
||||
ev.target.value = String(e.quantity);
|
||||
}
|
||||
@@ -221,22 +484,109 @@ export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
{editing && (
|
||||
<div className="mt-4 rounded-[10px] border border-line bg-card/50 p-3">
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<span className="font-display text-[0.9rem] font-bold">
|
||||
{editing.equipment.name} — edycja
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={closeEdit}
|
||||
aria-label="Zamknij edycję"
|
||||
className="text-[0.8125rem] text-dim hover:text-ink cursor-pointer"
|
||||
>
|
||||
Zamknij
|
||||
</button>
|
||||
</div>
|
||||
{hasSpecFields(editing.equipment.kind) && (
|
||||
<div className="mb-3">
|
||||
<label className="mb-2 flex cursor-pointer items-center gap-2 text-[0.875rem]">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={editCustom}
|
||||
onChange={(e) => setEditCustom(e.target.checked)}
|
||||
className="h-4 w-4 accent-accent"
|
||||
/>
|
||||
Własne parametry (domyślne: {formatEquipmentSpec(editing.equipment.spec) ?? 'brak'})
|
||||
</label>
|
||||
{editCustom && (
|
||||
<SpecFieldsEditor
|
||||
kind={editing.equipment.kind}
|
||||
values={editFields}
|
||||
onChange={(patch) => setEditFields({ ...editFields, ...patch })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-3">
|
||||
<div className="mb-1.5 text-[0.8125rem] font-semibold text-dim">
|
||||
Zdjęcia ({editing.photos?.length ?? 0}/{MAX_EQUIPMENT_PHOTO_FILES})
|
||||
</div>
|
||||
{editing.photos && editing.photos.length > 0 && (
|
||||
<div className="mb-2 flex flex-wrap gap-2">
|
||||
{editing.photos.map((p) => (
|
||||
<span key={p.id} className="relative inline-block">
|
||||
<AuthImage
|
||||
src={p.url}
|
||||
alt={editing.equipment.name}
|
||||
className="h-16 w-16 rounded-[8px] border border-line object-cover"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void removePhoto(editing, p.id)}
|
||||
aria-label="Usuń zdjęcie"
|
||||
className="absolute -top-1.5 -right-1.5 grid h-5 w-5 place-items-center rounded-full border border-line bg-card text-danger cursor-pointer"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{(editing.photos?.length ?? 0) < MAX_EQUIPMENT_PHOTO_FILES && (
|
||||
<PhotoPicker
|
||||
files={editFiles}
|
||||
onChange={setEditFiles}
|
||||
label="Dodaj zdjęcia urządzenia"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="sm" onClick={saveEdit} disabled={savingEdit}>
|
||||
{savingEdit ? 'Zapisywanie…' : 'Zapisz'}
|
||||
</Button>
|
||||
{editCustom && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setEditCustom(false);
|
||||
setEditFields(specFieldsFrom(editing.equipment.spec));
|
||||
}}
|
||||
>
|
||||
Przywróć katalog
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
<Select
|
||||
value={addId}
|
||||
onChange={(e) => setAddId(e.target.value)}
|
||||
onChange={(e) => selectAdd(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 qty = totalQty(e.id);
|
||||
const spec = formatEquipmentSpec(e.spec);
|
||||
return (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.name}
|
||||
{spec ? ` · ${spec}` : ''}
|
||||
{qty != null ? ` (${qty} szt.)` : ''}
|
||||
{qty > 0 ? ` (${qty} szt.)` : ''}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
@@ -254,6 +604,31 @@ export function EquipmentSection({ gym }: { gym: Gym }) {
|
||||
{busy ? 'Dodawanie…' : 'Dodaj'}
|
||||
</Button>
|
||||
</div>
|
||||
{addItem && hasSpecFields(addItem.kind) && (
|
||||
<div className="mt-3">
|
||||
<label className="mb-2 flex cursor-pointer items-center gap-2 text-[0.875rem]">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={addCustom}
|
||||
onChange={(e) => setAddCustom(e.target.checked)}
|
||||
className="h-4 w-4 accent-accent"
|
||||
/>
|
||||
Ustaw własne parametry (domyślne: {formatEquipmentSpec(addItem.spec) ?? 'brak'})
|
||||
</label>
|
||||
{addCustom && (
|
||||
<SpecFieldsEditor
|
||||
kind={addItem.kind}
|
||||
values={addFields}
|
||||
onChange={(patch) => setAddFields({ ...addFields, ...patch })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{addItem && (
|
||||
<div className="mt-3">
|
||||
<PhotoPicker files={addFiles} onChange={setAddFiles} label="Zdjęcia urządzenia" />
|
||||
</div>
|
||||
)}
|
||||
{isLoading && <Loading />}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -114,7 +114,7 @@ test('właściciel ma menu „Siłownie" i zarządza swoją siłownią', async (
|
||||
await expect(page.getByText('Wyjątek dodany')).toBeVisible();
|
||||
});
|
||||
|
||||
test('właściciel może zwiększyć ilość już dodanego sprzętu', async ({ page }) => {
|
||||
test('ponowne dodanie tego samego typu tworzy osobną instancję urządzenia', async ({ page }) => {
|
||||
mockApi(page);
|
||||
await page.goto('/login');
|
||||
await page.locator('input[type="email"]').fill('test@fitos.pl');
|
||||
@@ -130,8 +130,80 @@ test('właściciel może zwiększyć ilość już dodanego sprzętu', async ({ p
|
||||
// zarządzanie sprzętem z menu kontekstowego (grupa „Urządzenia” → modal)
|
||||
await page.locator('button[data-slot="button"]', { hasText: 'Urządzenia' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
// select pokazuje cały katalog — ponowne dodanie zwiększa ilość
|
||||
// każde dodanie = NOWA instancja (osobny chip), bez inkrementacji ilości
|
||||
await dialog.getByLabel('Dodaj urządzenie').selectOption('eq-2');
|
||||
await dialog.getByRole('button', { name: 'Dodaj', exact: true }).click();
|
||||
await expect(dialog.getByText('Hantle ×3 · 2.5–25 kg', { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText('Hantle · 2.5–25 kg', { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText('Hantle ×2 · 2.5–25 kg', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('właściciel może zmienić ilość instancji urządzenia', async ({ page }) => {
|
||||
mockApi(page);
|
||||
await page.goto('/login');
|
||||
await page.locator('input[type="email"]').fill('test@fitos.pl');
|
||||
await page.locator('input[type="password"]').fill('haslo123');
|
||||
await page.getByRole('button', { name: 'Zaloguj' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
|
||||
|
||||
await page.getByRole('link', { name: 'Siłownie' }).click();
|
||||
await page.getByRole('link', { name: 'Żelazna Świątynia' }).click();
|
||||
await page.locator('button[data-slot="button"]', { hasText: 'Urządzenia' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
|
||||
await dialog.getByLabel('Ilość: Sztanga').fill('4');
|
||||
await dialog.getByLabel('Ilość: Sztanga').press('Enter');
|
||||
await expect(dialog.getByText('Sztanga ×4 · do 100 kg', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('właściciel może nadać instancji własne parametry (nadpisanie speca)', async ({ page }) => {
|
||||
mockApi(page);
|
||||
await page.goto('/login');
|
||||
await page.locator('input[type="email"]').fill('test@fitos.pl');
|
||||
await page.locator('input[type="password"]').fill('haslo123');
|
||||
await page.getByRole('button', { name: 'Zaloguj' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
|
||||
|
||||
await page.getByRole('link', { name: 'Siłownie' }).click();
|
||||
await page.getByRole('link', { name: 'Żelazna Świątynia' }).click();
|
||||
await page.locator('button[data-slot="button"]', { hasText: 'Urządzenia' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
|
||||
// panel edycji instancji Hantle: własny zakres 5–5 kg = ciężar stały „5 kg”
|
||||
await dialog.getByRole('button', { name: 'Edytuj Hantle' }).click();
|
||||
await dialog.getByRole('checkbox', { name: /Własne parametry/ }).check();
|
||||
await dialog.getByLabel('Min. obciążenie (kg)').fill('5');
|
||||
await dialog.getByLabel('Max. obciążenie (kg)').fill('5');
|
||||
await dialog.getByRole('button', { name: 'Zapisz' }).click();
|
||||
await expect(dialog.getByText('Hantle ×2 · 5 kg', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('właściciel może dodać zdjęcie do urządzenia', async ({ page }) => {
|
||||
mockApi(page);
|
||||
await page.goto('/login');
|
||||
await page.locator('input[type="email"]').fill('test@fitos.pl');
|
||||
await page.locator('input[type="password"]').fill('haslo123');
|
||||
await page.getByRole('button', { name: 'Zaloguj' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
|
||||
|
||||
await page.getByRole('link', { name: 'Siłownie' }).click();
|
||||
await page.getByRole('link', { name: 'Żelazna Świątynia' }).click();
|
||||
await page.locator('button[data-slot="button"]', { hasText: 'Urządzenia' }).click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
|
||||
const png = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
);
|
||||
await dialog.getByRole('button', { name: 'Edytuj Sztanga' }).click();
|
||||
await dialog.getByLabel('Dodaj zdjęcia urządzenia').setInputFiles({
|
||||
name: 'sztanga.png',
|
||||
mimeType: 'image/png',
|
||||
buffer: png,
|
||||
});
|
||||
await dialog.getByRole('button', { name: 'Zapisz' }).click();
|
||||
|
||||
// miniatura na chipie + ponowne otwarcie panelu pokazuje licznik zdjęcia
|
||||
await expect(dialog.locator('img[alt="Sztanga"]')).toBeVisible();
|
||||
await dialog.getByRole('button', { name: 'Edytuj Sztanga' }).click();
|
||||
await expect(dialog.getByText('Zdjęcia (1/5)')).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -917,7 +917,14 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
} = opts;
|
||||
|
||||
// Stateful: equipment added via POST /gyms/:id/equipment persists on refetch.
|
||||
const ownedGymEquipment = [...TEST_GYM_OWNED.equipment];
|
||||
// Instancje (GymEquipment.id) — powtórne dodanie typu = NOWA instancja.
|
||||
const ownedGymEquipment = TEST_GYM_OWNED.equipment.map((e) => ({
|
||||
...e,
|
||||
spec: null,
|
||||
photos: [] as { id: string; url: string; createdAt: string }[],
|
||||
}));
|
||||
let eqInstanceSeq = ownedGymEquipment.length;
|
||||
let eqPhotoSeq = 0;
|
||||
const myGymsBody = myGyms ?? { gyms: [{ ...TEST_GYM_OWNED, equipment: ownedGymEquipment }] };
|
||||
|
||||
// Stateful: komentarze pod ćwiczeniami — dodane przez POST widoczne po refetch historii.
|
||||
@@ -1119,11 +1126,12 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
|
||||
page.route('**/api/v1/gyms/*/equipment/*', (route) => {
|
||||
const req = route.request();
|
||||
const eqId = req.url().match(/equipment\/([^/]+)$/)?.[1];
|
||||
const instanceId = req.url().match(/equipment\/([^/]+)$/)?.[1];
|
||||
if (req.method() === 'PATCH') {
|
||||
const body = JSON.parse(req.postData() || '{}');
|
||||
const link = ownedGymEquipment.find((e) => e.equipmentId === eqId);
|
||||
const link = ownedGymEquipment.find((e) => e.id === instanceId);
|
||||
if (link && typeof body.quantity === 'number') link.quantity = body.quantity;
|
||||
if (link && 'spec' in body) link.spec = body.spec ?? null;
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
@@ -1131,7 +1139,7 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
});
|
||||
}
|
||||
if (req.method() === 'DELETE') {
|
||||
const idx = ownedGymEquipment.findIndex((e) => e.equipmentId === eqId);
|
||||
const idx = ownedGymEquipment.findIndex((e) => e.id === instanceId);
|
||||
if (idx >= 0) ownedGymEquipment.splice(idx, 1);
|
||||
return route.fulfill({ status: 204 });
|
||||
}
|
||||
@@ -1143,19 +1151,27 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
if (req.method() === 'POST') {
|
||||
const body = JSON.parse(req.postData() || '{}');
|
||||
const added = TEST_EQUIPMENT.find((e) => e.id === body.equipmentId);
|
||||
if (added && !ownedGymEquipment.some((e) => e.equipmentId === added.id)) {
|
||||
if (added) {
|
||||
// Każde dodanie = nowa instancja (bez deduplikacji typu katalogowego).
|
||||
eqInstanceSeq += 1;
|
||||
ownedGymEquipment.push({
|
||||
id: `ge-${added.id}`,
|
||||
id: `ge-${eqInstanceSeq}`,
|
||||
gymId: TEST_GYM_OWNED.id,
|
||||
equipmentId: added.id,
|
||||
quantity: body.quantity ?? 1,
|
||||
spec: body.spec ?? null,
|
||||
photos: [],
|
||||
equipment: added,
|
||||
});
|
||||
}
|
||||
const instance = ownedGymEquipment[ownedGymEquipment.length - 1];
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment } }),
|
||||
body: JSON.stringify({
|
||||
gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment },
|
||||
instance: added ? instance : undefined,
|
||||
}),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
@@ -1296,6 +1312,49 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
return route.fulfill({ status: 200, contentType: 'image/png', body: Buffer.from(TINY_PNG, 'base64') });
|
||||
});
|
||||
|
||||
// ---------- zdjęcia instancji urządzeń (max 5 per instancja) ----------
|
||||
const eqGymBody = () =>
|
||||
JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment } });
|
||||
|
||||
page.route('**/api/v1/gyms/*/equipment/*/photos', (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() !== 'POST') return route.fulfill({ status: 200, contentType: 'application/json', body: eqGymBody() });
|
||||
const instanceId = req.url().match(/equipment\/([^/]+)\/photos/)?.[1];
|
||||
const link = ownedGymEquipment.find((e) => e.id === instanceId);
|
||||
const raw = req.postData() || '';
|
||||
const count = (raw.match(/name="photos"/g) || []).length;
|
||||
if (link) {
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
if (link.photos.length >= 5) break;
|
||||
eqPhotoSeq += 1;
|
||||
const photoId = `ep-${eqPhotoSeq}`;
|
||||
link.photos.push({
|
||||
id: photoId,
|
||||
url: `/gyms/${TEST_GYM_OWNED.id}/equipment/${instanceId}/photos/${photoId}`,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: eqGymBody() });
|
||||
});
|
||||
|
||||
page.route('**/api/v1/gyms/*/equipment/*/photos/*', (route) => {
|
||||
const req = route.request();
|
||||
const url = req.url();
|
||||
const instanceId = url.match(/equipment\/([^/]+)\/photos\//)?.[1];
|
||||
const photoId = url.match(/photos\/([^/?]+)$/)?.[1];
|
||||
if (req.method() === 'DELETE') {
|
||||
const link = ownedGymEquipment.find((e) => e.id === instanceId);
|
||||
if (link) {
|
||||
const idx = link.photos.findIndex((p) => p.id === photoId);
|
||||
if (idx >= 0) link.photos.splice(idx, 1);
|
||||
}
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: eqGymBody() });
|
||||
}
|
||||
// GET — serwowanie pliku zdjęcia urządzenia.
|
||||
return route.fulfill({ status: 200, contentType: 'image/png', body: Buffer.from(TINY_PNG, 'base64') });
|
||||
});
|
||||
|
||||
// ---------- virtual gyms (ratings) ----------
|
||||
page.route('**/api/v1/gyms/virtual', (route) =>
|
||||
route.fulfill({
|
||||
|
||||
Reference in New Issue
Block a user