Files
FitOS/admin/test/e2e/mock-api.ts

1040 lines
33 KiB
TypeScript

import type { Page } from '@playwright/test';
import type {
ActivityLog,
AdminAnnouncement,
Equipment,
Gym,
GymClaim,
User,
} from '../../src/api/types';
export const TEST_ADMIN = {
id: 'admin-test',
email: 'admin@fitos.pl',
firstName: 'Admin',
lastName: 'Test',
birthDate: null,
heightCm: null,
phone: null,
platformRoles: ['ADMIN'],
permissions: [
'users:read',
'users:manage',
'pii:read',
'roles:manage',
'catalog:manage',
'gyms:manage',
'announcements:manage',
'verifications:view',
'logs:view',
],
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-01-01T00:00:00.000Z',
};
export const TEST_EQUIPMENT: Equipment[] = [
{
id: 'eq-1',
name: 'Sztanga',
kind: 'BARBELL',
spec: { maxLoadKg: 100 },
description: 'Sztanga z talerzami.',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
exercisesCount: 3,
gymsCount: 2,
},
{
id: 'eq-2',
name: 'Dywan',
kind: 'OTHER',
spec: null,
description: 'Dywan do ćwiczeń.',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
exercisesCount: 0,
gymsCount: 0,
},
];
export const TEST_GYM_PHOTOS = [
{
id: 'photo-1',
url: '/gyms/gym-1/photos/photo-1',
order: 0,
createdAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'photo-2',
url: '/gyms/gym-1/photos/photo-2',
order: 1,
createdAt: '2026-01-02T00:00:00.000Z',
},
];
export const TEST_GYM: Gym = {
id: 'gym-1',
name: 'Fit Factory',
location: 'Bobrowiecka 12, 02-847 Warszawa',
addressLine1: 'Bobrowiecka 12',
addressLine2: null,
postalCode: '02-847',
city: 'Warszawa',
countryCode: 'PL',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 120,
kind: 'REAL',
isPrivate: false,
equipment: [
{ id: 'ge-1', gymId: 'gym-1', equipmentId: 'eq-1', quantity: 1, equipment: TEST_EQUIPMENT[0] },
{ id: 'ge-2', gymId: 'gym-1', equipmentId: 'eq-2', quantity: 3, equipment: TEST_EQUIPMENT[1] },
],
coverPhoto: '/gyms/gym-1/photos/photo-1',
photos: TEST_GYM_PHOTOS,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-05T00:00:00.000Z',
_count: { memberships: 12 },
owners: [{ id: 'user-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' }],
};
export const TEST_GYM_2: Gym = {
id: 'gym-2',
name: 'Mega Gym',
location: 'Kraków',
availability: null,
capacity: null,
kind: 'REAL',
isPrivate: false,
equipment: [],
coverPhoto: null,
createdAt: '2026-02-01T00:00:00.000Z',
updatedAt: '2026-02-05T00:00:00.000Z',
_count: { memberships: 4 },
owners: [],
};
/** Właściciele (OWNER) siłowni gym-1 — tylko w odpowiedzi GET /admin/gyms/gym-1. */
export const TEST_GYM_OWNERS = [
{ id: 'user-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' },
];
/** Członkowie siłowni gym-1 — GET /admin/gyms/gym-1/members (tabela w konsoli detalu). */
export const TEST_GYM_MEMBERS = [
{
membershipId: 'membership-1',
roles: ['OWNER'],
roleKeys: ['GYM_OWNER'],
joinedAt: '2026-01-02T10:00:00.000Z',
checkedInNow: false,
user: {
id: 'user-owner',
firstName: 'Anna',
lastName: 'Kowalska',
email: 'anna@fitos.pl',
status: 'ACTIVE',
},
},
{
membershipId: 'membership-2',
roles: ['MEMBER', 'TRAINER'],
roleKeys: ['GYM_TRAINER'],
joinedAt: '2026-02-01T10:00:00.000Z',
checkedInNow: true,
user: {
id: 'user-1',
firstName: 'Jan',
lastName: 'Kowalski',
email: 'jan@fitos.pl',
status: 'ACTIVE',
},
},
];
/** Katalog ról gymowych siłowni gym-1 — GET /admin/gyms/gym-1/roles (RBAC faza 2). */
export const TEST_GYM_ROLES = [
{
id: 'role-gym-owner',
key: 'GYM_OWNER',
name: 'Właściciel',
permissions: [
'gym:edit',
'gym:members',
'gym:delegate',
'gym:equipment',
'gym:gallery',
'gym:announcements',
'gym:exceptions',
'gym:contact',
'gym:stats',
'gym:delete',
],
isSystem: true,
grantCount: 1,
},
{
id: 'role-gym-trainer',
key: 'GYM_TRAINER',
name: 'Trener',
permissions: ['trainer:clients'],
isSystem: true,
grantCount: 1,
},
];
/** Wniosek o weryfikację wirtualnej siłowni (PENDING, z dokumentem). */
export const TEST_CLAIM_VERIFICATION: GymClaim = {
id: 'claim-v1',
gymId: 'gym-v1',
type: 'verification',
gym: { id: 'gym-v1', name: 'Wirtualna Alfa', kind: 'VIRTUAL', isPrivate: true },
gymName: null,
gymLocation: null,
gymAvailability: null,
gymCapacity: null,
description: 'Prowadzę tę siłownię od 2020 roku.',
companyName: 'Alfa Sp. z o.o.',
nip: '1234567890',
phone: '+48 600 100 200',
email: 'alfa@fitos.pl',
address: 'ul. Morska 1, Gdynia',
status: 'PENDING',
rejectReason: null,
decidedAt: null,
createdAt: '2026-08-25T10:00:00.000Z',
user: {
id: 'user-v1',
firstName: 'Marek',
lastName: 'Wirtualny',
email: 'alfa@fitos.pl',
phone: '+48 600 100 200',
},
documentCount: 1,
documents: [
{
id: 'doc-v1',
originalName: 'akt-y.pdf',
mimeType: 'application/pdf',
sizeBytes: 1024,
createdAt: '2026-08-25T10:00:00.000Z',
},
],
};
/** Wniosek o nową realną siłownię (PENDING). */
export const TEST_CLAIM_NEW: GymClaim = {
id: 'claim-n1',
gymId: null,
type: 'new',
gym: null,
gymName: 'Nowa Realna Siłownia',
gymLocation: 'ul. Długa 5, Warszawa',
gymAvailability: null,
gymCapacity: 40,
description: 'Nowa siłownia, otwieramy w październiku.',
companyName: null,
nip: null,
phone: '+48 700 300 400',
email: 'nowa@fitos.pl',
address: null,
status: 'PENDING',
rejectReason: null,
decidedAt: null,
createdAt: '2026-08-26T12:00:00.000Z',
user: {
id: 'user-n1',
firstName: 'Anna',
lastName: 'Nowa',
email: 'nowa@fitos.pl',
phone: '+48 700 300 400',
},
documentCount: 0,
documents: [],
};
export const TEST_USER: User = {
id: 'user-1',
email: 'jan@fitos.pl',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
socialMedia: null,
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: '+48 500 100 200',
platformRoles: [],
availability: null,
priorities: null,
exclusions: null,
developMuscles: ['chest'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: ['legs'],
status: 'ACTIVE',
suspensionUntil: null,
restrictionReason: null,
createdAt: '2026-01-01T00:00:00.000Z',
memberships: [{ gymId: 'gym-1', roles: ['MEMBER'], roleKeys: [], gym: TEST_GYM }],
};
export const TEST_EXERCISES = [
{
id: 'ex-1',
slug: 'bench-press',
name: 'Wyciskanie sztangi leżąc',
primaryMuscle: 'chest',
secondaryMuscles: ['triceps'],
equipment: [TEST_EQUIPMENT[0]],
hasReps: true,
hasLoad: true,
hasRest: true,
hasSets: true,
hasRir: true,
hasDifficulty: true,
hasCardio: false,
hasTime: false,
hasSpeed: false,
description: 'Podstawowe ćwiczenie na klatkę.',
howTo: null,
commonMistakes: null,
source: 'BUILTIN',
planExercisesCount: 1,
},
];
export const TEST_FOCUS_AREAS = [
{
id: 'fa-1',
name: 'Klatka piersiowa',
muscle: 'chest',
description: 'Wyciskanie, rozpiętki.',
exercisesCount: 1,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'fa-2',
name: 'Nogi',
muscle: 'legs',
description: 'Przysiady, wykroki.',
exercisesCount: 0,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
];
export const TEST_LOGS: ActivityLog[] = [
{
id: 'log-1',
action: 'plan.activated',
entityType: 'plan',
entityId: 'plan-1',
details: { actorId: 'user-1', title: 'Plan na masę', startDate: '2026-08-24' },
createdAt: '2026-08-20T10:00:00.000Z',
actor: { id: 'user-1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
},
{
id: 'log-2',
action: 'session.completed',
entityType: 'session',
entityId: 'session-1',
details: {
actorId: 'user-1',
dayId: 'day-1',
planId: 'plan-1',
planTitle: 'Plan na masę',
exercises: 4,
sets: 12,
},
createdAt: '2026-08-21T18:30:00.000Z',
actor: { id: 'user-1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
},
{
id: 'log-3',
action: 'weight.removed',
entityType: 'user',
entityId: 'user-1',
details: { actorId: 'user-1', value: 82.5 },
createdAt: '2026-08-22T09:00:00.000Z',
actor: { id: 'user-1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski' },
},
];
export interface MockApiOptions {
/** Status odpowiedzi POST /auth/login (domyślnie 200). */
loginStatus?: number;
/** Ciało odpowiedzi POST /auth/login. */
loginBody?: unknown;
/** Ciało odpowiedzi GET /admin/gyms. */
gyms?: unknown;
/** Ciało odpowiedzi GET /admin/users. */
users?: unknown;
/** Ciało odpowiedzi GET /admin/logs. */
logs?: unknown;
/** Ciało odpowiedzi GET /admin/users/:id/activity (historia konta). */
activity?: unknown;
/** Ciało odpowiedzi GET /admin/gyms/claims. */
claims?: unknown;
/** Startowy stan GET /admin/announcements (stateful CRUD w teście). */
announcements?: unknown;
}
/**
* Mockuje API pod /api/v1. Niezamockowane endpointy zwracają 200 z {}.
* Kolejność rejestracji jest ważna: fallback musi być pierwszy
* (Playwright dopasowuje route'y w odwrotnej kolejności rejestracji).
*/
export function mockApi(page: Page, opts: MockApiOptions = {}) {
const {
loginStatus = 200,
loginBody = { user: TEST_ADMIN, accessToken: 'test-access-token' },
gyms = { gyms: [] },
users = { users: [] },
logs = { logs: TEST_LOGS, total: TEST_LOGS.length },
activity = { logs: [], total: 0 },
claims = { claims: [] as GymClaim[] },
announcements = [] as AdminAnnouncement[],
} = opts;
// Stateful: claims persist across list/detail/approve/reject.
const claimsState: GymClaim[] = (claims as { claims: GymClaim[] }).claims.map((c) => ({ ...c }));
page.route('**/api/v1/**', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({}) }),
);
// Stateful: ogłoszenia (globalne + per-siłownia) — CRUD w ramach testu.
let announcementsState = JSON.parse(JSON.stringify(announcements)) as AdminAnnouncement[];
let announcementSeq = announcementsState.length;
page.route('**/api/v1/admin/announcements**', (route) => {
const req = route.request();
const url = new URL(req.url());
const method = req.method();
const id = url.pathname.split('/').at(-1);
const isCollection = id === 'announcements';
if (method === 'GET') {
const gymId = url.searchParams.get('gymId');
const items = gymId
? announcementsState.filter((a) => a.gymId === gymId)
: announcementsState;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ announcements: items }),
});
}
if (method === 'POST' && isCollection) {
const body = (req.postDataJSON() ?? {}) as {
title?: string;
body?: string;
gymId?: string | null;
};
const created: AdminAnnouncement = {
id: `ann-${++announcementSeq}`,
kind: 'MANUAL',
authorId: TEST_ADMIN.id,
gymId: body.gymId ?? null,
gymName:
body.gymId === TEST_GYM.id
? TEST_GYM.name
: body.gymId === TEST_GYM_2.id
? TEST_GYM_2.name
: null,
title: body.title ?? '',
body: body.body ?? '',
createdAt: new Date().toISOString(),
};
announcementsState = [...announcementsState, created];
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ announcement: created }),
});
}
const found = !isCollection ? announcementsState.find((a) => a.id === id) : undefined;
if (!found) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: JSON.stringify({ error: { message: 'Not found' } }),
});
}
if (method === 'PATCH') {
const patch = (req.postDataJSON() ?? {}) as { title?: string; body?: string };
const updated = { ...found, ...patch };
announcementsState = announcementsState.map((a) => (a.id === found.id ? updated : a));
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ announcement: updated }),
});
}
if (method === 'DELETE') {
announcementsState = announcementsState.filter((a) => a.id !== found.id);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405 });
});
page.route('**/api/v1/auth/refresh', (route) =>
route.fulfill({
status: 401,
contentType: 'application/json',
body: JSON.stringify({ error: { message: 'No session' } }),
}),
);
page.route('**/api/v1/auth/login', (route) =>
route.fulfill({
status: loginStatus,
contentType: 'application/json',
body: JSON.stringify(
loginBody ?? {
error: { code: 'INVALID_CREDENTIALS', message: 'Nieprawidłowy e-mail lub hasło' },
},
),
}),
);
page.route('**/api/v1/me', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ user: TEST_ADMIN, memberships: [] }),
}),
);
// Stateful: 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 }));
let photoSeq = TEST_GYM_PHOTOS.length;
// Stateful: właściciele siłowni gym-1 — nadawanie/odbieranie roli OWNER.
const gymOwnersState = TEST_GYM_OWNERS.map((o) => ({ ...o }));
// Stateful: członkowie gym-1 — menu członka (PUT ról z grantów / DELETE z powodem).
const membersState = TEST_GYM_MEMBERS.map((m) => ({
...m,
roles: [...m.roles],
roleKeys: [...m.roleKeys],
}));
// Wyprowadzenie DTO ról z kluczy grantów — tak samo jak w API (deriveMembershipRoles).
const deriveRoles = (keys: string[]): string[] => {
const out: string[] = [];
if (keys.includes('GYM_OWNER')) out.push('OWNER');
if (keys.includes('GYM_TRAINER')) out.push('TRAINER');
if (!out.includes('OWNER')) out.push('MEMBER');
return out;
};
// Stateful: katalog ról gymowych (GET/POST/PATCH/DELETE /admin/gyms/gym-1/roles).
const gymRolesState = TEST_GYM_ROLES.map((r) => ({
...r,
permissions: [...r.permissions],
}));
let gymRoleSeq = gymRolesState.length;
const coverOf = (photos: typeof gymPhotosState) =>
photos.length ? `/gyms/gym-1/photos/${photos[0].id}` : null;
const gymDetailBody = () =>
JSON.stringify({
...TEST_GYM,
equipment: gymEquipmentState,
photos: [...gymPhotosState],
owners: [...gymOwnersState],
coverPhoto: coverOf(gymPhotosState),
});
// Detal siłowni (GET /admin/gyms/gym-1) — pełna galeria (lista ma tylko okładkę).
page.route('**/api/v1/admin/gyms/gym-1', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() }),
);
// POST /gyms/gym-1/photos — upload (multipart, pole `photos`).
page.route('**/api/v1/gyms/*/photos', (route) => {
const req = route.request();
if (req.method() !== 'POST') {
return route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() });
}
const raw = req.postData() || '';
const count = (raw.match(/name="photos"/g) || []).length;
for (let i = 0; i < count; i += 1) {
photoSeq += 1;
gymPhotosState.push({
id: `photo-${photoSeq}`,
url: `/gyms/gym-1/photos/photo-${photoSeq}`,
order: gymPhotosState.length,
createdAt: new Date().toISOString(),
});
}
return route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() });
});
// /gyms/gym-1/photos/:photoId — DELETE / PATCH .../cover / GET (serwowanie obrazu).
page.route('**/api/v1/gyms/*/photos/*', (route) => {
const req = route.request();
const url = req.url();
const photoId = url.match(/photos\/([^/?]+)$/)?.[1];
if (req.method() === 'DELETE') {
const idx = gymPhotosState.findIndex((p) => p.id === photoId);
if (idx >= 0) gymPhotosState.splice(idx, 1);
gymPhotosState.forEach((p, i) => (p.order = i));
return route.fulfill({ status: 204 });
}
if (req.method() === 'PATCH' && url.endsWith('/cover')) {
const idx = gymPhotosState.findIndex((p) => p.id === photoId);
if (idx >= 0) {
const [moved] = gymPhotosState.splice(idx, 1);
gymPhotosState.unshift(moved);
gymPhotosState.forEach((p, i) => (p.order = i));
}
return route.fulfill({ status: 200, contentType: 'application/json', body: gymDetailBody() });
}
return route.fulfill({
status: 200,
contentType: 'image/png',
body: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
'base64',
),
});
});
// Lista siłowni (bez `/gym-1`) — wyszukiwanie i filtr `kind` po stronie „API”.
page.route(
(url) => /\/api\/v1\/admin\/gyms(\?.*)?$/.test(url.pathname + (url.search ?? '')),
(route) => {
const raw = (gyms as { gyms?: Array<Record<string, unknown>> } | null)?.gyms ?? [];
const params = new URL(route.request().url()).searchParams;
const q = (params.get('q') ?? '').trim().toLowerCase();
const kind = params.get('kind');
const filtered = raw.filter((g) => {
if (kind && g.kind !== kind) return false;
if (!q) return true;
const hay = [
String(g.name ?? ''),
String(g.location ?? ''),
String(g.city ?? ''),
String(g.addressLine1 ?? ''),
String(g.postalCode ?? ''),
...(Array.isArray(g.owners)
? (g.owners as Array<Record<string, unknown>>).flatMap((o) => [
String(o.firstName ?? ''),
String(o.lastName ?? ''),
String(o.email ?? ''),
])
: []),
]
.join(' ')
.toLowerCase();
return hay.includes(q);
});
const body =
gyms != null
? {
...gyms,
gyms: filtered.map((g) =>
g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g,
),
}
: gyms;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(body),
});
},
);
// Logi pojedynczej siłowni (GET /admin/gyms/:id/logs).
page.route('**/api/v1/admin/gyms/*/logs*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(logs),
}),
);
// Członkowie pojedynczej siłowni (GET /admin/gyms/:id/members) — q i role po stronie „API";
// role żyją w membersState (menu członka PATCH/DELETE aktualizuje je na bieżąco).
page.route('**/api/v1/admin/gyms/*/members*', (route) => {
const params = new URL(route.request().url()).searchParams;
const q = (params.get('q') ?? '').trim().toLowerCase();
const role = params.get('role');
const list = membersState.filter(
(m) =>
(!role || m.roles.includes(role)) &&
(!q ||
`${m.user.firstName ?? ''} ${m.user.lastName ?? ''} ${m.user.email}`
.toLowerCase()
.includes(q)),
);
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ members: list, total: list.length }),
});
});
// PUT ról członka z grantów (RBAC faza 2): roleKeys → wyprowadzone roles w membersState.
page.route('**/api/v1/admin/gyms/*/members/*/roles', (route) => {
const req = route.request();
if (req.method() !== 'PUT') return route.fulfill({ status: 405 });
const userId = decodeURIComponent(req.url().match(/members\/([^/?]+)\/roles/)?.[1] ?? '');
const body = JSON.parse(req.postData() || '{}');
const m = membersState.find((x) => x.user.id === userId);
if (m && Array.isArray(body.roleKeys)) {
m.roleKeys = body.roleKeys;
m.roles = deriveRoles(m.roleKeys);
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ roles: m?.roleKeys ?? [] }),
});
});
// Katalog ról gymowych (GET/POST /admin/gyms/:id/roles; PATCH/DELETE /roles/:roleId).
page.route('**/api/v1/admin/gyms/*/roles/*', (route) => {
const req = route.request();
const roleId = req.url().match(/roles\/([^/?]+)/)?.[1];
const role = gymRolesState.find((r) => r.id === roleId);
if (req.method() === 'PATCH') {
const body = JSON.parse(req.postData() || '{}');
if (role) {
if (typeof body.name === 'string') role.name = body.name;
if (Array.isArray(body.permissions)) role.permissions = body.permissions;
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ role: role ?? {} }),
});
}
if (req.method() === 'DELETE') {
const idx = gymRolesState.findIndex((r) => r.id === roleId);
if (idx >= 0) gymRolesState.splice(idx, 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405 });
});
page.route('**/api/v1/admin/gyms/*/roles', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = JSON.parse(req.postData() || '{}');
const created = {
id: `role-custom-${++gymRoleSeq}`,
key: `G_GYM1_CUSTOM_${gymRoleSeq}`,
name: body.name ?? '',
permissions: Array.isArray(body.permissions) ? body.permissions : [],
isSystem: false,
grantCount: 0,
};
gymRolesState.push(created);
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ role: created }),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ roles: gymRolesState }),
});
});
// Wnioski i zaproszenia pojedynczej siłowni (GET /admin/gyms/:id/related).
page.route('**/api/v1/admin/gyms/*/related*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ claims: [], invitations: [] }),
}),
);
// 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 instanceId = req.url().match(/equipment\/([^/]+)$/)?.[1];
if (req.method() === 'PATCH') {
const body = JSON.parse(req.postData() || '{}');
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',
body: JSON.stringify({ gym: { ...TEST_GYM, equipment: gymEquipmentState } }),
});
}
if (req.method() === 'DELETE') {
const idx = gymEquipmentState.findIndex((e) => e.id === instanceId);
if (idx >= 0) gymEquipmentState.splice(idx, 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 204 });
});
// Właściciele (OWNER): POST nadaje / DELETE odbiera rolę — stanowo (gymOwnersState + membersState).
page.route('**/api/v1/admin/gyms/*/owners**', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = JSON.parse(req.postData() || '{}');
const list = (users as { users?: User[] } | null)?.users ?? [];
const u = list.find((x) => x.id === body.userId);
if (u && !gymOwnersState.some((o) => o.id === u.id)) {
gymOwnersState.push({
id: u.id,
firstName: u.firstName,
lastName: u.lastName,
email: u.email,
});
const m = membersState.find((x) => x.user.id === u.id);
if (m && !m.roles.includes('OWNER')) m.roles.push('OWNER');
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ membership: { gymId: 'gym-1', roles: ['OWNER'] } }),
});
}
if (req.method() === 'DELETE') {
const userId = req.url().match(/owners\/([^/?]+)/)?.[1];
const idx = gymOwnersState.findIndex((o) => o.id === userId);
if (idx >= 0) gymOwnersState.splice(idx, 1);
const m = userId ? membersState.find((x) => x.user.id === userId) : undefined;
if (m) m.roles = m.roles.filter((r) => r !== 'OWNER');
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405 });
});
// Wyjątki harmonogramu — jeden wyjątek dla gym-1 (pokrywa chipy wyjątków pod paskiem godzin).
page.route('**/api/v1/admin/gyms/*/exceptions*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
exceptions: [
{
id: 'ex-1',
gymId: 'gym-1',
date: '2026-12-24',
availability: { start: '10:00', end: '14:00' },
createdAt: '2026-12-01T00:00:00.000Z',
},
],
}),
}),
);
page.route('**/api/v1/admin/users', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(users) }),
);
// Stateful: honors the `action` and `userId` query parameters (server-side filters).
// `*` at the end matches the optional query string.
page.route('**/api/v1/admin/logs*', (route) => {
const body = (logs ?? { logs: TEST_LOGS, total: TEST_LOGS.length }) as {
logs?: ActivityLog[];
total?: number;
};
const params = new URL(route.request().url()).searchParams;
const action = params.get('action');
const userId = params.get('userId');
let list = body.logs;
if (action) list = list?.filter((l) => l.action === action);
if (userId) list = list?.filter((l) => l.actor.id === userId);
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ logs: list ?? [], total: list?.length ?? 0 }),
});
});
page.route('**/api/v1/admin/focus-areas', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ focusAreas: TEST_FOCUS_AREAS }),
}),
);
page.route('**/api/v1/admin/equipment', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ equipment: TEST_EQUIPMENT }),
}),
);
page.route('**/api/v1/admin/exercises', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ exercises: TEST_EXERCISES }),
}),
);
// Logi audytu na koncie (karta w konsoli + podstrona /users/:id/logs).
// Honoruje `scope`: onAccount = operacje NA koncie, performed = aktor = user, all = unia.
page.route('**/api/v1/admin/users/*/activity*', (route) => {
const url = new URL(route.request().url());
const scope = url.searchParams.get('scope') ?? 'onAccount';
const uid = url.pathname.match(/admin\/users\/([^/]+)\/activity/)?.[1] ?? '';
const src = ((activity as { logs?: ActivityLog[] })?.logs ?? []) as ActivityLog[];
const onAccount = (l: ActivityLog) => l.entityType === 'user' && l.entityId === uid;
const list =
scope === 'performed'
? src.filter((l) => l.actor.id === uid)
: scope === 'all'
? src.filter((l) => onAccount(l) || l.actor.id === uid)
: src.filter(onAccount);
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ logs: list, total: list.length }),
});
});
// PATCH ról / DELETE członkostwa (menu członka w konsoli siłowni) — stanowo (membersState).
page.route('**/api/v1/admin/users/*/memberships/*', (route) => {
const req = route.request();
const userId = decodeURIComponent(req.url().match(/users\/([^/]+)\/memberships\//)?.[1] ?? '');
if (req.method() === 'PATCH') {
const body = JSON.parse(req.postData() || '{}');
const m = membersState.find((x) => x.user.id === userId);
if (m && Array.isArray(body.roles)) m.roles = body.roles;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ membership: { userId, gymId: 'gym-1', roles: m?.roles ?? [] } }),
});
}
if (req.method() === 'DELETE') {
const idx = membersState.findIndex((x) => x.user.id === userId);
if (idx >= 0) membersState.splice(idx, 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 405 });
});
// ---------- gym claims (verifications) ----------
// Kolejność rejestracji: list (catch-all) najpierw, potem coraz bardziej
// specyficzne route'y (Playwright dopasowuje w odwrotnej kolejności).
page.route('**/api/v1/admin/gyms/claims*', (route) => {
const status = new URL(route.request().url()).searchParams.get('status');
const list = status ? claimsState.filter((c) => c.status === status) : claimsState;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ claims: list }),
});
});
page.route('**/api/v1/admin/gyms/claims/*', (route) => {
const id = route
.request()
.url()
.match(/claims\/([^/?]+)$/)?.[1];
const claim = claimsState.find((c) => c.id === id);
if (!claim) {
return route.fulfill({
status: 404,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Claim not found' } }),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ claim }),
});
});
page.route('**/api/v1/admin/gyms/claims/*/approve', (route) => {
const id = route
.request()
.url()
.match(/claims\/([^/]+)\/approve$/)?.[1];
const claim = claimsState.find((c) => c.id === id);
if (claim && claim.status === 'PENDING') {
claim.status = 'APPROVED';
claim.decidedAt = new Date().toISOString();
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ ok: true }),
});
});
page.route('**/api/v1/admin/gyms/claims/*/reject', (route) => {
const id = route
.request()
.url()
.match(/claims\/([^/]+)\/reject$/)?.[1];
const body = JSON.parse(route.request().postData() || '{}');
const claim = claimsState.find((c) => c.id === id);
if (claim && claim.status === 'PENDING') {
claim.status = 'REJECTED';
claim.rejectReason = body.reason ?? null;
claim.decidedAt = new Date().toISOString();
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ ok: true }),
});
});
page.route('**/api/v1/admin/gyms/claims/*/documents/*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/pdf',
body: 'mock-document-content',
}),
);
}