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

1849 lines
62 KiB
TypeScript

import type { Page } from '@playwright/test';
export const TEST_USER = {
id: 'user-test',
email: 'test@fitos.pl',
firstName: 'Test',
lastName: 'User',
nickname: null,
socialMedia: null,
age: 30,
heightCm: 180,
phone: '+48 600 000 000',
isAdmin: false,
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',
};
export const TEST_EQUIPMENT = [
{ id: 'eq-1', name: 'Sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: 'Sztanga z talerzami.' },
{ id: 'eq-2', name: 'Hantle', kind: 'DUMBBELL', spec: { minKg: 2.5, maxKg: 25 }, description: 'Hantle wolne.' },
{ id: 'eq-3', name: 'Kettlebell', kind: 'KETTLEBELL', spec: { minKg: 4, maxKg: 32 }, description: 'Kettlebell.' },
];
export const TEST_FOCUS_AREAS = [
{ id: 'fa-1', name: 'Klatka piersiowa', muscle: 'chest', description: 'Wyciskanie, rozpiętki, pompki.', 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_DASHBOARD = {
killstreak: 3,
killstreakBest: 5,
// Kropki killstreaka względne do „dziś" — widoczne w oknie 30 dni.
killstreakDays: [2, 1, 0].map((d) => {
const day = new Date();
day.setDate(day.getDate() - d);
return `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(
day.getDate(),
).padStart(2, '0')}T07:00:00.000Z`;
}),
history: { completedPlans: 2, sessions: 18, sets: 143 },
week: { planned: 3, completed: 1 },
lastSessionAt: '2026-10-13T07:00:00.000Z',
firstSessionAt: '2026-06-01T07:00:00.000Z',
weeklySets: [30, 33, 36, 34, 38, 41, 0, 44, 39, 42, 36, 40].map((sets, i) => ({
weekStart: new Date(Date.UTC(2026, 5, 29 + i * 7)).toISOString(),
sets,
})),
nextTraining: {
dayId: 'day-1',
date: '2026-08-24',
exercises: [{ name: 'Przysiady', muscle: 'legs' }],
},
progress: { completed: 5, total: 20, percent: 25 },
extra: { sets: 5 },
missing: { sets: 1 },
activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01' },
};
function makeExercise(id: string, name: string, primaryMuscle: string) {
return {
id,
slug: id,
name,
primaryMuscle,
secondaryMuscles: [],
equipment: [],
hasReps: true,
hasLoad: true,
hasRest: true,
hasSets: true,
hasRir: true,
hasDifficulty: true,
hasCardio: false,
hasTime: false,
hasSpeed: false,
description: null,
howTo: null,
commonMistakes: null,
source: 'BUILTIN',
};
}
export const TEST_DAY = {
id: 'day-1',
date: '2026-08-24',
status: 'PLANNED',
dayOfWeek: 1,
sessions: [{ id: 'sess-1', status: 'IN_PROGRESS', startedAt: '2026-08-24T07: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_OWNED = {
id: 'gym-1',
name: 'Żelazna Świątynia',
location: 'Warszawa',
addressLine1: 'Mokotowska 12A',
addressLine2: null,
postalCode: '00-900',
city: 'Warszawa',
countryCode: 'PL',
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
capacity: 50,
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: 2, equipment: TEST_EQUIPMENT[1] },
],
coverPhoto: '/gyms/gym-1/photos/photo-1',
roles: ['OWNER', 'TRAINER'],
};
export const TEST_GYM_JOINABLE = {
id: 'gym-2',
name: 'Mega Gym',
location: 'Kraków',
availability: null,
capacity: null,
kind: 'REAL',
isPrivate: false,
equipment: [],
coverPhoto: null,
};
/** Publiczna wirtualna siłownia (do oceniania i dołączania). */
export const TEST_GYM_VIRTUAL_PUBLIC = {
id: 'gym-v1',
name: 'Wirtualna Alfa',
location: 'Gdańsk',
availability: null,
capacity: 30,
kind: 'VIRTUAL',
isPrivate: false,
equipment: [{ id: 'gev-1', gymId: 'gym-v1', equipmentId: 'eq-1', quantity: 2, equipment: TEST_EQUIPMENT[0] }],
};
/** Prywatna wirtualna siłownia, której właścicielem jest test user. */
export const TEST_GYM_VIRTUAL_PRIVATE = {
id: 'gym-v2',
name: 'Moja Prywatna Wirtualna',
location: 'Wrocław',
availability: null,
capacity: null,
kind: 'VIRTUAL',
isPrivate: true,
equipment: [],
};
/** Otrzymane zaproszenie do prywatnej wirtualnej siłowni. */
export const TEST_GYM_INVITATION_RECEIVED = {
id: 'gym-inv-1',
direction: 'received',
gym: { id: 'gym-v3', name: 'Prywatna Beta', location: 'Poznań', kind: 'VIRTUAL', isPrivate: true },
user: null,
invitedBy: { id: 'owner-1', firstName: 'Marek', lastName: 'Trener', email: 'marek@test.local' },
invitedAt: '2026-08-20T00:00:00.000Z',
expiresAt: '2026-08-27T00:00:00.000Z',
};
export const TEST_USER_WITH_SOCIALS = {
...TEST_USER,
nickname: 'fitfan',
socialMedia: [
{ platform: 'INSTAGRAM', url: 'https://instagram.com/fitfan' },
{ platform: 'OTHER', url: 'https://example.com/blog', label: 'Blog' },
],
};
export const TEST_TRAINEE = {
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
gyms: [{ id: 'gym-1', name: 'Żelazna Świątynia' }],
activePlan: { id: 'plan-1', title: 'Plan testowy', progress: { completed: 5, total: 20, percent: 25 } },
killstreak: 3,
lastSessionAt: '2026-08-24T07:00:00.000Z',
flags: ['streak_reset'],
};
export const TEST_TRAINEES = [TEST_TRAINEE];
export const TEST_TRAINEE_DETAIL = {
coachingId: 'coaching-1',
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
socialMedia: null,
// equipment = do limitowania ćwiczeń w edytorze planu podopiecznego
gyms: [
{
id: 'gym-1',
name: 'Żelazna Świątynia',
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: 2, equipment: TEST_EQUIPMENT[1] },
],
},
],
activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01' },
progress: { completed: 5, total: 20, percent: 25 },
killstreak: 3,
nextTraining: { dayId: 'day-1', date: '2026-08-25', exercises: [{ name: 'Przysiady', muscle: 'legs' }] },
extra: { sets: 5 },
missing: { sets: 1 },
lastSessionAt: '2026-08-24T07:00:00.000Z',
flags: ['streak_reset'],
};
export const TEST_TRAINEE_NICK = {
...TEST_TRAINEE,
user: { ...TEST_TRAINEE.user, nickname: 'annanowak' },
};
export const TEST_TRAINEE_DETAIL_NICK = {
...TEST_TRAINEE_DETAIL,
user: { ...TEST_TRAINEE_DETAIL.user, nickname: 'annanowak' },
socialMedia: [
{ platform: 'TIKTOK', url: 'https://tiktok.com/@annanowak' },
{ platform: 'OTHER', url: 'https://example.com/blog', label: 'Blog' },
],
};
export const TEST_TRAINEE_HISTORY = {
sessions: [
{
id: 'hist-sess-1',
status: 'COMPLETED',
startedAt: '2026-08-24T07:00:00.000Z',
endedAt: '2026-08-24T08:30:00.000Z',
date: '2026-08-24',
dayOfWeek: 1,
plan: 'Plan testowy',
exercises: [
{
id: 'se-1',
name: 'Przysiady',
muscle: 'legs',
isExtra: false,
sets: [
{
index: 0,
reps: 10,
rir: 2,
difficulty: 3,
// komentarz trenującego przy serii (widoczny trenerowi)
note: 'ostatnia seria była ciężka',
planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 },
},
],
comments: [] as { id: string; authorId: string; authorName: string; body: string; createdAt: string }[],
},
{
id: 'se-2',
name: 'Wyciskanie',
muscle: 'chest',
isExtra: true,
sets: [{ index: 0, reps: 8, rir: 1, difficulty: null, note: null, planned: null }],
comments: [] as { id: string; authorId: string; authorName: string; body: string; createdAt: string }[],
},
],
},
{
id: 'hist-sess-2',
status: 'COMPLETED',
startedAt: '2026-08-17T07:00:00.000Z',
endedAt: '2026-08-17T08:30:00.000Z',
date: '2026-08-17',
dayOfWeek: 1,
plan: 'Plan testowy',
exercises: [
{
id: 'se-3',
name: 'Przysiady',
muscle: 'legs',
isExtra: false,
sets: [
{
index: 0,
reps: 8,
rir: 3,
difficulty: 3,
note: null,
planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 },
},
],
comments: [] as { id: string; authorId: string; authorName: string; body: string; createdAt: string }[],
},
],
},
],
};
export const TEST_USER_SEARCH = [
{
id: 'candidate-1',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
email: 'jan.kowalski@test.local',
phone: '+48 500 100 200',
gyms: [{ id: 'gym-2', name: 'Mega Gym' }],
},
];
export const TEST_INVITATIONS = [
{
id: 'inv-1',
direction: 'received',
other: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener', nickname: null, email: 'marek@test.local', phone: null },
invitedAt: '2026-08-20T00:00:00.000Z',
expiresAt: '2026-08-27T00:00:00.000Z',
},
{
id: 'inv-2',
direction: 'sent',
other: { id: 'trainee-2', firstName: 'Piotr', lastName: 'Podopieczny', nickname: null, email: 'piotr@test.local', phone: null },
invitedAt: '2026-08-21T00:00:00.000Z',
expiresAt: '2026-08-28T00:00:00.000Z',
},
];
export const TEST_TRAINEE_REPORT = {
plan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01T00:00:00.000Z' },
muscles: [
{
muscle: 'legs',
planned: { sets: 12, reps: 120 },
actual: { sets: 10, reps: 96 },
extra: { sets: 2 },
missing: { sets: 2 },
completionPct: 83,
recommendedRange: { setsMin: 10, setsMax: 18 },
outOfRange: false,
},
{
muscle: 'chest',
planned: { sets: 10, reps: 90 },
actual: { sets: 4, reps: 32 },
extra: { sets: 0 },
missing: { sets: 6 },
completionPct: 40,
recommendedRange: { setsMin: 10, setsMax: 20 },
outOfRange: true,
},
],
days: [
{ date: '2026-08-18T00:00:00.000Z', status: 'COMPLETED', moved: false },
{ date: '2026-08-20T00:00:00.000Z', status: 'SKIPPED', moved: false },
{ date: '2026-08-21T00:00:00.000Z', status: 'COMPLETED', moved: true },
{ date: '2026-08-25T00:00:00.000Z', status: 'PLANNED', moved: false },
],
};
export const TEST_TRAINEE_MOVES = {
moves: [
{
dayId: 'day-3',
date: '2026-08-21T00:00:00.000Z',
fromDate: '2026-08-19T00:00:00.000Z',
toDate: '2026-08-21T00:00:00.000Z',
reason: 'choroba',
movedAt: '2026-08-19T09:00:00.000Z',
},
],
};
export const TEST_TRAINEE_EXERCISE_PROGRESS = {
exercises: [
{
exerciseId: 'ex-1',
name: 'Przysiady',
muscle: 'legs',
points: [
{ date: '2026-08-17', oneRm: 72, volumeKg: 480, reps: 8, sets: 1 },
{ date: '2026-08-24', oneRm: 76, volumeKg: 600, reps: 10, sets: 1 },
],
},
{
exerciseId: 'ex-2',
name: 'Wyciskanie',
muscle: 'chest',
points: [{ date: '2026-08-24', oneRm: null, volumeKg: null, reps: 8, sets: 1 }],
},
],
};
export const TEST_CONVERSATIONS = {
conversations: [
{
coachingId: 'coaching-1',
role: 'trainer',
other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' },
unreadCount: 2,
},
{
coachingId: 'coaching-2',
role: 'trainer',
other: { id: 'trainee-2', firstName: 'Piotr', lastName: 'Kowal', nickname: null },
lastMessage: null,
unreadCount: 0,
},
],
};
export const TEST_MESSAGE_THREAD = {
role: 'trainer',
other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
messages: [
{
id: 'msg-1',
senderId: 'trainee-1',
body: 'Dobrze się czuję',
createdAt: '2026-08-24T10:00:00.000Z',
attachment: null,
},
],
};
export const TEST_MY_EXERCISE_PROGRESS = TEST_TRAINEE_EXERCISE_PROGRESS;
/**
* Moja historia treningów — daty dynamiczne: bieżący miesiąc (dzień 3) i
* poprzedni (dzień 15), aby filtr miesiąca miał co filtrować.
*/
export function myHistoryBody() {
const now = new Date();
const cur = new Date(now.getFullYear(), now.getMonth(), 3, 7);
const prev = new Date(now.getFullYear(), now.getMonth() - 1, 15, 7);
const dateStr = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
return {
sessions: [
{
id: 'my-hist-1',
status: 'COMPLETED',
startedAt: cur.toISOString(),
endedAt: new Date(cur.getTime() + 90 * 60000).toISOString(),
date: dateStr(cur),
dayOfWeek: 1,
plan: 'Plan testowy',
norm: { done: 1, total: 2 },
bonus: 0,
deficit: 1,
exercises: [
{
id: 'my-se-1',
name: 'Przysiady',
muscle: 'legs',
isExtra: false,
comments: [],
sets: [
// komentarz trenującego przy serii (widoczny w historii)
{ index: 0, reps: 10, rir: 2, difficulty: null, note: 'ostatnia seria była ciężka', planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } },
{ index: 1, reps: null, rir: null, difficulty: null, note: null, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } },
],
},
],
},
{
id: 'my-hist-2',
status: 'COMPLETED',
startedAt: prev.toISOString(),
endedAt: new Date(prev.getTime() + 60 * 60000).toISOString(),
date: dateStr(prev),
dayOfWeek: 3,
plan: 'Plan testowy',
norm: { done: 1, total: 1 },
bonus: 0,
deficit: 0,
exercises: [
{
id: 'my-se-2',
name: 'Wyciskanie',
muscle: 'chest',
isExtra: false,
comments: [],
sets: [{ index: 0, reps: 8, rir: 1, difficulty: null, planned: { reps: 8, loadKg: 40, restSec: 90, rir: 2 } }],
},
],
},
],
};
}
export const TEST_TRAINEE_PLANS = [
{
id: 'tp-1',
userId: 'trainee-1',
title: 'Plan masowy',
status: 'DRAFT',
weeksCount: 1,
startDate: null,
gym: null,
creator: { id: 'trainer-2', firstName: 'Jan', lastName: 'Kowalski' },
weeks: [],
},
{
id: 'tp-2',
userId: 'trainee-1',
title: 'Plan aktywny',
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
gym: { id: 'gym-1', name: 'Żelazna Świątynia' },
creator: null,
weeks: [],
},
{
id: 'tp-3',
userId: 'trainee-1',
title: 'Plan domknięty',
status: 'ACTIVE',
weeksCount: 1,
startDate: '2026-08-24',
gym: null,
creator: null,
weeks: [],
},
{
id: 'tp-4',
userId: 'trainee-1',
title: 'Plan ukończony',
status: 'COMPLETED',
weeksCount: 1,
startDate: '2026-08-24',
gym: null,
creator: null,
weeks: [],
},
];
export const TEST_TRAINEE_PLAN_DETAIL = {
id: 'tp-1',
userId: 'trainee-1',
canManage: true,
title: 'Plan masowy',
status: 'DRAFT',
weeksCount: 1,
startDate: null,
gym: null,
creator: { id: 'trainer-2', firstName: 'Jan', lastName: 'Kowalski' },
weeks: [
{
id: 'tw-1',
index: 0,
customName: null,
days: [
{
id: 'td-1',
dayOfWeek: 1,
date: null,
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'tpe-1',
exerciseId: 'ex-1',
order: 0,
exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
sets: [
{ id: 'tps-1', index: 0, reps: 10, loadKg: 60, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null },
],
},
],
},
],
},
],
};
/** Plan udostępniony zalogowanemu użytkownikowi (read-only; właściciel = trener). */
export const TEST_SHARED_PLAN = {
id: 'shared-1',
userId: 'trainer-2',
canManage: false,
title: 'Plan udostępniony',
status: 'DRAFT',
weeksCount: 2,
startDate: null,
gym: null,
creator: null,
sharedBy: { id: 'trainer-2', firstName: 'Jan', lastName: 'Kowalski' },
weeks: [],
};
export const TEST_TRAINEE_PLAN_DETAIL_ACTIVE = {
id: 'tp-2',
userId: 'trainee-1',
canManage: true,
title: 'Plan aktywny',
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
gym: { id: 'gym-1', name: 'Żelazna Świątynia' },
creator: null,
weeks: [
{
id: 'tw-1',
index: 0,
customName: null,
days: [
{
id: 'td-1',
dayOfWeek: 1,
date: '2026-08-24',
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'tpe-2',
exerciseId: 'ex-2',
order: 0,
exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
sets: [
{ id: 'tps-2', index: 0, reps: 8, loadKg: 40, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null },
],
},
],
},
],
},
],
};
/** Plan aktywny bez zaplanowanych dni (wszystkie ukończone) — można go ukończyć ręcznie. */
export const TEST_TRAINEE_PLAN_DETAIL_FINISHED = {
...TEST_TRAINEE_PLAN_DETAIL_ACTIVE,
id: 'tp-3',
title: 'Plan domknięty',
weeksCount: 1,
weeks: [
{
id: 'tw-3',
index: 0,
customName: null,
days: [
{
id: 'td-3',
dayOfWeek: 1,
date: '2026-08-24',
status: 'COMPLETED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'tpe-3',
exerciseId: 'ex-2',
order: 0,
exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
sets: [
{ id: 'tps-3', index: 0, reps: 8, loadKg: 40, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null },
],
},
],
},
],
},
],
};
/** Plan ukończony — w panelu trenera bez akcji „Wznów" (reopen tylko u właściciela). */
export const TEST_TRAINEE_PLAN_DETAIL_DONE = {
...TEST_TRAINEE_PLAN_DETAIL_FINISHED,
id: 'tp-4',
title: 'Plan ukończony',
status: 'COMPLETED',
};
export const TEST_TRAINEE_LATEST_RESULTS = [
{ exerciseId: 'ex-1', name: 'Przysiady', muscle: 'legs', date: '2026-08-24', sets: [{ reps: 12, loadKg: 70 }], oneRm: 80.6 },
];
/**
* Kalendarz podopiecznego (dni aktywnego planu) — daty dynamiczne w BIEŻĄCYM
* miesiącu, aby zakładka Kalendarz zawsze renderowała treningi.
*/
export function traineeCalendarDays() {
const now = new Date();
const iso = (day: number) => new Date(now.getFullYear(), now.getMonth(), day).toISOString();
return [
{
id: 'tc-1',
date: iso(3),
status: 'COMPLETED',
dayOfWeek: 1,
exercises: [{ name: 'Przysiady', muscle: 'legs' }],
},
{
id: 'tc-2',
date: iso(15),
status: 'PLANNED',
dayOfWeek: 3,
exercises: [
{ name: 'Przysiady', muscle: 'legs' },
{ name: 'Wyciskanie', muscle: 'chest' },
],
},
];
}
export function traineeCalendarBody() {
const now = new Date();
return {
month: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`,
days: traineeCalendarDays(),
};
}
export const TEST_SESSION = {
id: 'sess-1',
status: 'IN_PROGRESS',
startedAt: '2026-08-24T07:00:00.000Z',
day: {
id: 'day-1',
date: '2026-08-24',
status: 'PLANNED',
week: { plan: { id: 'plan-1', title: 'Plan testowy', status: 'ACTIVE' } },
moveLog: [],
},
exercises: [
{
id: 'se-1',
order: 0,
hidden: false,
removed: false,
exercise: makeExercise('pz-1', 'Przysiady', 'legs'),
planExercise: {
id: 'pe-1',
sets: [
{
id: 'ps-1',
index: 0,
reps: 10,
loadKg: 60,
restSec: 90,
rir: 2,
difficulty: null,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
sets: [{ id: 'ss-1', planSetId: 'ps-1', index: 0, reps: null, rir: null, difficulty: null, note: null }],
},
{
id: 'se-2',
order: 1,
hidden: false,
removed: false,
exercise: makeExercise('pz-2', 'Wyciskanie', 'chest'),
planExercise: null,
sets: [{ id: 'ss-2', planSetId: null, index: 0, reps: null, rir: null, difficulty: null, note: null }],
},
],
};
/** Mockuje dzień z aktywną sesją (planowane ćwiczenie + dodane ponad plan). */
export function mockDayExecution(page: Page) {
mockApi(page);
// Stateful (jak serwer): PATCH /sessions/sets/:id zapisuje wyniki w sesji — po
// zapisie seria staje się uzupełniona, a „Następna” przesuwa się na kolejną pustą.
const session = JSON.parse(JSON.stringify(TEST_SESSION)) as typeof TEST_SESSION;
page.route('**/api/v1/days/day-1', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ day: TEST_DAY }) }),
);
page.route('**/api/v1/sessions/sets/*', (route) => {
const req = route.request();
if (req.method() === 'PATCH') {
const id = req.url().split('/').pop() ?? '';
const patch = (req.postDataJSON() ?? {}) as Record<string, unknown>;
for (const ex of session.exercises)
for (const s of ex.sets)
if (s.id === id) {
for (const key of ['reps', 'rir', 'difficulty', 'note'] as const)
if (key in patch) Object.assign(s, { [key]: patch[key] });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });
}
return route.fallback();
});
page.route('**/api/v1/sessions/sess-1', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ session }) }),
);
}
/**
* Mockuje dzień z aktywną sesją i statefulny flow porzucenia:
* POST /sessions/sess-1/abandon oznacza sesję jako ABANDONED, a dzień jako SKIPPED
* (treningu nie da się ponownie wykonać).
*/
export function mockDayExecutionAbandon(page: Page) {
mockApi(page);
let abandoned = false;
page.route('**/api/v1/days/day-1', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
day: {
...TEST_DAY,
status: abandoned ? 'SKIPPED' : 'PLANNED',
sessions: [
{ id: 'sess-1', status: abandoned ? 'ABANDONED' : 'IN_PROGRESS', startedAt: '2026-08-24T07:00:00.000Z' },
],
},
}),
}),
);
page.route('**/api/v1/sessions/sess-1', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ session: { ...TEST_SESSION, status: abandoned ? 'ABANDONED' : 'IN_PROGRESS' } }),
}),
);
page.route('**/api/v1/sessions/sess-1/abandon', (route) => {
abandoned = true;
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
});
}
/**
* Mockuje dzień zaplanowany (PLANNED) z porzuconą sesją — np. po auto-porzuceniu
* przez scheduler: sesja ABANDONED, dzień nadal PLANNED (można rozpocząć nową sesję).
*/
export function mockDayExecutionAbandonedPlanned(page: Page) {
mockApi(page);
page.route('**/api/v1/days/day-1', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
day: {
...TEST_DAY,
status: 'PLANNED',
sessions: [{ id: 'sess-1', status: 'ABANDONED', startedAt: '2026-08-24T07:00:00.000Z' }],
},
}),
}),
);
page.route('**/api/v1/sessions/sess-1', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ session: { ...TEST_SESSION, status: 'ABANDONED' } }),
}),
);
}
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 /dashboard. */
dashboard?: unknown;
/** Ciało odpowiedzi GET /me (domyślnie: TEST_USER bez członkostw). */
me?: unknown;
/** Ciało odpowiedzi GET /me/active-session (domyślnie: brak aktywnej sesji). */
activeSession?: unknown;
/** Ciało odpowiedzi GET /trainer/trainees. */
trainees?: unknown;
/** Ciało odpowiedzi GET /trainer/invitations. */
invitations?: unknown;
/** Ciało odpowiedzi GET /trainer/search. */
userSearch?: unknown;
/** Ciało odpowiedzi GET /trainer/trainees/:id (domyślnie: TEST_TRAINEE_DETAIL). */
traineeDetail?: unknown;
/** Ciało odpowiedzi GET /messages/conversations (domyślnie: TEST_CONVERSATIONS). */
conversations?: unknown;
/** Ciało odpowiedzi GET /messages/conversations/:id (domyślnie: TEST_MESSAGE_THREAD). */
messageThread?: unknown;
/** Ciało odpowiedzi GET /gyms/invitations (domyślnie: otrzymane zaproszenie do siłowni). */
gymInvitations?: unknown;
/** Ciało odpowiedzi GET /gyms (własne siłownie z rolami; domyślnie: TEST_GYM_OWNED). */
myGyms?: unknown;
/** Ciało odpowiedzi GET /plans/shared-with-me (domyślnie: brak udostępnionych planów). */
sharedWithMe?: unknown;
/** Ciało odpowiedzi GET /me/trainers (domyślnie: brak trenerów). */
myTrainers?: unknown;
/** Ciało odpowiedzi GET /me/history (domyślnie: myHistoryBody; honoruje ?month=). */
history?: unknown;
/** Ciało odpowiedzi GET /me/body-parameters (domyślnie: brak pomiarów; stateful POST /weight). */
bodyParameters?: unknown;
/** Wpisy feedu GET /me/feed (domyślnie: pusty; stateful: oznaczanie przeczytania). */
feed?: { items: { source: string; id: string; read?: boolean }[] };
}
/**
* 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_USER, accessToken: 'test-access-token' },
dashboard = TEST_DASHBOARD,
me = { user: TEST_USER, memberships: [] },
activeSession = { session: null },
trainees = { trainees: TEST_TRAINEES },
invitations = { invitations: TEST_INVITATIONS },
userSearch = { users: TEST_USER_SEARCH },
traineeDetail = TEST_TRAINEE_DETAIL,
conversations = TEST_CONVERSATIONS,
messageThread = TEST_MESSAGE_THREAD,
gymInvitations = { invitations: [] },
myGyms,
sharedWithMe,
myTrainers,
history,
bodyParameters,
feed,
} = opts;
// Stateful: equipment added via POST /gyms/:id/equipment persists on refetch.
// 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.
const traineeHistory = JSON.parse(JSON.stringify(TEST_TRAINEE_HISTORY)) as typeof TEST_TRAINEE_HISTORY;
// Stateful: virtual gyms (ratings, claims) + gym invitations (sent/received).
const virtualGymState = [
{
...TEST_GYM_VIRTUAL_PUBLIC,
up: 2,
down: 1,
myVote: null as 'UP' | 'DOWN' | null,
claimStatus: null as string | null,
rejectReason: null as string | null,
},
];
const privateVirtualGym = {
...TEST_GYM_VIRTUAL_PRIVATE,
up: 0,
down: 0,
myVote: null as 'UP' | 'DOWN' | null,
claimStatus: null as string | null,
rejectReason: null as string | null,
};
const gymClaimsState: Record<string, unknown>[] = [];
const gymInvitationState: Record<string, unknown>[] = (gymInvitations as { invitations: Record<string, unknown>[] })
.invitations.map((i) => ({ ...i }));
let claimSeq = 0;
let gymInviteSeq = 0;
const findVirtualGym = (id: string) =>
[...virtualGymState, privateVirtualGym].find((x) => x.id === id);
// 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({
gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment, photos: [...gymPhotosState], coverPhoto: coverOf(gymPhotosState) },
roles: ['OWNER', 'TRAINER'],
isAdmin: false,
});
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' } }),
}),
);
// Stateful: PATCH /me merges the patch into the user (jak availability/nickname/socialMedia).
let meBody = me as { user: Record<string, unknown> } & Record<string, unknown>;
page.route('**/api/v1/me', (route) => {
const req = route.request();
if (req.method() === 'PATCH') {
const patch = (req.postDataJSON() ?? {}) as Record<string, unknown>;
meBody = { ...meBody, user: { ...meBody.user, ...patch } };
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(meBody) });
});
// registered after `**/api/v1/me` — month-aware: ?month=YYYY-MM filtruje po s.date.
const historyBody = (history ?? myHistoryBody()) as { sessions: { date: string | null }[] };
page.route('**/api/v1/me/history*', (route) => {
const monthParam = route.request().url().match(/[?&]month=(\d{4}-\d{2})/)?.[1] ?? null;
const sessions = monthParam
? historyBody.sessions.filter((s) => (s.date ?? '').slice(0, 7) === monthParam)
: historyBody.sessions;
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ sessions }) });
});
// Stateful: parametry ciała — POST /weight dopisuje punkt (refetch po dodaniu).
const bodyParams = JSON.parse(
JSON.stringify(bodyParameters ?? { weight: [], circumferences: [] }),
) as { weight: { id: string; value: number; date: string }[]; circumferences: unknown[] };
page.route('**/api/v1/me/body-parameters/weight', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = (req.postDataJSON() ?? {}) as { value: number; date?: string };
const date = body.date ?? new Date().toISOString().slice(0, 10);
bodyParams.weight.push({ id: `w-new-${bodyParams.weight.length}`, value: body.value, date });
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
});
page.route('**/api/v1/me/body-parameters', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(bodyParams) }),
);
page.route('**/api/v1/me/active-session', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(activeSession) }),
);
// ---------- feed / aktualności (powiadomienia + ogłoszenia), stateful ----------
const feedItems = JSON.parse(JSON.stringify(feed ?? { items: [] })).items as {
source: string;
id: string;
read?: boolean;
}[];
const feedJson = (status: number, body: unknown) =>
({ status, contentType: 'application/json', body: JSON.stringify(body) }) as const;
// Najpierw ogólna trasa, potem szczegółyne (Playwright: późniejsze rejestracje mają priorytet).
page.route('**/api/v1/me/feed*', (route) => {
const limit = Number(new URL(route.request().url()).searchParams.get('limit') ?? '20');
return route.fulfill(
feedJson(200, { items: feedItems.slice(0, limit), nextCursor: null }),
);
});
page.route('**/api/v1/me/feed/*/read', (route) => {
const id = new URL(route.request().url()).pathname.split('/').at(-2);
const item = feedItems.find((i) => i.id === id);
if (item) item.read = true;
return route.fulfill(feedJson(200, { ok: true }));
});
page.route('**/api/v1/me/feed/read-all', (route) => {
feedItems.forEach((i) => {
i.read = true;
});
return route.fulfill(feedJson(200, { ok: true }));
});
page.route('**/api/v1/me/feed/unread-count', (route) =>
route.fulfill(
feedJson(200, { unreadCount: feedItems.filter((i) => !i.read).length }),
),
);
// ---------- udostępnianie planów (PlanShare) ----------
page.route('**/api/v1/plans/shared-with-me', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(sharedWithMe ?? { plans: [] }) }),
);
page.route('**/api/v1/me/trainers', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(myTrainers ?? { trainers: [] }) }),
);
page.route('**/api/v1/plans/*/share', (route) =>
route.fulfill({
status: route.request().method() === 'POST' ? 201 : 200,
contentType: 'application/json',
body: JSON.stringify({ ok: true }),
}),
);
page.route('**/api/v1/focus-areas', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ focusAreas: TEST_FOCUS_AREAS }),
}),
);
page.route('**/api/v1/me/focus-chain', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_FOCUS_CHAIN),
}),
);
page.route('**/api/v1/dashboard', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(dashboard) }),
);
page.route('**/api/v1/gyms/all', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ gyms: [TEST_GYM_OWNED, TEST_GYM_JOINABLE] }),
}),
);
page.route('**/api/v1/gyms/*/join', (route) =>
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ membership: { gymId: TEST_GYM_JOINABLE.id, roles: ['MEMBER'] } }),
}),
);
page.route('**/api/v1/equipment', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ equipment: TEST_EQUIPMENT }),
}),
);
page.route('**/api/v1/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 = 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',
body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment } }),
});
}
if (req.method() === 'DELETE') {
const idx = ownedGymEquipment.findIndex((e) => e.id === instanceId);
if (idx >= 0) ownedGymEquipment.splice(idx, 1);
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 204 });
});
page.route('**/api/v1/gyms/*/equipment', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = JSON.parse(req.postData() || '{}');
const added = TEST_EQUIPMENT.find((e) => e.id === body.equipmentId);
if (added) {
// Każde dodanie = nowa instancja (bez deduplikacji typu katalogowego).
eqInstanceSeq += 1;
ownedGymEquipment.push({
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 },
instance: added ? instance : undefined,
}),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment } }),
});
});
page.route('**/api/v1/gyms', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = JSON.parse(req.postData() || '{}');
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({
gym: { id: 'gym-new', name: body.name, location: body.location ?? null, availability: body.availability ?? null, capacity: body.capacity ?? null, kind: body.kind ?? 'VIRTUAL', isPrivate: body.isPrivate ?? false, equipment: [], roles: ['OWNER'] },
}),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(myGymsBody),
});
});
// Owner-scoped schedule exceptions.
page.route('**/api/v1/gyms/*/exceptions/*', (route) =>
route.fulfill({ status: 204 }),
);
page.route('**/api/v1/gyms/*/exceptions', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = JSON.parse(req.postData() || '{}');
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({
exception: {
id: 'ex-1',
gymId: TEST_GYM_OWNED.id,
date: body.date,
availability: body.availability ?? null,
},
}),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ exceptions: [] }),
});
});
// Owner-scoped gym update (PATCH) / delete (DELETE).
// The glob also matches /gyms/all, so delegate that to the all-gyms list.
page.route('**/api/v1/gyms/*', (route) => {
const req = route.request();
if (req.url().endsWith('/gyms/all')) {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ gyms: [TEST_GYM_OWNED, TEST_GYM_JOINABLE] }),
});
}
if (req.method() === 'PATCH') {
const body = JSON.parse(req.postData() || '{}');
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, ...body } }),
});
}
if (req.method() === 'DELETE') {
return route.fulfill({ status: 204 });
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment } }),
});
});
// ---------- galeria zdjęć (siłownia REAL gym-1) ----------
// 1x1 transparent PNG — wystarczające, by <img> się wczytał bez błędu konsoli.
const TINY_PNG =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
// Detal siłowni (GET /gyms/gym-1) — siłownia + galeria + role zalogowanego.
page.route('**/api/v1/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() });
}
// GET — serwowanie pliku zdjęcia.
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({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ gyms: [...virtualGymState, privateVirtualGym] }),
}),
);
page.route('**/api/v1/gyms/*/rate', (route) => {
const req = route.request();
if (req.method() !== 'POST') return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });
const gymId = req.url().match(/gyms\/([^/]+)\/rate/)?.[1];
const body = JSON.parse(req.postData() || '{}');
const gym = virtualGymState.find((g) => g.id === gymId);
if (!gym) return route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Gym not found' } }) });
const vote = body.vote as 'UP' | 'DOWN';
if (gym.myVote === vote) {
// toggle off
if (vote === 'UP') gym.up -= 1;
else gym.down -= 1;
gym.myVote = null;
} else {
if (gym.myVote === 'UP') gym.up -= 1;
if (gym.myVote === 'DOWN') gym.down -= 1;
gym.myVote = vote;
if (vote === 'UP') gym.up += 1;
else gym.down += 1;
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ vote: gym.myVote, up: gym.up, down: gym.down }),
});
});
// ---------- gym claims ----------
page.route('**/api/v1/gyms/claims', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const raw = req.postData() || '';
// multipart: name="x" <reszta nagłówka> <pusta linia> <wartość>
const field = (name: string) =>
raw.match(new RegExp(`name="${name}"[^\\r\\n]*\\r?\\n\\r?\\n([^\\r\\n]*)`))?.[1]?.trim() || null;
const gymId = field('gymId');
const gymName = field('gymName');
const gymLocation = field('gymLocation');
claimSeq += 1;
const claim = {
id: `claim-${claimSeq}`,
gymId,
type: gymId ? 'verification' : 'new',
gym: gymId ? { id: gymId, name: 'Wirtualna Alfa', kind: 'VIRTUAL', isPrivate: false } : null,
gymName: gymId ? null : gymName ?? 'Nowa Realna Siłownia',
gymLocation: gymId ? null : gymLocation ?? 'ul. Testowa 1, Warszawa',
gymAvailability: null,
gymCapacity: null,
description: 'opis',
companyName: null,
nip: null,
phone: null,
email: null,
address: null,
status: 'PENDING',
rejectReason: null,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
documents: [],
};
gymClaimsState.push(claim);
if (gymId) {
const g = findVirtualGym(gymId);
if (g) g.claimStatus = 'PENDING';
}
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ claim }) });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ claims: gymClaimsState }) });
});
page.route('**/api/v1/gyms/claims/*', (route) => {
const req = route.request();
if (req.method() === 'DELETE') {
const claimId = req.url().match(/claims\/([^/]+)$/)?.[1];
const idx = gymClaimsState.findIndex((c) => c.id === claimId);
if (idx >= 0) {
const [removed] = gymClaimsState.splice(idx, 1);
const gymId = (removed as { gymId: string | null }).gymId;
if (gymId) {
const g = findVirtualGym(gymId);
if (g) g.claimStatus = null;
}
}
return route.fulfill({ status: 204 });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });
});
// ---------- gym invitations (private virtual gyms) ----------
page.route('**/api/v1/gyms/invitations/*', (route) => {
const req = route.request();
const id = req.url().match(/invitations\/([^/]+)(\/(accept|decline))?$/)?.[1];
const action = req.url().match(/invitations\/[^/]+\/(accept|decline)$/)?.[1];
if (req.method() === 'DELETE') {
const idx = gymInvitationState.findIndex((i) => i.id === id);
if (idx >= 0) gymInvitationState.splice(idx, 1);
return route.fulfill({ status: 204 });
}
if (action === 'accept' || action === 'decline') {
const inv = gymInvitationState.find((i) => i.id === id);
if (inv) {
if (action === 'accept') {
const idx = gymInvitationState.findIndex((i) => i.id === id);
if (idx >= 0) gymInvitationState.splice(idx, 1);
} else {
inv.status = 'DECLINED';
}
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ invitation: inv ?? { id } }) });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });
});
page.route('**/api/v1/gyms/invitations', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = JSON.parse(req.postData() || '{}');
gymInviteSeq += 1;
const invitation = {
id: `gym-inv-new-${gymInviteSeq}`,
direction: 'sent',
gym: { id: body.gymId, name: 'Moja Prywatna Wirtualna', location: 'Wrocław', kind: 'VIRTUAL', isPrivate: true },
user: { id: body.userId, firstName: 'Jan', lastName: 'Kowalski', email: 'jan.kowalski@test.local' },
invitedBy: null,
invitedAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 7 * 86400000).toISOString(),
};
gymInvitationState.push(invitation);
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ invitation }) });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ invitations: gymInvitationState }) });
});
// registered last — takes priority over the `invitations/*` glob for the search URL
page.route('**/api/v1/gyms/invitations/search*', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(userSearch) }),
);
// ---------- trainer / trainees ----------
// trailing * — the search URL carries ?firstName=&lastName=
page.route('**/api/v1/trainer/search*', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(userSearch) }),
);
page.route('**/api/v1/trainer/invitations/*', (route) => {
const req = route.request();
if (req.method() === 'DELETE') return route.fulfill({ status: 204 });
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ coaching: { id: 'inv-1', status: 'ACTIVE' } }),
});
});
page.route('**/api/v1/trainer/invitations', (route) => {
const req = route.request();
if (req.method() === 'POST') {
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ coaching: { id: 'inv-new', status: 'PENDING' } }),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(invitations),
});
});
page.route('**/api/v1/trainer/trainees/*/history', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(traineeHistory),
}),
);
page.route('**/api/v1/trainer/trainees/*', (route) => {
const req = route.request();
if (req.method() === 'DELETE') return route.fulfill({ status: 204 });
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(traineeDetail),
});
});
page.route('**/api/v1/trainer/trainees', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(trainees) }),
);
// registered last — takes priority over the wildcard `trainees/*` route
page.route('**/api/v1/trainer/trainees/*/report', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_TRAINEE_REPORT),
}),
);
page.route('**/api/v1/trainer/trainees/*/moves', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_TRAINEE_MOVES),
}),
);
// registered last — takes priority over the wildcard `trainees/*` route
page.route('**/api/v1/trainer/trainees/*/exercise-progress', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_TRAINEE_EXERCISE_PROGRESS),
}),
);
// registered last — takes priority over the wildcard `trainees/*` route.
// Month-aware: treningi tylko w bieżącym miesiącu (puste pozostałe miesiące).
page.route('**/api/v1/trainer/trainees/*/calendar*', (route) => {
const monthParam = route.request().url().match(/[?&]month=(\d{4}-\d{2})/)?.[1] ?? null;
const current = traineeCalendarBody();
const body =
monthParam === null || monthParam === current.month
? current
: { month: monthParam, days: [] };
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(body),
});
});
// ---------- komunikator (messages) ----------
const sentMessages: unknown[] = [];
page.route('**/api/v1/messages/conversations', (route) =>
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(conversations) }),
);
page.route('**/api/v1/messages/conversations/*', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = req.postDataJSON() as { body: string; sessionId?: string; sessionExerciseId?: string };
const attachment = body.sessionId
? body.sessionExerciseId
? {
sessionId: body.sessionId,
sessionDate: '2026-08-24',
plan: 'Plan testowy',
exercise: {
name: 'Przysiady',
sets: [{ index: 0, reps: 10, rir: 2, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }],
},
exercises: [],
}
: {
sessionId: body.sessionId,
sessionDate: '2026-08-24',
plan: 'Plan testowy',
exercise: null,
exercises: [
{ name: 'Przysiady', setsDone: 1, setsTotal: 1 },
{ name: 'Wyciskanie', setsDone: 1, setsTotal: 1 },
],
}
: null;
const msg = {
id: `sent-${sentMessages.length}`,
senderId: 'trainer-1',
body: body.body,
createdAt: new Date().toISOString(),
attachment,
};
sentMessages.push(msg);
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ message: msg }),
});
}
const thread = messageThread as typeof TEST_MESSAGE_THREAD;
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ ...thread, messages: [...thread.messages, ...sentMessages] }),
});
});
// ---------- komentarze pod ćwiczeniami ----------
const newComment = {
id: 'c-new',
authorId: 'trainer-1',
authorName: 'Marek Trener',
body: 'Dobre formowanie',
createdAt: '2026-08-24T11:00:00.000Z',
};
page.route('**/api/v1/me/comments', (route) =>
route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ comment: newComment }) }),
);
page.route('**/api/v1/trainer/trainees/*/comments', (route) => {
const req = route.request();
if (req.method() === 'POST') {
const body = req.postDataJSON() as { body: string; sessionId?: string; sessionExerciseId?: string };
const comment = {
id: `c-${Date.now()}`,
authorId: 'trainer-1',
authorName: 'Marek Trener',
body: body.body,
createdAt: new Date().toISOString(),
};
// dodaj do właściwego ćwiczenia w stateful historii
for (const session of traineeHistory.sessions) {
for (const ex of session.exercises) {
if (ex.id === body.sessionExerciseId) ex.comments.push(comment);
}
}
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ comment }) });
}
return route.fulfill({ status: 204 });
});
// ---------- postępy per ćwiczenie (me) ----------
page.route('**/api/v1/me/exercise-progress', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(TEST_MY_EXERCISE_PROGRESS),
}),
);
}
/**
* Mockuje obszar planów: ćwiczenia, lista (pusta), tworzenie (POST /plans)
* i szczegóły utworzonego planu. Używany do testu tworzenia planu z datą startu.
*/
export function mockPlans(page: Page) {
mockApi(page);
page.route('**/api/v1/exercises', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
exercises: [
{ id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
{ id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
],
}),
}),
);
page.route('**/api/v1/plans/plan-new', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
plan: {
id: 'plan-new',
userId: 'user-test',
canManage: true,
title: 'Plan e2e',
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
gym: null,
creator: null,
weeks: [],
},
}),
}),
);
page.route('**/api/v1/plans', (route) => {
const req = route.request();
if (req.method() === 'POST') {
// echo gymId z ciała żądania (customName w tygodniach nie ma wpływu na odpowiedź)
let gym: { id: string; name: string } | null = null;
try {
const body = req.postDataJSON() as { gymId?: string | null };
if (body.gymId) gym = { id: body.gymId, name: 'Żelazna Świątynia' };
} catch {
// brak ciała — bez siłowni
}
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: 'plan-new', gym } }),
});
}
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ plans: [] }),
});
});
}
/**
* Mockuje plany podopiecznego (trener): ćwiczenia, lista planów podopiecznego,
* szczegóły planu, akcje (aktywuj/porzuć/ukończ) oraz ostatnie wyniki do prefylu.
* Rejestrowane po mockApi — mają pierwszeństwo nad wildcard `trainees/*`.
*/
export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) {
mockApi(page, opts);
page.route('**/api/v1/exercises', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
exercises: [
{ id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
{ id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
],
}),
}),
);
page.route('**/api/v1/trainer/trainees/*/exercise-latest', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ results: TEST_TRAINEE_LATEST_RESULTS }),
}),
);
page.route('**/api/v1/trainer/trainees/*/plans/*', (route) => {
const req = route.request();
const url = req.url();
if (req.method() === 'PATCH' || req.method() === 'DELETE') {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
}
if (
url.includes('/activate') ||
url.includes('/abandon') ||
url.includes('/complete')
) {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
}
if (url.endsWith('/tp-2')) {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_ACTIVE }) });
}
if (url.endsWith('/tp-3')) {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_FINISHED }) });
}
if (url.endsWith('/tp-4')) {
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL_DONE }) });
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: TEST_TRAINEE_PLAN_DETAIL }) });
});
page.route('**/api/v1/trainer/trainees/*/plans', (route) => {
const req = route.request();
if (req.method() === 'POST') {
// echo gymId z ciała żądania (customName w tygodniach nie ma wpływu na odpowiedź)
let gym: { id: string; name: string } | null = null;
try {
const body = req.postDataJSON() as { gymId?: string | null };
if (body.gymId) gym = { id: body.gymId, name: 'Żelazna Świątynia' };
} catch {
// brak ciała — bez siłowni
}
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: 'tp-new', gym } }),
});
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plans: TEST_TRAINEE_PLANS }) });
});
}