diff --git a/AGENTS.md b/AGENTS.md index f2904a9..18da1ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,8 +24,8 @@ Jesteś seniorskim inżynierem oprogramowania. Nigdy nie zgaduj. Jeśli nie jest - Adres API w app: `app/public/config.js` (`window.__FITOS_CONFIG__.apiUrl`) — runtime, bez rebuildu; `VITE_API_URL` tylko fallback build-time. ## Inwarianty domenowe (złamanie nie wyłapią lint/testy) -- Maszyny stanów: plan draft→active→completed/abandoned; dzień planned→completed/skipped (auto-wygasanie 23:59); sesja in_progress→completed/abandoned (auto-abandon po 24h, jedna aktywna na dzień). -- Killstreak: kolejne skuteczne treningi (wszystkie serie = zaplanowane + dodane); reset po pominięciu lub dniu częściowym — `services/killstreak.ts`. +- Maszyny stanów: plan draft→active→completed/abandoned; dzień planned→completed/skipped (auto-wygasanie po upływie dnia w schedulerze, strefa `TZ` kontenera); sesja in_progress→completed/abandoned (auto-abandon po 24h → dzień skipped; jedna aktywna na dzień — pilnowane też częściowym indeksem unikalnym w bazie; ukończenie sesji nie przywraca dnia skipped). +- Killstreak: kolejne skuteczne treningi (skuteczny = wszystkie serie planowe zapisane + każde dodane ćwiczenie ma ≥1 zapisaną serię; serie nadprogramowe = bonus bez wpływu); liczone z planów active+completed; reset po pominięciu lub dniu częściowym — `services/killstreak.ts`. - Scheduler: `services/scheduler.ts`. Pełne zasady: README „Kluczowe decyzje (MVP)". ## Testy — obowiązkowe po każdej zmianie diff --git a/README.md b/README.md index f3f00e9..5f6146b 100644 --- a/README.md +++ b/README.md @@ -101,11 +101,11 @@ Uruchamianie: `npm test` (pojedynczy przebieg) lub `npm run test:watch`; e2e (ap ## Kluczowe decyzje (MVP) -- Autoryzacja: e-mail + hasło, JWT access (15 min, header) + refresh (7 dni, httpOnly cookie), `token_version` do odwołania. +- Autoryzacja: e-mail + hasło, JWT access (15 min, header) + refresh (7 dni, httpOnly cookie, rotacja przy każdym odświeżeniu), `token_version` do odwołania (globalnie per użytkownik). - Plan: draft → active → completed/abandoned; tygodnie zdefiniowane osobno; data startu (poniedziałek) — można ją podać przy tworzeniu (plan tworzony i aktywowany w jednym kroku) albo później przy aktywacji; daty dni liczone automatycznie. -- Dzień: planned → completed/skipped; auto-wygasanie o 23:59 → skipped (scheduler). -- Sesja: in_progress → completed/abandoned; auto-abandon po 24h (scheduler); jedna aktywna sesja na dzień. -- Killstreak: liczba kolejnych skutecznych treningów (wszystkie serie sesji = zaplanowane + dodane); reset po pominięciu lub dniu częściowym. +- Dzień: planned → completed/skipped; auto-wygasanie po upływie dnia (scheduler, co 60 s; strefa serwera = `TZ`, domyślnie Europe/Warsaw) → skipped; sesja toczona na wygasłym dniu jest porzucana razem z nim. +- Sesja: in_progress → completed/abandoned; auto-abandon po 24h (scheduler) — dzień takiej sesji staje się skipped (jak przy ręcznym porzuceniu); jedna aktywna sesja na dzień (pilnowana też indeksem unikalnym w bazie); ukończenie nie „ożywia" dnia skipped. +- Killstreak: liczba kolejnych skutecznych treningów — skuteczny = wszystkie serie planowe zapisane + każde dodane ćwiczenie ma ≥1 zapisaną serię; serie nadprogramowe (bonus) bez wpływu; liczone z planów active i completed; reset po pominięciu lub dniu częściowym. - Pula ćwiczeń: seed (idempotentny upsert po slug + seed_version), cała pula dostępna w MVP (bez filtrowania przez sprzęt siłowni). - PWA: tylko instalowalność (manifest), bez cache offline. - Panel admina: osobna aplikacja (dodawanie siłowni, zarządzanie użytkownikami i rolami). diff --git a/api/docker-compose.yml b/api/docker-compose.yml index ea604ac..b6f6df2 100644 --- a/api/docker-compose.yml +++ b/api/docker-compose.yml @@ -15,6 +15,9 @@ services: LOG_LEVEL: ${LOG_LEVEL:-info} COOKIE_SECURE: ${COOKIE_SECURE:-false} UPLOAD_DIR: /app/uploads + # Daty treningowe (północ/23:59 dnia) liczone są w strefie procesu — + # kontener musi pracować w strefie użytkowników, nie w UTC. + TZ: ${TZ:-Europe/Warsaw} volumes: - fitos_uploads:/app/uploads depends_on: diff --git a/api/prisma/migrations/20261011000000_one_active_session_per_day/migration.sql b/api/prisma/migrations/20261011000000_one_active_session_per_day/migration.sql new file mode 100644 index 0000000..0fd2d73 --- /dev/null +++ b/api/prisma/migrations/20261011000000_one_active_session_per_day/migration.sql @@ -0,0 +1,3 @@ +-- CreateIndex: at most one IN_PROGRESS session per training day (enforced by the +-- database, so concurrent starts of the same day can never both succeed). +CREATE UNIQUE INDEX "TrainingSession_dayId_in_progress_key" ON "TrainingSession"("dayId") WHERE "status" = 'IN_PROGRESS'; diff --git a/api/src/services/audit.ts b/api/src/services/audit.ts index 591f604..1282be1 100644 --- a/api/src/services/audit.ts +++ b/api/src/services/audit.ts @@ -26,7 +26,10 @@ export async function logActivity(prisma: PrismaClient, input: ActivityLogInput) }, }); } catch (e) { - logger.error({ err: e, action: input.action, actorId: input.actorId }, 'Failed to write activity log'); + logger.error( + { err: e, action: input.action, actorId: input.actorId }, + 'Failed to write activity log', + ); } } @@ -62,11 +65,12 @@ export async function listActivityLogs(prisma: PrismaClient, filters: ActivityLo const where: Prisma.ActivityLogWhereInput = { ...(filters.action ? { action: filters.action } : {}), ...(filters.userId ? { actorId: filters.userId } : {}), + // Granice dat w strefie serwera (jak reszta systemu), nie w UTC. createdAt: filters.from || filters.to ? { - ...(filters.from ? { gte: new Date(`${filters.from}T00:00:00.000Z`) } : {}), - ...(filters.to ? { lte: new Date(`${filters.to}T23:59:59.999Z`) } : {}), + ...(filters.from ? { gte: new Date(`${filters.from}T00:00:00`) } : {}), + ...(filters.to ? { lte: new Date(`${filters.to}T23:59:59.999`) } : {}), } : undefined, }; diff --git a/api/src/services/dashboard.ts b/api/src/services/dashboard.ts index 0c98e09..3648409 100644 --- a/api/src/services/dashboard.ts +++ b/api/src/services/dashboard.ts @@ -6,7 +6,15 @@ export async function getDashboard(prisma: PrismaClient, userId: string) { where: { userId, status: 'ACTIVE' }, }); - const killstreak = activePlan ? await getKillstreak(prisma, userId) : 0; + // Killstreak liczy dni także ze skończonych planów — sam brak aktywnego planu + // (np. minutowa przerwa między planami) nie zeruje wyniku z wczoraj. + const planHistory = activePlan + ? true + : !!(await prisma.trainingPlan.findFirst({ + where: { userId, status: 'COMPLETED' }, + select: { id: true }, + })); + const killstreak = planHistory ? await getKillstreak(prisma, userId) : 0; let nextTraining: { dayId: string; @@ -20,7 +28,9 @@ export async function getDashboard(prisma: PrismaClient, userId: string) { if (activePlan) { const days = await prisma.planDay.findMany({ where: { week: { planId: activePlan.id } }, - include: { exercises: { include: { exercise: { select: { name: true, primaryMuscle: true } } } } }, + include: { + exercises: { include: { exercise: { select: { name: true, primaryMuscle: true } } } }, + }, }); const now = new Date(); @@ -40,9 +50,7 @@ export async function getDashboard(prisma: PrismaClient, userId: string) { } const total = days.length; - const done = days.filter( - (d) => d.status === 'COMPLETED' || d.status === 'SKIPPED', - ).length; + const done = days.filter((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED').length; progress = { completed: done, total, @@ -66,28 +74,30 @@ export async function getDashboard(prisma: PrismaClient, userId: string) { // Missing = planned sets left undone in completed sessions // (planned set count minus planned sets with recorded reps). - const completedSessions = await prisma.trainingSession.findMany({ - where: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } }, - include: { - exercises: { - where: { removed: false, hidden: false }, - include: { - planExercise: { include: { sets: true } }, - sets: { select: { planSetId: true, reps: true } }, - }, + // Agregacje zamiast pełnego wczytywania historii sesji. + const sessionExercises = await prisma.sessionExercise.findMany({ + where: { + removed: false, + hidden: false, + session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } }, + }, + select: { planExercise: { select: { sets: { select: { id: true } } } } }, + }); + const plannedSetCount = sessionExercises.reduce( + (n, ex) => n + (ex.planExercise ? ex.planExercise.sets.length : 0), + 0, + ); + const donePlannedSetCount = await prisma.sessionSet.count({ + where: { + planSetId: { not: null }, + reps: { not: null }, + exercise: { + removed: false, + hidden: false, + session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } }, }, }, }); - let plannedSetCount = 0; - let donePlannedSetCount = 0; - for (const s of completedSessions) { - for (const ex of s.exercises) { - if (ex.planExercise) plannedSetCount += ex.planExercise.sets.length; - for (const st of ex.sets) { - if (st.planSetId != null && st.reps != null) donePlannedSetCount++; - } - } - } missing = { sets: plannedSetCount - donePlannedSetCount }; } diff --git a/api/src/services/killstreak.ts b/api/src/services/killstreak.ts index 2b09e14..c9715ec 100644 --- a/api/src/services/killstreak.ts +++ b/api/src/services/killstreak.ts @@ -11,7 +11,11 @@ export interface EffectiveSession { /** * A training is "effective" (counts toward killstreak) when the user performed - * all sets of the session: planned sets + sets of added exercises. + * the session: every planned (norm) set has reps recorded, and every exercise + * added beyond the plan has at least one recorded set. + * Extra (bonus) sets are exactly that — a bonus: recorded or not, they never + * affect effectiveness (same rule as completing the session, which extras + * never block). */ export function isSessionEffective(session: EffectiveSession): boolean { for (const ex of session.exercises) { @@ -22,10 +26,8 @@ export function isSessionEffective(session: EffectiveSession): boolean { if (!done) return false; } } else { - if (ex.sets.length === 0) return false; - for (const s of ex.sets) { - if (s.reps == null) return false; - } + // Ćwiczenie dodane: bez ani jednej zapisanej serii trening się nie liczy. + if (!ex.sets.some((s) => s.reps != null)) return false; } } return true; @@ -35,11 +37,13 @@ export function isSessionEffective(session: EffectiveSession): boolean { * Killstreak = number of consecutive effective trainings (regardless of day). * Grows by 1 for each effective training; resets to 0 after a skip * (including auto-expired days) or a partially completed day. + * Counts days of ACTIVE and COMPLETED plans — finishing a plan does not wipe + * the streak built the day before its end. */ export async function getKillstreak(prisma: PrismaClient, userId: string): Promise { const days = await prisma.planDay.findMany({ where: { - week: { plan: { userId, status: 'ACTIVE' } }, + week: { plan: { userId, status: { in: ['ACTIVE', 'COMPLETED'] } } }, date: { not: null }, }, orderBy: { date: 'asc' }, diff --git a/api/src/services/scheduler.ts b/api/src/services/scheduler.ts index fdcfa30..3a31ab2 100644 --- a/api/src/services/scheduler.ts +++ b/api/src/services/scheduler.ts @@ -3,10 +3,13 @@ import { logger } from '../lib/logger.js'; /** * Background jobs (every 60s): - * 1. Auto-expire training days at 23:59 of their date -> skipped. - * 2. Auto-abandon sessions after 24h. - * 3. Auto-complete active plans when all days are completed/skipped. - * 4. Remove gym schedule exceptions whose date is in the past. + * 1. Auto-expire training days whose date has passed -> skipped. + * 2. Abandon in-progress sessions belonging to expired days (the day is closed, + * the training can no longer be completed). + * 3. Auto-abandon sessions after 24h; the day they belong to is skipped too + * (same rule as manual abandonment — an abandoned training is not retryable). + * 4. Auto-complete active plans when all days are completed/skipped. + * 5. Remove gym schedule exceptions whose date is in the past. */ export function startScheduler(prisma: PrismaClient): void { const tick = async () => { @@ -20,13 +23,32 @@ export function startScheduler(prisma: PrismaClient): void { }); if (expired.count > 0) logger.info({ count: expired.count }, 'Auto-expired days -> skipped'); - const cutoff = new Date(now.getTime() - 24 * 60 * 60 * 1000); - const abandoned = await prisma.trainingSession.updateMany({ - where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } }, + // Sesja dnia, który wygasł, nigdy nie zostanie już ukończona — porządek natychmiast. + const orphaned = await prisma.trainingSession.updateMany({ + where: { status: 'IN_PROGRESS', day: { status: 'SKIPPED' } }, data: { status: 'ABANDONED', endedAt: now }, }); - if (abandoned.count > 0) - logger.info({ count: abandoned.count }, 'Auto-abandoned sessions (24h)'); + if (orphaned.count > 0) + logger.info({ count: orphaned.count }, 'Abandoned sessions of expired days'); + + const cutoff = new Date(now.getTime() - 24 * 60 * 60 * 1000); + const stale = await prisma.trainingSession.findMany({ + where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } }, + select: { id: true, dayId: true }, + }); + if (stale.length > 0) { + await prisma.trainingSession.updateMany({ + where: { id: { in: stale.map((s) => s.id) } }, + data: { status: 'ABANDONED', endedAt: now }, + }); + // Porzucona sesja nie może pozwalać na ponowne wykonanie dnia — + // dokładnie tak samo jak przy ręcznym porzuceniu sesji. + await prisma.planDay.updateMany({ + where: { id: { in: [...new Set(stale.map((s) => s.dayId))] }, status: 'PLANNED' }, + data: { status: 'SKIPPED', skippedAt: now }, + }); + logger.info({ count: stale.length }, 'Auto-abandoned sessions (24h)'); + } const activePlans = await prisma.trainingPlan.findMany({ where: { status: 'ACTIVE' }, diff --git a/api/src/services/sessions.ts b/api/src/services/sessions.ts index 4b5719e..c149dd0 100644 --- a/api/src/services/sessions.ts +++ b/api/src/services/sessions.ts @@ -45,37 +45,41 @@ export async function startSession(prisma: PrismaClient, dayId: string, userId: }); if (!day || day.week.plan.userId !== userId) throw notFound('Day not found'); if (day.status !== 'PLANNED') throw badRequest('Day is not in planned state'); + // Szybka ścieżka — rozstrzygające sprawdzenie jest w transakcji (pod blokadą). const active = await prisma.trainingSession.findFirst({ where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } } }, orderBy: { startedAt: 'desc' }, }); if (active) throw conflict('You already have an active session'); - const session = await prisma.trainingSession.create({ data: { dayId: day.id } }); - if (day.exercises.length > 0) { - await prisma.sessionExercise.createMany({ - data: day.exercises.map((e) => ({ - sessionId: session.id, - exerciseId: e.exerciseId, - planExerciseId: e.id, - order: e.order, - })), + // Całość musi być atomowa: kopiowanie dnia (sesja + ćwiczenia + serie) nie może + // zostawić „pół-sesji" przy błędzie w połowie zapisu. + // Blokada doradcza per użytkownik serializuje równoległe starty, więc sprawdzenie + // „jedna aktywna sesja" + wstawienie jest wolne od wyścigu; częściowy indeks + // unikalny (dayId WHERE IN_PROGRESS) jest ostatnią linią obrony w bazie. + const session = await prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${userId}))`; + const activeInTx = await tx.trainingSession.findFirst({ + where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } } }, + select: { id: true }, }); - for (const e of day.exercises) { - if (e.sets.length === 0) continue; - const se = await prisma.sessionExercise.findFirst({ - where: { sessionId: session.id, planExerciseId: e.id }, - }); - if (se) { - await prisma.sessionSet.createMany({ - data: e.sets.map((ps) => ({ - exerciseId: se.id, - planSetId: ps.id, - index: ps.index, + if (activeInTx) throw conflict('You already have an active session'); + return tx.trainingSession.create({ + data: { + dayId: day.id, + exercises: { + create: day.exercises.map((e) => ({ + exerciseId: e.exerciseId, + planExerciseId: e.id, + order: e.order, + sets: { + create: e.sets.map((ps) => ({ planSetId: ps.id, index: ps.index })), + }, })), - }); - } - } - } + }, + }, + select: { id: true, status: true }, + }); + }); return { sessionId: session.id, status: session.status }; } @@ -193,8 +197,7 @@ export async function updateExercise( data: UpdateExerciseInput, ) { const exercise = await getExerciseOwned(prisma, exerciseId, userId); - if (exercise.session.status !== 'IN_PROGRESS') - throw badRequest('Session is not in progress'); + if (exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress'); await prisma.sessionExercise.update({ where: { id: exercise.id }, data, @@ -209,8 +212,7 @@ export async function updateExercise( */ export async function addSet(prisma: PrismaClient, exerciseId: string, userId: string) { const exercise = await getExerciseOwned(prisma, exerciseId, userId); - if (exercise.session.status !== 'IN_PROGRESS') - throw badRequest('Session is not in progress'); + if (exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress'); const sets = await prisma.sessionSet.findMany({ where: { exercise: { sessionId: exercise.session.id }, removed: false }, }); @@ -218,8 +220,7 @@ export async function addSet(prisma: PrismaClient, exerciseId: string, userId: s if (pendingNorm > 0) throw badRequest('All planned sets must be recorded before adding an extra set'); const pendingExtra = sets.filter((s) => s.planSetId == null && s.reps == null).length; - if (pendingExtra > 0) - throw badRequest('An extra set is already in progress'); + if (pendingExtra > 0) throw badRequest('An extra set is already in progress'); const maxIndex = await prisma.sessionSet.aggregate({ where: { exerciseId: exercise.id }, _max: { index: true }, @@ -238,12 +239,16 @@ export async function updateSet( ) { const set = await prisma.sessionSet.findUnique({ where: { id: setId }, - include: { exercise: { include: { session: { include: { day: { include: { week: { include: { plan: true } } } } } } } } }, + include: { + exercise: { + include: { + session: { include: { day: { include: { week: { include: { plan: true } } } } } }, + }, + }, + }, }); - if (!set || set.exercise.session.day.week.plan.userId !== userId) - throw notFound('Set not found'); - if (set.exercise.session.status !== 'IN_PROGRESS') - throw badRequest('Session is not in progress'); + if (!set || set.exercise.session.day.week.plan.userId !== userId) throw notFound('Set not found'); + if (set.exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress'); const updated = await prisma.sessionSet.update({ where: { id: set.id }, data, @@ -258,14 +263,17 @@ export async function updateSet( export async function deleteSet(prisma: PrismaClient, setId: string, userId: string) { const set = await prisma.sessionSet.findUnique({ where: { id: setId }, - include: { exercise: { include: { session: { include: { day: { include: { week: { include: { plan: true } } } } } } } } }, + include: { + exercise: { + include: { + session: { include: { day: { include: { week: { include: { plan: true } } } } } }, + }, + }, + }, }); - if (!set || set.exercise.session.day.week.plan.userId !== userId) - throw notFound('Set not found'); - if (set.planSetId != null) - throw badRequest('Only extra sets can be removed'); - if (set.exercise.session.status !== 'IN_PROGRESS') - throw badRequest('Session is not in progress'); + if (!set || set.exercise.session.day.week.plan.userId !== userId) throw notFound('Set not found'); + if (set.planSetId != null) throw badRequest('Only extra sets can be removed'); + if (set.exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress'); await prisma.sessionSet.update({ where: { id: set.id }, data: { removed: true } }); return { ok: true }; } @@ -283,18 +291,24 @@ export async function completeSession(prisma: PrismaClient, sessionId: string, u 0, ); if (pending > 0) - throw badRequest(`All planned sets must be recorded before completing the session (${pending} remaining)`); + throw badRequest( + `All planned sets must be recorded before completing the session (${pending} remaining)`, + ); const now = new Date(); - await prisma.$transaction([ - prisma.trainingSession.update({ - where: { id: session.id }, + // Atomowe zamknięcie sesji i dnia: dzień można oznaczyć jako wykonany tylko gdy + // wciąż jest zaplanowany — wygasły (SKIPPED) nie może „ożyć" jako COMPLETED. + await prisma.$transaction(async (tx) => { + const s = await tx.trainingSession.updateMany({ + where: { id: session.id, status: 'IN_PROGRESS' }, data: { status: 'COMPLETED', endedAt: now }, - }), - prisma.planDay.update({ - where: { id: session.dayId }, + }); + if (s.count === 0) throw conflict('Session is no longer in progress'); + const d = await tx.planDay.updateMany({ + where: { id: session.dayId, status: 'PLANNED' }, data: { status: 'COMPLETED', completedAt: now }, - }), - ]); + }); + if (d.count === 0) throw conflict('Training day is no longer planned'); + }); return { ok: true }; } @@ -306,15 +320,18 @@ export async function abandonSession(prisma: PrismaClient, sessionId: string, us const session = await getSessionOwned(prisma, sessionId, userId); if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress'); const now = new Date(); - await prisma.$transaction([ - prisma.trainingSession.update({ - where: { id: session.id }, + await prisma.$transaction(async (tx) => { + const s = await tx.trainingSession.updateMany({ + where: { id: session.id, status: 'IN_PROGRESS' }, data: { status: 'ABANDONED', endedAt: now }, - }), - prisma.planDay.update({ - where: { id: session.dayId }, + }); + if (s.count === 0) throw conflict('Session is no longer in progress'); + // Dzień oznaczamy jako pominięty tylko gdy wciąż jest zaplanowany + // (mógł już wygasnąć w schedulerze — wtedy nie nadpisujemy). + await tx.planDay.updateMany({ + where: { id: session.dayId, status: 'PLANNED' }, data: { status: 'SKIPPED', skippedAt: now }, - }), - ]); + }); + }); return { ok: true }; } diff --git a/api/test/unit/killstreak.property.test.ts b/api/test/unit/killstreak.property.test.ts index 029c72b..72d2c25 100644 --- a/api/test/unit/killstreak.property.test.ts +++ b/api/test/unit/killstreak.property.test.ts @@ -84,6 +84,21 @@ describe('isSessionEffective (property-based)', () => { ); }); + it('an unrecorded extra (bonus) set never changes the result', () => { + fc.assert( + fc.property(sessionArb, (session) => { + // dokleja niezapisaną serię nadprogramową do pierwszego widocznego ćwiczenia + const withPendingExtra: EffectiveSession = { + exercises: session.exercises.map((e, i) => + i === 0 ? { ...e, sets: [...e.sets, { planSetId: null, reps: null }] } : e, + ), + }; + return isSessionEffective(session) === isSessionEffective(withPendingExtra); + }), + { numRuns: 200 }, + ); + }); + it('a visible added exercise without sets makes the session ineffective', () => { fc.assert( fc.property(fc.array(exerciseArb), (others) => { diff --git a/api/test/unit/killstreak.test.ts b/api/test/unit/killstreak.test.ts index 5162b01..09854b0 100644 --- a/api/test/unit/killstreak.test.ts +++ b/api/test/unit/killstreak.test.ts @@ -24,6 +24,13 @@ function addedExercise(reps: (number | null)[]): Session { }; } +/** Ćwiczenie planowe z nadprogramową (bonusową) serią o zadanych wartościach. */ +function plannedExerciseWithExtra(reps: (number | null)[], extra: number | null): Session { + const ex = plannedExercise(['ps1'], reps); + ex.sets.push({ planSetId: null, reps: extra }); + return ex; +} + function day( dateOffsetDays: number, status: 'PLANNED' | 'COMPLETED' | 'SKIPPED', @@ -81,21 +88,33 @@ describe('isSessionEffective', () => { expect(isSessionEffective(session)).toBe(true); }); - it('counts added exercises (no planExercise) — all sets need reps', () => { + it('counts added exercises (no planExercise) — at least one set with reps', () => { const session: EffectiveSession = { exercises: [addedExercise([10, 12])] }; expect(isSessionEffective(session)).toBe(true); }); - it('added exercise with a set without reps is not effective', () => { - const session: EffectiveSession = { exercises: [addedExercise([10, null])] }; + it('added exercise with only an unrecorded (bonus) set is not effective', () => { + const session: EffectiveSession = { exercises: [addedExercise([null])] }; expect(isSessionEffective(session)).toBe(false); }); + it('unrecorded extra set of an added exercise is a bonus and does not hurt', () => { + const session: EffectiveSession = { exercises: [addedExercise([10, null])] }; + expect(isSessionEffective(session)).toBe(true); + }); + it('added exercise without any sets is not effective', () => { const session: EffectiveSession = { exercises: [addedExercise([])] }; expect(isSessionEffective(session)).toBe(false); }); + it('unrecorded extra set of a planned exercise is a bonus and does not hurt', () => { + const session: EffectiveSession = { + exercises: [plannedExerciseWithExtra([10], null)], + }; + expect(isSessionEffective(session)).toBe(true); + }); + it('empty session (no exercises) is effective', () => { expect(isSessionEffective({ exercises: [] })).toBe(true); }); @@ -166,4 +185,17 @@ describe('getKillstreak', () => { ]), ).toBe(1); }); + + it('counts days of active and completed plans (finished plan keeps the streak)', async () => { + await run([day(-1, 'COMPLETED', [[plannedExercise(['ps1'], [10])]])]); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + week: expect.objectContaining({ + plan: expect.objectContaining({ status: { in: ['ACTIVE', 'COMPLETED'] } }), + }), + }), + }), + ); + }); }); diff --git a/api/test/unit/scheduler.test.ts b/api/test/unit/scheduler.test.ts index 6a98533..de92b3e 100644 --- a/api/test/unit/scheduler.test.ts +++ b/api/test/unit/scheduler.test.ts @@ -3,12 +3,13 @@ import { startScheduler } from '../../src/services/scheduler.js'; const planDayUpdateMany = vi.fn(); const sessionUpdateMany = vi.fn(); +const sessionFindMany = vi.fn(); const planFindMany = vi.fn(); const planUpdate = vi.fn(); const prisma = { planDay: { updateMany: planDayUpdateMany }, - trainingSession: { updateMany: sessionUpdateMany }, + trainingSession: { updateMany: sessionUpdateMany, findMany: sessionFindMany }, trainingPlan: { findMany: planFindMany, update: planUpdate }, } as never; @@ -25,6 +26,7 @@ beforeEach(() => { vi.setSystemTime(NOW); planDayUpdateMany.mockReset().mockResolvedValue({ count: 0 }); sessionUpdateMany.mockReset().mockResolvedValue({ count: 0 }); + sessionFindMany.mockReset().mockResolvedValue([]); planFindMany.mockReset().mockResolvedValue([]); planUpdate.mockReset().mockResolvedValue({}); }); @@ -43,15 +45,41 @@ describe('scheduler', () => { expect(planDayUpdateMany.mock.calls[0][0].data.skippedAt).toEqual(NOW); }); - it('auto-abandons in-progress sessions older than 24h', async () => { + it('abandons in-progress sessions of expired (skipped) days', async () => { await tickOnce(); - const cutoff = new Date(NOW.getTime() - 24 * 60 * 60 * 1000); expect(sessionUpdateMany).toHaveBeenCalledWith({ - where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } }, + where: { status: 'IN_PROGRESS', day: { status: 'SKIPPED' } }, data: { status: 'ABANDONED', endedAt: expect.any(Date) }, }); }); + it('auto-abandons in-progress sessions older than 24h and skips their days', async () => { + sessionFindMany.mockResolvedValue([{ id: 's1', dayId: 'd1' }, { id: 's2', dayId: 'd2' }]); + await tickOnce(); + const cutoff = new Date(NOW.getTime() - 24 * 60 * 60 * 1000); + expect(sessionFindMany).toHaveBeenCalledWith({ + where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } }, + select: { id: true, dayId: true }, + }); + expect(sessionUpdateMany).toHaveBeenCalledWith({ + where: { id: { in: ['s1', 's2'] } }, + data: { status: 'ABANDONED', endedAt: expect.any(Date) }, + }); + // dzień porzuconej sesji nie może zostać ponownie wykonany (jak przy ręcznym abandon) + expect(planDayUpdateMany).toHaveBeenLastCalledWith({ + where: { id: { in: ['d1', 'd2'] }, status: 'PLANNED' }, + data: { status: 'SKIPPED', skippedAt: expect.any(Date) }, + }); + }); + + it('does not skip days when no stale sessions exist', async () => { + await tickOnce(); + // jedyne wywołania to auto-wygasanie (where po dacie) — brak drugiej tury po stale ids + for (const [args] of planDayUpdateMany.mock.calls) { + expect(args.where).not.toHaveProperty('id'); + } + }); + it('auto-completes an active plan when all days are closed', async () => { planFindMany.mockResolvedValue([ { diff --git a/api/test/unit/services-sessions.test.ts b/api/test/unit/services-sessions.test.ts index 3ee8f1b..5ca7add 100644 --- a/api/test/unit/services-sessions.test.ts +++ b/api/test/unit/services-sessions.test.ts @@ -2,9 +2,15 @@ import { describe, it, expect, vi } from 'vitest'; import { abandonSession, addExercise, addSet, completeSession, deleteSet, getActiveSession, startSession } from '../../src/services/sessions.js'; function mockPrisma() { - return { - planDay: { findUnique: vi.fn(), update: vi.fn() }, - trainingSession: { findUnique: vi.fn(), findFirst: vi.fn(), create: vi.fn(), update: vi.fn() }, + const prisma: any = { + planDay: { findUnique: vi.fn(), update: vi.fn(), updateMany: vi.fn() }, + trainingSession: { + findUnique: vi.fn(), + findFirst: vi.fn(), + create: vi.fn(), + update: vi.fn(), + updateMany: vi.fn(), + }, sessionExercise: { findUnique: vi.fn(), findFirst: vi.fn(), @@ -23,8 +29,14 @@ function mockPrisma() { aggregate: vi.fn(), }, exercise: { findUnique: vi.fn() }, + $executeRaw: vi.fn().mockResolvedValue(1), $transaction: vi.fn(), }; + // transakcja interaktywna: callback dostaje ten sam obiekt (tx === prisma w mocku) + prisma.$transaction.mockImplementation(async (cb: (tx: unknown) => Promise) => + cb(prisma), + ); + return prisma; } const ownedDay = { @@ -69,27 +81,50 @@ describe('startSession', () => { }); }); - it('creates a session with exercises and planned sets', async () => { + it('creates a session with exercises and planned sets in one transaction', async () => { const prisma = mockPrisma(); prisma.planDay.findUnique.mockResolvedValue(ownedDay); prisma.trainingSession.findFirst.mockResolvedValue(null); prisma.trainingSession.create.mockResolvedValue({ id: 's1', status: 'IN_PROGRESS' }); - prisma.sessionExercise.createMany.mockResolvedValue({ count: 2 }); - prisma.sessionExercise.findFirst.mockResolvedValue({ id: 'se1' }); - prisma.sessionSet.createMany.mockResolvedValue({ count: 1 }); const result = await startSession(prisma, 'd1', 'u1'); expect(result).toEqual({ sessionId: 's1', status: 'IN_PROGRESS' }); - expect(prisma.sessionExercise.createMany).toHaveBeenCalledWith({ - data: [ - { sessionId: 's1', exerciseId: 'pz1', planExerciseId: 'pe1', order: 0 }, - { sessionId: 's1', exerciseId: 'pz2', planExerciseId: 'pe2', order: 1 }, - ], + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + // blokada doradcza per użytkownik serializuje równoległe starty + expect(prisma.$executeRaw).toHaveBeenCalled(); + // całe drzewo (ćwiczenia + serie) tworzone jednym zagnieżdżonym create + expect(prisma.trainingSession.create).toHaveBeenCalledWith({ + data: { + dayId: 'd1', + exercises: { + create: [ + { + exerciseId: 'pz1', + planExerciseId: 'pe1', + order: 0, + sets: { create: [{ planSetId: 'ps1', index: 0 }] }, + }, + { exerciseId: 'pz2', planExerciseId: 'pe2', order: 1, sets: { create: [] } }, + ], + }, + }, + select: { id: true, status: true }, }); - expect(prisma.sessionSet.createMany).toHaveBeenCalledWith({ - data: [{ exerciseId: 'se1', planSetId: 'ps1', index: 0 }], + }); + + it('409 when a concurrent start won the race (second in-transaction check)', async () => { + const prisma = mockPrisma(); + prisma.planDay.findUnique.mockResolvedValue(ownedDay); + // wyścig: szybka ścieżka przechodzi, sprawdzienie w transakcji już widzi aktywną sesję + prisma.trainingSession.findFirst + .mockResolvedValueOnce(null) + .mockResolvedValueOnce({ id: 's-active' }); + await expect(startSession(prisma, 'd1', 'u1')).rejects.toMatchObject({ + status: 409, + message: 'You already have an active session', }); + expect(prisma.trainingSession.create).not.toHaveBeenCalled(); }); }); @@ -175,10 +210,49 @@ describe('completeSession', () => { ], }, ]); - prisma.$transaction.mockResolvedValue([{}, {}]); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + prisma.planDay.updateMany.mockResolvedValue({ count: 1 }); await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({ ok: true }); - expect(prisma.$transaction).toHaveBeenCalled(); + // warunkowe updateMany: sesja tylko IN_PROGRESS, dzień tylko PLANNED + expect(prisma.trainingSession.updateMany).toHaveBeenCalledWith({ + where: { id: 's1', status: 'IN_PROGRESS' }, + data: { status: 'COMPLETED', endedAt: expect.any(Date) }, + }); + expect(prisma.planDay.updateMany).toHaveBeenCalledWith({ + where: { id: 'd1', status: 'PLANNED' }, + data: { status: 'COMPLETED', completedAt: expect.any(Date) }, + }); + }); + + it('refuses to revive an expired (skipped) day as completed', async () => { + const prisma = mockPrisma(); + prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress); + prisma.sessionExercise.findMany.mockResolvedValue([ + { id: 'se1', removed: false, sets: [{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false }] }, + ]); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + // dzień wygasł w schedulerze (SKIPPED) — warunkowe updateMany nic nie trafia + prisma.planDay.updateMany.mockResolvedValue({ count: 0 }); + + await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({ + status: 409, + message: 'Training day is no longer planned', + }); + }); + + it('conflicts when the session was concurrently closed', async () => { + const prisma = mockPrisma(); + prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress); + prisma.sessionExercise.findMany.mockResolvedValue([ + { id: 'se1', removed: false, sets: [{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false }] }, + ]); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 0 }); + + await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({ + status: 409, + message: 'Session is no longer in progress', + }); }); it('ignores removed sets when counting pending norm sets', async () => { @@ -194,7 +268,8 @@ describe('completeSession', () => { ], }, ]); - prisma.$transaction.mockResolvedValue([{}, {}]); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + prisma.planDay.updateMany.mockResolvedValue({ count: 1 }); await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({ ok: true }); }); @@ -220,18 +295,35 @@ describe('abandonSession', () => { it('abandons the session and marks the day skipped (the training cannot be executed again)', async () => { const prisma = mockPrisma(); prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress); - prisma.$transaction.mockResolvedValue([{}, {}]); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + prisma.planDay.updateMany.mockResolvedValue({ count: 1 }); const result = await abandonSession(prisma, 's1', 'u1'); expect(result).toEqual({ ok: true }); - expect(prisma.trainingSession.update).toHaveBeenCalledWith( - expect.objectContaining({ where: { id: 's1' }, data: expect.objectContaining({ status: 'ABANDONED' }) }), + expect(prisma.trainingSession.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: 's1', status: 'IN_PROGRESS' }, + data: expect.objectContaining({ status: 'ABANDONED' }), + }), ); - expect(prisma.planDay.update).toHaveBeenCalledWith( - expect.objectContaining({ where: { id: 'd1' }, data: expect.objectContaining({ status: 'SKIPPED' }) }), + // dzień oznaczany tylko gdy wciąż PLANNED (nie nadpisuje wygasłego) + expect(prisma.planDay.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: 'd1', status: 'PLANNED' }, + data: expect.objectContaining({ status: 'SKIPPED' }), + }), ); }); + + it('tolerates an already-expired day when abandoning (day guard counts 0 rows)', async () => { + const prisma = mockPrisma(); + prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + prisma.planDay.updateMany.mockResolvedValue({ count: 0 }); + + await expect(abandonSession(prisma, 's1', 'u1')).resolves.toEqual({ ok: true }); + }); }); describe('addSet', () => {