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, birthDate: '1996-05-05T00:00:00.000Z', 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.', setsMin: 12, setsMax: 20, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }, { id: 'fa-2', name: 'Nogi', muscle: 'legs', description: 'Przysiady, wykroki.', setsMin: 10, setsMax: 18, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }, ]; /** Domyślna objętość planu (GET /plans/:id/volume) — partie z priorytetów. */ export const TEST_PLAN_VOLUME = { plan: { id: 'plan-v', title: 'Plan objętości', weeksCount: 4, startDate: '2026-10-05', status: 'ACTIVE', }, muscles: [ { muscle: 'chest', planned: { sets: 48, reps: 480 }, actual: { sets: 40, reps: 400 }, extra: { sets: 4 }, missing: { sets: 8 }, completionPct: 83, recommendedRange: { setsMin: 48, setsMax: 80 }, outOfRange: true, }, { muscle: 'legs', planned: { sets: 32, reps: 320 }, actual: { sets: 34, reps: 340 }, extra: { sets: 2 }, missing: { sets: 0 }, completionPct: 100, recommendedRange: { setsMin: 40, setsMax: 72 }, outOfRange: false, }, ], }; 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, planId: 'plan-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_BOARD: { gym: { id: string; name: string }; myStatsOptIn: boolean; rangeDays: number; ranking: { userId: string; nickname: string | null; firstName: string; lastName: string; sessions: number; tonnageKg: number; days: number; }[]; aggregate: { tonnageKg: number; sessions: number; uniqueExercisers: number; muscles: { muscle: string; sets: number; volumeKg: number }[]; }; records: { exerciseId: string; name: string; nameEn: string | null; muscle: string; oneRm: number; date: string; author: { nickname: string | null; firstName: string; lastName: string } | null; }[]; } = { gym: { id: 'gym-1', name: 'Żelazna Świątynia' }, myStatsOptIn: false, rangeDays: 30, ranking: [ { userId: 'u-ala', nickname: 'żelazka', firstName: 'Ala', lastName: 'Nowak', sessions: 8, tonnageKg: 18200, days: 6, }, { userId: 'u-bob', nickname: null, firstName: 'Bob', lastName: 'Kowal', sessions: 5, tonnageKg: 11000, days: 4, }, ], aggregate: { tonnageKg: 42000, sessions: 24, uniqueExercisers: 9, muscles: [ { muscle: 'legs', sets: 40, volumeKg: 21000 }, { muscle: 'chest', sets: 25, volumeKg: 9500 }, ], }, records: [ { exerciseId: 'e-squat', name: 'Przysiady', nameEn: 'Squat', muscle: 'legs', oneRm: 140, date: '2026-09-12T16:00:00.000Z', author: { nickname: 'żelazka', firstName: 'Ala', lastName: 'Nowak' }, }, { exerciseId: 'e-bench', name: 'Wyciskanie leżąc', nameEn: 'Bench press', muscle: 'chest', oneRm: 100, date: '2026-08-30T16:00:00.000Z', author: null, }, ], }; 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; /** Statystyki osobiste GET /me/stats (podstrona profilu + wykres tonażu na przeglądzie). */ export const TEST_ME_STATS = { rangeDays: 90, sessions: { count: 2, sets: 12, reps: 96, avgMinutes: 75 }, tonnageKg: 5200, tonnageAllTimeKg: 42000, topGym: { gymId: 'gym-1', name: 'Żelazna Świątynia', sessions: 2 }, topEquipment: { equipmentId: 'eq-1', name: 'Sztanga', nameEn: null, sets: 8 }, topExercise: { exerciseId: 'ex-1', name: 'Przysiady', nameEn: null, muscle: 'legs', sessions: 2, sets: 8, }, muscles: [ { muscle: 'legs', sets: 8, volumeKg: 3000 }, { muscle: 'chest', sets: 4, volumeKg: 2200 }, ], weekday: [ { dow: 0, sessions: 1 }, { dow: 1, sessions: 0 }, { dow: 2, sessions: 1 }, { dow: 3, sessions: 0 }, { dow: 4, sessions: 0 }, { dow: 5, sessions: 0 }, { dow: 6, sessions: 0 }, ], heatmap: [ { day: 0, hour: 7, count: 1 }, { day: 2, hour: 18, count: 1 }, ], weeklyTonnage: [2000, 2400, 2200, 2600, 2500, 2800, 0, 3000, 2700, 2900, 2400, 2800].map( (volumeKg, i) => ({ weekStart: new Date(Date.UTC(2026, 5, 29 + i * 7)).toISOString(), volumeKg, }), ), records: [ { exerciseId: 'ex-1', name: 'Przysiady', nameEn: null, muscle: 'legs', oneRm: 116.7, date: '2026-08-24T07:00:00.000Z', }, { exerciseId: 'ex-2', name: 'Wyciskanie', nameEn: null, muscle: 'chest', oneRm: 80.6, date: '2026-08-24T07:00:00.000Z', }, ], plans: { completed: 1, abandoned: 0, daysCompleted: 6, daysSkipped: 1 }, }; /** * 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; 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 }), }); }); page.route('**/api/v1/sessions/sess-1/complete', (route) => { abandoned = false; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true, summary: { durationSec: 3000, exercises: 3, sets: 12, bonusSets: 1, reps: 96, tonnageKg: 5400, killstreak: { current: 6, best: 6, newRecord: true, sampleSize: 20, beatCount: 15 }, volume: { ownAvgKg: 4800, ownAvgSessions: 6, globalAvgKg: 4200, globalSample: 30 }, }, }), }); }); } /** * Mockuje dzień z ukończoną sesją (COMPLETED) — tryb tylko do odczytu * z akcją „Wznów trening”. Używane do testu nawigacji „Wstecz” do planu dnia. */ export function mockDayExecutionCompleted(page: Page, opts?: MockApiOptions) { mockApi(page, opts); page.route('**/api/v1/days/day-1', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ day: { ...TEST_DAY, status: 'COMPLETED', sessions: [{ id: 'sess-1', status: 'COMPLETED', 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: 'COMPLETED' } }), }), ); } /** * 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 /plans/shared-by-me (domyślnie: brak planów udostępnionych przeze mnie). */ sharedByMe?: unknown; /** Ciało odpowiedzi GET /plans/templates (domyślnie: brak szablonów). */ planTemplates?: unknown; /** Ciało odpowiedzi GET /plans/templates/:id (domyślnie: 404). */ planTemplateDetail?: unknown; /** Ciało odpowiedzi GET /plans/:id/volume (domyślnie: TEST_PLAN_VOLUME). */ planVolume?: 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/stats (domyślnie: TEST_ME_STATS). */ myStats?: 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 }[] }; /** Aktywna bytność GET /me/presence (domyślnie: brak; stateful: POST check-in aktualizuje). */ presence?: unknown; /** Wpisy GET /me/presence/history (domyślnie: []; check-in zamyka aktywną jako wizytę). */ presenceHistory?: unknown; /** Ciało GET /me/presence/stats (domyślnie: puste statystyki). */ presenceStats?: unknown; /** Ciało GET /gyms/:id/announcements (domyślnie: puste; canManage z właściciela). */ gymAnnouncements?: unknown; /** Ciało GET /gyms/:id/equipment-usage (domyślnie: brak wierszy). */ equipmentUsage?: { equipment: unknown[] }; /** Ciało GET /gyms/:id/presence-stats (domyślnie: przykładowa telemetria bytności). */ gymPresenceStats?: unknown; /** Ciało GET /gyms/:id/contact (member view lub owner threads; domyślnie: stateful member lazy). */ gymContact?: unknown; /** Ciało GET /gym-contact/conversations (skrzynka właściciela; domyślnie: wyprowadzone z memberSends). */ gymContactInbox?: unknown; /** Baza ciała GET /gym-contact/conversations/:id (domyślnie: wątek członka z memberSends). */ gymContactThread?: { role: string; conversation?: unknown; messages: unknown[]; canReply?: boolean; }; /** Ciało GET /gyms/:id/stats/overview (domyślnie: przykładowe KPI REAL + heatmapa). */ gymStats?: unknown; /** Ciało GET /gyms/:id/board (domyślnie: TEST_GYM_BOARD ze stanem zgody). */ gymBoard?: 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_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, sharedByMe, planTemplates, planTemplateDetail, planVolume, myTrainers, history, myStats, bodyParameters, feed, presence, presenceHistory, presenceStats, gymAnnouncements, equipmentUsage, gymPresenceStats, gymContact, gymContactInbox, gymContactThread, gymStats, gymBoard, } = opts; // Stateful: bytność (check-in) — aktywna obecność + zamknięte wizyty; occupancy liczy się z niej. interface MockPresenceVisit { id: string; gymId: string; gymName: string; status: string; source: string; checkedInAt: string; lastActivityAt: string; closedAt: string | null; durationMinutes: number; } const GYM_PRESENCE_INFO: Record = { 'gym-1': { name: 'Żelazna Świątynia', capacity: 50 }, 'gym-2': { name: 'Mega Gym', capacity: null }, }; let activePresence: MockPresenceVisit | null = (presence ?? null) as MockPresenceVisit | null; const presenceVisits: MockPresenceVisit[] = JSON.parse( JSON.stringify(presenceHistory ?? []), ) as MockPresenceVisit[]; const closeActivePresence = () => { if (!activePresence) return; const closedAt = new Date().toISOString(); presenceVisits.unshift({ ...activePresence, status: 'CLOSED', closedAt, durationMinutes: Math.max( 1, Math.round((Date.now() - new Date(activePresence.checkedInAt).getTime()) / 60000), ), }); activePresence = null; }; const occupancyOf = (gymId: string) => (activePresence?.gymId === gymId ? 1 : 0); const withOccupancy = (body: unknown) => { if (!body || typeof body !== 'object') return body; const b = body as { gyms?: { kind?: string; id: string }[] }; if (!Array.isArray(b.gyms)) return body; return { ...b, gyms: b.gyms.map((g) => ({ ...g, currentOccupancy: g.kind === 'REAL' ? occupancyOf(g.id) : null, })), }; }; // 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[] = []; const gymInvitationState: Record[] = ( gymInvitations as { invitations: Record[] } ).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), currentOccupancy: occupancyOf('gym-1'), }, 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 } & Record; page.route('**/api/v1/me', (route) => { const req = route.request(); if (req.method() === 'PATCH') { const patch = (req.postDataJSON() ?? {}) as Record; 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 }), }); }); // Statystyki osobiste (GET /me/stats) — podstrona profilu + mini-wykres tonażu. page.route('**/api/v1/me/stats*', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(myStats ?? TEST_ME_STATS), }), ); // 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 })); }); // GET /me/feed/announcements/:id — szczegóły ogłoszenia (oznacza przeczytane). page.route('**/api/v1/me/feed/announcements/*', (route) => { const id = new URL(route.request().url()).pathname.split('/').at(-1); const item = feedItems.find((i) => i.source === 'announcement' && i.id === id); if (!item) return route.fulfill( feedJson(404, { error: { code: 'NOT_FOUND', message: 'Announcement not found' } }), ); item.read = true; return route.fulfill(feedJson(200, { announcement: item, read: true })); }); 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/plans/shared-by-me', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(sharedByMe ?? { plans: [] }), }), ); // ---------- szablony planów (kind=TEMPLATE) ---------- page.route('**/api/v1/plans/templates/*', (route) => planTemplateDetail ? route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(planTemplateDetail), }) : route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Plan template not found' } }), }), ); page.route('**/api/v1/plans/templates', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(planTemplates ?? { templates: [] }), }), ); page.route('**/api/v1/plans/*/clone', (route) => route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ plan: { id: 'plan-cloned', title: 'Plan e2e', status: 'DRAFT' } }), }), ); page.route('**/api/v1/plans/*/as-template', (route) => route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ plan: { id: 'tpl-new', title: 'Plan e2e', status: 'DRAFT' } }), }), ); page.route('**/api/v1/plans/*/volume', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(planVolume ?? TEST_PLAN_VOLUME), }), ); 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) => { const req = route.request(); if (req.method() !== 'POST') return route.fallback(); const gymId = req.url().match(/gyms\/([^/]+)\/join/)?.[1] ?? TEST_GYM_JOINABLE.id; joinedGyms.add(gymId); return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ membership: { gymId, 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(withOccupancy(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, }, }), }); } // GET: własna siłownia ma jeden wyjątek (pokrywa pasek godzin w widoku detalu) if (req.url().includes(`/gyms/${TEST_GYM_OWNED.id}/exceptions`)) { return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ exceptions: [ { id: 'ex-existing', gymId: TEST_GYM_OWNED.id, date: '2026-12-24', availability: { start: '10:00', end: '14:00' }, }, ], }), }); } 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 }); } // GET — dla gym-2 oddaję dołączalną Mega Gym (deep-link check-in testuje inną siłownię) const segId = req.url().match(/gyms\/([^/?]+)/)?.[1] ?? ''; if (segId === TEST_GYM_JOINABLE.id) { return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ gym: { ...TEST_GYM_JOINABLE, currentOccupancy: occupancyOf(TEST_GYM_JOINABLE.id) }, roles: [], isAdmin: false, }), }); } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ gym: { ...TEST_GYM_OWNED, equipment: ownedGymEquipment, currentOccupancy: occupancyOf('gym-1'), }, }), }); }); // ---------- galeria zdjęć (siłownia REAL gym-1) ---------- // 1x1 transparent PNG — wystarczające, by 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() }), ); // ---------- ogłoszenia siłowni + mapa ciepła urządzeń (podstrony) ---------- page.route('**/api/v1/gyms/*/announcements', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymAnnouncements ?? { announcements: [], canManage: false }), }), ); page.route('**/api/v1/gyms/*/equipment-usage*', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(equipmentUsage ?? { equipment: [] }), }), ); // 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" 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), }), ); // ---------- bytność (check-in, QR, occupancy) ---------- page.route('**/api/v1/gyms/*/check-in', (route) => { const req = route.request(); if (req.method() !== 'POST') return route.fallback(); const gymId = req.url().match(/gyms\/([^/]+)\/check-in/)?.[1] ?? ''; const info = GYM_PRESENCE_INFO[gymId] ?? { name: gymId, capacity: null }; const src = (req.postDataJSON() as { source?: string } | null)?.source ?? 'MANUAL'; if (activePresence && activePresence.gymId === gymId) { return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }), }); } closeActivePresence(); const now = new Date().toISOString(); activePresence = { id: 'presence-1', gymId, gymName: info.name, gymCapacity: info.capacity, status: 'ACTIVE', source: src, checkedInAt: now, lastActivityAt: now, closedAt: null, durationMinutes: 0, }; return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }), }); }); page.route('**/api/v1/me/presence/check-out', (route) => { closeActivePresence(); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ checkedOut: true }), }); }); page.route('**/api/v1/me/presence/heartbeat', (route) => { // heartbeat odświeża slot — globalny modal keep-alive zamyka się po potwierdzeniu if (activePresence) activePresence.lastActivityAt = new Date().toISOString(); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ touched: activePresence != null }), }); }); page.route('**/api/v1/me/presence/history*', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ visits: presenceVisits }), }), ); page.route('**/api/v1/me/presence/stats', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify( presenceStats ?? { stats: { visits: presenceVisits.length, avgStayMinutes: null, heatmap: [], topGyms: [], peak: 0, topEquipment: [], }, }, ), }), ); page.route('**/api/v1/me/presence', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ presence: activePresence }), }), ); // zmiana siłowni planu (modal rozpoczęcia treningu) page.route('**/api/v1/plans/*/gym', (route) => { const req = route.request(); if (req.method() !== 'PATCH') return route.fallback(); const planId = req.url().match(/plans\/([^/]+)\/gym/)?.[1] ?? ''; const gymId = (req.postDataJSON() as { gymId?: string | null } | null)?.gymId ?? null; const info = gymId ? (GYM_PRESENCE_INFO[gymId] ?? { name: gymId }) : null; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: { id: planId, gym: gymId ? { id: gymId, name: info!.name } : null }, }), }); }); // ---------- kontakt członek ↔ właściciele + statystyki właściciela ---------- interface GymContactMsg { id: string; senderId: string; senderName: string; body: string; createdAt: string; } const MEMBER_NAME = `${TEST_USER.firstName} ${TEST_USER.lastName}`; const OWNER_NAME = 'Marek Trener'; // stateful: wysłane przez członka (TEST_USER) i przez właściciela (odpowiedzi) const memberSends: GymContactMsg[] = []; const ownerReplies: GymContactMsg[] = []; let lastSendGymId = ''; // dołączenia (POST /gyms/:id/join) — role w detalu VIRTUAL publicznej const joinedGyms = new Set(); const gymNameOf = (gymId: string) => findVirtualGym(gymId)?.name ?? (gymId === TEST_GYM_OWNED.id ? TEST_GYM_OWNED.name : gymId === TEST_GYM_JOINABLE.id ? TEST_GYM_JOINABLE.name : gymId); const memberConversation = () => memberSends.length === 0 ? null : { id: 'gconv-1', gymId: lastSendGymId, gymName: gymNameOf(lastSendGymId), userId: TEST_USER.id, memberName: MEMBER_NAME, createdAt: memberSends[0].createdAt, updatedAt: memberSends[memberSends.length - 1].createdAt, }; // GET /gyms/:id/contact — member (leniwy wątek) albo owner (lista wątków, gdy podano ciało). page.route('**/api/v1/gyms/*/contact', (route) => { if (gymContact !== undefined) return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymContact), }); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ role: 'member', conversation: memberConversation(), messages: [...memberSends], canReply: true, }), }); }); // POST /gyms/:id/contact/messages — członek inicjuje/odpowiada (upsert per [gymId,userId]). page.route('**/api/v1/gyms/*/contact/messages', (route) => { const req = route.request(); if (req.method() !== 'POST') return route.fallback(); const gymId = req.url().match(/gyms\/([^/]+)\/contact\/messages/)?.[1] ?? ''; lastSendGymId = gymId; const body = (req.postDataJSON() ?? {}) as { body?: string }; const msg: GymContactMsg = { id: `gmsg-m-${memberSends.length}`, senderId: TEST_USER.id, senderName: MEMBER_NAME, body: body.body ?? '', createdAt: new Date().toISOString(), }; memberSends.push(msg); return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ conversation: memberConversation() }), }); }); // GET /gym-contact/conversations — skrzynka właściciela. page.route('**/api/v1/gym-contact/conversations', (route) => { if (gymContactInbox !== undefined) return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymContactInbox), }); const conv = memberConversation(); const last = memberSends[memberSends.length - 1]; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ conversations: conv ? [ { id: conv.id, gymId: conv.gymId, gymName: conv.gymName, userId: conv.userId, counterpartName: MEMBER_NAME, lastMessageBody: last?.body ?? null, lastMessageAt: last?.createdAt ?? null, unreadCount: 0, }, ] : [], }), }); }); // POST /gym-contact/conversations/:id/messages — odpowiedź właściciela. page.route('**/api/v1/gym-contact/conversations/*/messages', (route) => { const req = route.request(); if (req.method() !== 'POST') return route.fallback(); const body = (req.postDataJSON() ?? {}) as { body?: string }; const msg: GymContactMsg = { id: `gmsg-o-${ownerReplies.length}`, senderId: 'owner-1', senderName: OWNER_NAME, body: body.body ?? '', createdAt: new Date().toISOString(), }; ownerReplies.push(msg); return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ message: msg }), }); }); // GET /gym-contact/conversations/:id — pojedynczy wątek (read-mark po stronie API pominięty). page.route('**/api/v1/gym-contact/conversations/*', (route) => { if (gymContactThread !== undefined) return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ...gymContactThread, messages: [...(gymContactThread.messages ?? []), ...ownerReplies], }), }); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ role: 'member', conversation: memberConversation(), messages: [...memberSends], canReply: true, }), }); }); // DELETE /gym-contact/messages/:id — tylko autor (twardy delete). page.route('**/api/v1/gym-contact/messages/*', (route) => { const id = route .request() .url() .match(/messages\/([^/?]+)/)?.[1]; const mi = memberSends.findIndex((m) => m.id === id); if (mi >= 0) memberSends.splice(mi, 1); const oi = ownerReplies.findIndex((m) => m.id === id); if (oi >= 0) ownerReplies.splice(oi, 1); return route.fulfill({ status: 204 }); }); // GET /gyms/:id/presence-stats — telemetria bytności (widok ogólny REAL, każdy zalogowany). page.route('**/api/v1/gyms/*/presence-stats*', (route) => { const body = gymPresenceStats ?? { gym: { id: 'gym-1', name: TEST_GYM_OWNED.name, kind: 'REAL', capacity: 50 }, stats: { visits: 96, avgStayMinutes: 68, heatmap: [ { day: 0, hour: 18, count: 5 }, { day: 2, hour: 17, count: 3 }, ], topGyms: [], peak: 5, topEquipment: [{ equipmentId: 'eq-1', name: 'ławka', nameEn: 'bench', count: 41 }], live: 7, visitsPerDay: 3.2, }, }; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body), }); }); // GET /gyms/:id/stats/overview — KPI + heatmapa (REAL, właściciel/admin). page.route('**/api/v1/gyms/*/stats/overview*', (route) => { const body = gymStats ?? { gym: { id: 'gym-1', name: TEST_GYM_OWNED.name, kind: 'REAL', capacity: 50 }, presence: { visits: 42, visitsPerDay: 1.4, avgStayMinutes: 75, peak: 5, live: 2, heatmap: [{ day: 0, hour: 18, count: 3 }], }, members: { total: 12, byRole: { OWNER: 1, TRAINER: 2, MEMBER: 9 }, newInRange: 4 }, activity: { sessionsStarted: 20, sessionsCompleted: 17, sessionsAbandoned: 3, uniqueExercisers: 6, }, }; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body), }); }); // GET /gyms/:id/board + PATCH /gyms/:id/stats-consent — tablica REAL ze stanem // zgody: po włączeniu opt-in TEST_USER dostaje wiersz rankingu i autora rekordu. // Rejestrowane po ogólnym gyms/* (Playwright: odwrotna kolejność priorytetu). let boardOptIn = false; page.route('**/api/v1/gyms/*/board*', (route) => { if (gymBoard) return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(gymBoard), }); const body: typeof TEST_GYM_BOARD = JSON.parse(JSON.stringify(TEST_GYM_BOARD)); body.myStatsOptIn = boardOptIn; const range = new URL(route.request().url()).searchParams.get('range'); body.rangeDays = range ? Number(range) : 30; if (boardOptIn) { body.ranking.push({ userId: TEST_USER.id, nickname: TEST_USER.nickname, firstName: TEST_USER.firstName, lastName: TEST_USER.lastName, sessions: 3, tonnageKg: 5200, days: 3, }); body.records[1].author = { nickname: TEST_USER.nickname, firstName: TEST_USER.firstName, lastName: TEST_USER.lastName, }; } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body), }); }); page.route('**/api/v1/gyms/*/stats-consent', (route) => { const enabled = Boolean( (JSON.parse(route.request().postData() ?? '{}') as { enabled?: boolean }).enabled, ); boardOptIn = enabled; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ statsOptIn: boardOptIn }), }); }); // Detale publicznej/prywatnej VIRTUAL (GET /gyms/gym-v1|gym-v2) — przeniesione // akcje (dołącz/ocena/zaproszenia/claim) operują na detalu, więc GET musi // zwracać siłownię + role + isAdmin (rejestrowane po ogólnym gyms/*). page.route('**/api/v1/gyms/gym-v1', (route) => { const g = findVirtualGym('gym-v1'); if (!g) return route.fallback(); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ gym: { ...g, photos: [] }, roles: joinedGyms.has('gym-v1') ? ['MEMBER'] : [], isAdmin: false, }), }); }); page.route('**/api/v1/gyms/gym-v2', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ gym: { ...privateVirtualGym, photos: [] }, roles: ['OWNER'], isAdmin: false, }), }), ); } /** * 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('/suspend') || 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 }), }); }); // POST /trainer/trainees/:id/plans/from-template/:templateId — klon szablonu trenera. // Rejestrowany po wildcardzie plans/* — ma pierwszeństwo (odwrotna kolejność rejestracji). page.route('**/api/v1/trainer/trainees/*/plans/from-template/*', (route) => route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ plan: { id: 'tp-from-tpl', title: 'Plan e2e', status: 'DRAFT' } }), }), ); } /** * Mockuje plan właściciela (ACTIVE) ze statefulnym zawieszeniem/wznowieniem: * POST /plans/plan-p/suspend -> SUSPENDED, POST /plans/plan-p/resume -> ACTIVE. * Używane w teście zawieszania planu (pauza bez utraty zaplanowanych dni). */ export function mockPlanSuspendFlow(page: Page) { mockApi(page); let status: 'ACTIVE' | 'SUSPENDED' = 'ACTIVE'; const planJson = () => ({ id: 'plan-p', userId: 'user-test', title: 'Plan pauzy', status, weeksCount: 1, startDate: '2026-08-24', gym: null, creator: null, canManage: true, shares: [], progress: { completed: 0, total: 1, percent: 0 }, weeks: [ { id: 'pw-1', index: 0, customName: null, days: [ { id: 'pd-1', dayOfWeek: 1, date: '2026-08-24T00:00:00.000Z', status: 'PLANNED', moveLog: [], sessions: [], exercises: [ { id: 'pex-1', exerciseId: 'ex-1', order: 0, exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' }, sets: [ { id: 'ps-1', index: 0, reps: 10, loadKg: null, restSec: null, rir: null, cardioBpm: null, timeSec: null, speed: null, }, ], }, ], }, ], }, ], }); page.route('**/api/v1/plans/plan-p/suspend', (route) => { status = 'SUSPENDED'; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true, title: 'Plan pauzy' }), }); }); page.route('**/api/v1/plans/plan-p/resume', (route) => { status = 'ACTIVE'; return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true, title: 'Plan pauzy', movedDays: 0 }), }); }); page.route('**/api/v1/plans/plan-p', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plan: planJson() }), }), ); page.route('**/api/v1/plans', (route) => { if (route.request().method() !== 'GET') return route.fallback(); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plans: [planJson()] }), }); }); }