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

506 lines
16 KiB
TypeScript

import type { Page } from '@playwright/test';
import type { ActivityLog, Equipment, Gym, GymClaim, User } from '../../src/api/types';
export const TEST_ADMIN = {
id: 'admin-test',
email: 'admin@fitos.pl',
firstName: 'Admin',
lastName: 'Test',
age: null,
heightCm: null,
phone: null,
isAdmin: true,
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',
},
{
id: 'eq-2',
name: 'Dywan',
kind: 'OTHER',
spec: null,
description: 'Dywan do ćwiczeń.',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
];
export const TEST_GYM_PHOTOS = [
{ 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: 'Warszawa, Mokotów',
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,
_count: { memberships: 12 },
};
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,
_count: { memberships: 4 },
};
/** 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,
age: 30,
heightCm: 180,
phone: '+48 500 100 200',
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: ['chest'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: ['legs'],
createdAt: '2026-01-01T00:00:00.000Z',
memberships: [{ gymId: 'gym-1', roles: ['MEMBER'], 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,
difficulty: 4,
source: 'BUILTIN',
},
];
export const TEST_FOCUS_AREAS = [
{ id: 'fa-1', name: 'Klatka piersiowa', muscle: 'chest', description: 'Wyciskanie, rozpiętki.', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' },
{ id: 'fa-2', name: 'Nogi', muscle: 'legs', description: 'Przysiady, wykroki.', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' },
];
export const TEST_FOCUS_CHAIN = {
develop: [{ muscle: 'chest', name: 'Klatka piersiowa', exercises: [{ id: 'pz-2', name: 'Wyciskanie' }] }],
canDo: [],
difficult: [],
avoid: [{ muscle: 'legs', name: 'Nogi', exercises: [{ id: 'pz-1', name: 'Przysiady' }] }],
};
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: null,
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/gyms/claims. */
claims?: 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 },
claims = { claims: [] as GymClaim[] },
} = 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({}) }),
);
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: { 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: quantities of TEST_GYM equipment persist across refetches (PATCH/DELETE).
const gymEquipmentState = TEST_GYM.equipment.map((e) => ({ ...e }));
// 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;
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],
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',
),
});
});
page.route('**/api/v1/admin/gyms', (route) => {
const list = (gyms as { gyms?: Array<Record<string, unknown>> } | null)?.gyms;
const body = list && gyms
? {
...gyms,
gyms: list.map((g) => (g.id === TEST_GYM.id ? { ...g, equipment: gymEquipmentState } : g)),
}
: gyms;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(body),
});
});
page.route('**/api/v1/admin/gyms/*/equipment/*', (route) => {
const req = route.request();
const eqId = req.url().match(/equipment\/([^/]+)$/)?.[1];
if (req.method() === 'PATCH') {
const body = JSON.parse(req.postData() || '{}');
const link = gymEquipmentState.find((e) => e.equipmentId === eqId);
if (link && typeof body.quantity === 'number') link.quantity = body.quantity;
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.equipmentId === eqId);
if (idx >= 0) gymEquipmentState.splice(idx, 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 204 });
});
page.route('**/api/v1/admin/users', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(users) }),
);
// Stateful: honors the `action` query parameter (server-side filter).
// `*` 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 action = new URL(route.request().url()).searchParams.get('action');
const list = action ? body.logs?.filter((l) => l.action === action) : body.logs;
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 }),
}),
);
page.route('**/api/v1/admin/users/*/focus-chain', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_FOCUS_CHAIN),
}),
);
page.route('**/api/v1/admin/users/*/memberships/*', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ membership: {} }),
}),
);
// ---------- 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',
}),
);
}