diff --git a/api/src/lib/strengthStats.ts b/api/src/lib/strengthStats.ts index 010d305..c94d73d 100644 --- a/api/src/lib/strengthStats.ts +++ b/api/src/lib/strengthStats.ts @@ -25,3 +25,31 @@ export function effectiveLoadKg( export function epleyOneRm(loadKg: number, reps: number): number { return loadKg * (1 + reps / 30); } + +/** + * Tonaż sesji: Σ(loadKg × reps) po seriach z obciążeniem z planu i zapisanymi + * powtórzeniami (ta sama definicja co w statystykach). Ćwiczenia usunięte + * wypadają; seria bez planowanego obciążenia (masa ciała) jest poza tonażem. + * null = żadna seria nie ma pary (obciążenie, powtórzenia) — brak tonażu do + * porównań, zamiast mylącego 0. + */ +export function sessionTonnageKg(session: { + exercises: { + removed: boolean; + sets: { planSet: { loadKg: number | null } | null; reps: number | null }[]; + }[]; +}): number | null { + let total = 0; + let any = false; + for (const ex of session.exercises) { + if (ex.removed) continue; + for (const st of ex.sets) { + const loadKg = st.planSet?.loadKg ?? null; + if (loadKg != null && st.reps != null) { + total += loadKg * st.reps; + any = true; + } + } + } + return any ? Math.round(total) : null; +} diff --git a/api/src/routes/sessions.ts b/api/src/routes/sessions.ts index 7aed0ce..51976cc 100644 --- a/api/src/routes/sessions.ts +++ b/api/src/routes/sessions.ts @@ -198,10 +198,13 @@ export function createSessionRoutes({ prisma }: AppDeps) { * /sessions/{id}/complete: * post: * summary: Complete session (requires all planned/norm sets recorded and no extra set - * still in progress — recorded bonus sets don't block; day -> completed) + * still in progress — recorded bonus sets don't block; day -> completed). + * Returns { ok, summary } — summary powers the post-workout celebration modal + * (session stats + killstreak percentile + tonnage vs own/global 30-day averages); + * null when summary computation failed (non-critical). * tags: [Sessions] * responses: - * 200: { description: OK } + * 200: { description: OK — { ok: true, summary: object | null } } * 400: { description: Session not in progress, planned sets still pending, or an extra set in progress } */ router.post( diff --git a/api/src/services/killstreak.ts b/api/src/services/killstreak.ts index 94ce982..7027b55 100644 --- a/api/src/services/killstreak.ts +++ b/api/src/services/killstreak.ts @@ -107,3 +107,68 @@ export async function getKillstreakStats( } return { current: streak, best, effectiveDates }; } + +/** + * Killstreaki bieżące WSZYSTKICH użytkowników posiadających plany + * (ACTIVE/SUSPENDED/COMPLETED) — jeden zbiorczy przebieg dni zamiast N + * osobnych. Reguły identyczne jak getKillstreak; użytkownicy bez dni + * w tym zakresie wypadają z próbki (brak klucza w mapie). + * Używane do porównań spersonalizowanych (np. próg centylowy killstreaka + * w podsumowaniu po treningu). + */ +export async function getAllKillstreaks(prisma: PrismaClient): Promise> { + const days = await prisma.planDay.findMany({ + where: { + week: { plan: { status: { in: ['ACTIVE', 'SUSPENDED', 'COMPLETED'] } } }, + removedAt: null, + date: { not: null }, + }, + orderBy: { date: 'asc' }, + select: { + date: true, + status: true, + week: { select: { plan: { select: { userId: true } } } }, + sessions: { + where: { status: 'COMPLETED' }, + // dzień może mieć wiele ukończonych sesji (po porzuconych) — liczy się najnowsza + orderBy: { endedAt: 'desc' }, + take: 1, + select: { + exercises: { + select: { + hidden: true, + removed: true, + sets: { select: { planSetId: true, reps: true } }, + planExercise: { select: { sets: { select: { id: true } } } }, + }, + }, + }, + }, + }, + }); + + const now = new Date(); + const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); + const streaks = new Map(); + const userIds = [...new Set(days.map((d) => d.week.plan.userId))]; + for (const id of userIds) streaks.set(id, 0); + + // dni posortowane globalnie po dacie — w ramach użytkownika też rosnąco, + // więc przemieszanie użytkowników w przebiegu nie zaburza ich kolejności + for (const day of days) { + if (day.date! >= startOfTomorrow) break; // future day — not yet relevant + const owner = day.week.plan.userId; + if (day.status === 'COMPLETED') { + const session = day.sessions[0]; + if (session && isSessionEffective(session)) { + streaks.set(owner, (streaks.get(owner) ?? 0) + 1); + } else { + streaks.set(owner, 0); + } + } else if (day.status === 'SKIPPED') { + streaks.set(owner, 0); + } + // PLANNED days (today, not yet done) do not change the streak + } + return streaks; +} diff --git a/api/src/services/sessions.ts b/api/src/services/sessions.ts index bfaa66d..ebf93ab 100644 --- a/api/src/services/sessions.ts +++ b/api/src/services/sessions.ts @@ -1,5 +1,7 @@ import type { Prisma, PrismaClient } from '@prisma/client'; import { badRequest, conflict, notFound } from '../lib/errors.js'; +import { sessionTonnageKg } from '../lib/strengthStats.js'; +import { getAllKillstreaks, getKillstreakStats } from './killstreak.js'; import { touchPresenceBestEffort } from './presence.js'; export interface UpdateExerciseInput { @@ -333,6 +335,163 @@ export async function deleteSet(prisma: PrismaClient, setId: string, userId: str return { ok: true }; } +/** + * Podsumowanie po ukończeniu sesji — dane do celebracyjnego okna w aplikacji: + * liczby sesji + killstreak (centyl wobec pozostałych trenujących) + tonaż + * wobec średniej własnej (30 dni) i globalnej (30 dni). Kontrakt liczbowy: + * front układa z tego komunikaty (i18n), serwer nie składa zdań. + * `null` = podsumowanie nie krytyczne — ukończony trening nigdy nie przez nie + * nie spada. + */ +export interface CompletionSummary { + durationSec: number; + exercises: number; + sets: number; + bonusSets: number; + reps: number; + tonnageKg: number | null; + killstreak: { + current: number; + best: number; + newRecord: boolean; + sampleSize: number; + beatCount: number; + }; + volume: { + ownAvgKg: number | null; + ownAvgSessions: number; + globalAvgKg: number | null; + globalSample: number; + }; +} + +/** Siedzące w próbkach porównań — zbyt mała próbka wprowadza w błąd, front wtedy pomija linię. */ +const OWN_AVG_MIN_SESSIONS = 1; +const GLOBAL_AVG_MIN_SESSIONS = 10; + +interface TonnageSessionRow { + id: string; + exercises: { + removed: boolean; + sets: { planSet: { loadKg: number | null } | null; reps: number | null }[]; + }[]; +} + +const tonnageInclude = { + exercises: { + select: { + removed: true, + sets: { select: { planSet: { select: { loadKg: true } }, reps: true } }, + }, + }, +} satisfies Prisma.TrainingSessionInclude; + +/** + * Średni tonaż ukończonych sesji z okna 30 dni (po endedAt), z pominięciem + * bieżącej sesji (porównanie z przeszłością, nie z samym sobą) i sesji bez + * tonażu (masa ciała — nie wchodzi do średniej kg, tak jak do statystyk). + */ +async function avgSessionTonnage( + prisma: PrismaClient, + since: Date, + excludeSessionId: string, + userId?: string, +): Promise<{ avgKg: number | null; sessions: number }> { + const rows = (await prisma.trainingSession.findMany({ + where: { + status: 'COMPLETED', + endedAt: { gte: since }, + id: { not: excludeSessionId }, + ...(userId ? { day: { week: { plan: { userId } } } } : {}), + }, + select: { id: true, exercises: tonnageInclude.exercises }, + })) as TonnageSessionRow[]; + const values: number[] = []; + for (const row of rows) { + const v = sessionTonnageKg(row); + if (v != null) values.push(v); + } + if (values.length === 0) return { avgKg: null, sessions: 0 }; + return { + avgKg: Math.round(values.reduce((a, b) => a + b, 0) / values.length), + sessions: values.length, + }; +} + +async function buildCompletionSummary( + prisma: PrismaClient, + sessionId: string, + userId: string, +): Promise { + const session = await prisma.trainingSession.findUnique({ + where: { id: sessionId }, + select: { + startedAt: true, + endedAt: true, + exercises: { + where: { removed: false }, + select: { + removed: true, + sets: { + where: { removed: false }, + select: { + planSetId: true, + reps: true, + planSet: { select: { loadKg: true } }, + }, + }, + }, + }, + }, + }); + if (!session || !session.endedAt) return null; + + const sets = session.exercises.flatMap((ex) => ex.sets); + const doneSets = sets.filter((s) => s.reps != null); + const durationSec = Math.max( + 0, + Math.round((session.endedAt.getTime() - session.startedAt.getTime()) / 1000), + ); + + const stats = await getKillstreakStats(prisma, userId); + const all = await getAllKillstreaks(prisma); + // próbka = pozostali właściciele planów z co najmniej jednym treningiem w historii + let sampleSize = 0; + let beatCount = 0; + for (const [otherId, streak] of all) { + if (otherId === userId) continue; + if (streak === 0) continue; // nikt nie trenował (jeszcze) — nie jest punktem odniesienia + sampleSize++; + if (stats.current > streak) beatCount++; + } + + const since30d = new Date(Date.now() - 30 * 24 * 3600 * 1000); + const own = await avgSessionTonnage(prisma, since30d, sessionId, userId); + const global = await avgSessionTonnage(prisma, since30d, sessionId); + + return { + durationSec, + exercises: session.exercises.length, + sets: doneSets.length, + bonusSets: doneSets.filter((s) => s.planSetId == null).length, + reps: doneSets.reduce((n, s) => n + (s.reps ?? 0), 0), + tonnageKg: sessionTonnageKg({ exercises: session.exercises }), + killstreak: { + current: stats.current, + best: stats.best, + newRecord: stats.current > 1 && stats.current === stats.best, + sampleSize, + beatCount, + }, + volume: { + ownAvgKg: own.sessions >= OWN_AVG_MIN_SESSIONS ? own.avgKg : null, + ownAvgSessions: own.sessions, + globalAvgKg: global.sessions >= GLOBAL_AVG_MIN_SESSIONS ? global.avgKg : null, + globalSample: global.sessions, + }, + }; +} + export async function completeSession(prisma: PrismaClient, sessionId: string, userId: string) { const session = await getSessionOwned(prisma, sessionId, userId); // Szybka ścieżka dla czytelnego 400; rozstrzygnięcie pod blokadą w transakcji. @@ -386,7 +545,16 @@ export async function completeSession(prisma: PrismaClient, sessionId: string, u }); if (d.count === 0) throw conflict('Training day is no longer planned'); }); - return { ok: true }; + // Podsumowanie liczone PO commitcie (dane sesji już zamknięte); nie może + // zepsuć ukończenia treningu — przy awarii zwracamy null i front wyświetli + // zwykły toast zamiast okna celebracji. + let summary: CompletionSummary | null = null; + try { + summary = await buildCompletionSummary(prisma, session.id, userId); + } catch { + summary = null; + } + return { ok: true, summary }; } /** diff --git a/api/src/swagger.ts b/api/src/swagger.ts index f35f208..5f73bfe 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -1854,9 +1854,14 @@ export const openapi: Record = { '/sessions/{id}/complete': { post: { tags: ['Sessions'], - summary: 'Complete session (requires all sets recorded; day -> completed)', + summary: + 'Complete session (requires all sets recorded; day -> completed). Returns { ok, summary: { durationSec, exercises, sets, bonusSets, reps, tonnageKg|null, killstreak: { current, best, newRecord, sampleSize, beatCount }, volume: { ownAvgKg|null, ownAvgSessions, globalAvgKg|null, globalSample } } | null } — summary feeds the post-workout celebration modal (null = non-critical failure)', security: [{ bearerAuth: [] }], parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + responses: { + 200: { description: 'OK — { ok: true, summary }' }, + 400: { description: 'Session not in progress or planned/bonus sets still pending' }, + }, }, }, '/sessions/{id}/abandon': { diff --git a/api/test/integration/sessions.test.ts b/api/test/integration/sessions.test.ts index 6663142..7eb08c4 100644 --- a/api/test/integration/sessions.test.ts +++ b/api/test/integration/sessions.test.ts @@ -545,6 +545,21 @@ describe('sessions routes', () => { .post(`/api/v1/sessions/${sessionId}/complete`) .set('Authorization', `Bearer ${token}`); expect(res.status).toBe(200); + expect(res.body.ok).toBe(true); + + // podsumowanie celebracyjne: liczby sesji + killstreak + średnie tonażu + const sm = res.body.summary; + expect(sm).toBeTruthy(); + expect(typeof sm.durationSec).toBe('number'); + expect(sm.exercises).toBeGreaterThanOrEqual(1); + expect(sm.sets).toBeGreaterThanOrEqual(2); + expect(sm.reps).toBeGreaterThan(0); + expect(typeof sm.tonnageKg).toBe('number'); + expect(sm.killstreak.current).toBeGreaterThanOrEqual(0); + expect(sm.killstreak).toHaveProperty('best'); + expect(sm.killstreak).toHaveProperty('newRecord'); + expect(sm.volume).toHaveProperty('ownAvgKg'); + expect(sm.volume).toHaveProperty('globalAvgKg'); const day = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`); expect(day.body.day.status).toBe('COMPLETED'); diff --git a/api/test/unit/killstreak.test.ts b/api/test/unit/killstreak.test.ts index 3a93646..be1d826 100644 --- a/api/test/unit/killstreak.test.ts +++ b/api/test/unit/killstreak.test.ts @@ -3,6 +3,7 @@ import { isSessionEffective, getKillstreak, getKillstreakStats, + getAllKillstreaks, type EffectiveSession, } from '../../src/services/killstreak.js'; @@ -198,10 +199,7 @@ describe('getKillstreak', () => { it('planned days do not change the streak', async () => { expect( - await run([ - day(-1, 'COMPLETED', [[plannedExercise(['ps1'], [10])]]), - day(0, 'PLANNED'), - ]), + await run([day(-1, 'COMPLETED', [[plannedExercise(['ps1'], [10])]]), day(0, 'PLANNED')]), ).toBe(1); }); @@ -270,3 +268,50 @@ describe('getKillstreakStats', () => { expect(res.effectiveDates.map((d) => d.getDate())).toEqual([12, 20]); }); }); + +describe('getAllKillstreaks', () => { + function uday( + userId: string, + dateOffsetDays: number, + status: 'PLANNED' | 'COMPLETED' | 'SKIPPED', + sessions: EffectiveSession['exercises'][][] = [], + ) { + return { week: { plan: { userId } }, ...day(dateOffsetDays, status, sessions) }; + } + + it('przelicza passy per użytkownik; reguły identyczne jak getKillstreak', async () => { + const eff = [[plannedExercise(['ps1'], [10])]]; + const partial = [[plannedExercise(['ps1'], [null])]]; + findMany.mockResolvedValue([ + uday('u2', -4, 'COMPLETED', eff), + uday('u1', -3, 'COMPLETED', eff), + uday('u2', -2, 'COMPLETED', partial), // częściowy dzień resetuje passę u2 + uday('u1', -1, 'COMPLETED', eff), + uday('u2', -1, 'COMPLETED', eff), + ]); + const res = await getAllKillstreaks(prisma); + expect(res.get('u1')).toBe(2); + expect(res.get('u2')).toBe(1); + }); + + it('dni przemieszane po dacie nie zaburniają kolejności w ramach użytkownika', async () => { + const eff = [[plannedExercise(['ps1'], [10])]]; + findMany.mockResolvedValue([ + uday('u2', -3, 'COMPLETED', eff), + uday('u1', -2, 'COMPLETED', eff), + uday('u2', -2, 'SKIPPED'), + uday('u1', -1, 'COMPLETED', eff), + uday('u2', -1, 'COMPLETED', eff), + ]); + const res = await getAllKillstreaks(prisma); + expect(res.get('u1')).toBe(2); + expect(res.get('u2')).toBe(1); + }); + + it('przyszłe dni (jeszcze nie nadszedł czas) pozostają bez wpływu', async () => { + const eff = [[plannedExercise(['ps1'], [10])]]; + findMany.mockResolvedValue([uday('u1', -1, 'COMPLETED', eff), uday('u1', 1, 'COMPLETED', eff)]); + const res = await getAllKillstreaks(prisma); + expect(res.get('u1')).toBe(1); + }); +}); diff --git a/api/test/unit/services-sessions.test.ts b/api/test/unit/services-sessions.test.ts index ee4eed3..60baa2f 100644 --- a/api/test/unit/services-sessions.test.ts +++ b/api/test/unit/services-sessions.test.ts @@ -13,10 +13,12 @@ import { function mockPrisma() { const prisma: any = { - planDay: { findUnique: vi.fn(), update: vi.fn(), updateMany: vi.fn() }, + planDay: { findUnique: vi.fn(), findMany: vi.fn(), update: vi.fn(), updateMany: vi.fn() }, + trainingPlan: { findMany: vi.fn() }, trainingSession: { findUnique: vi.fn(), findFirst: vi.fn(), + findMany: vi.fn(), create: vi.fn(), update: vi.fn(), updateMany: vi.fn(), @@ -270,7 +272,8 @@ describe('completeSession', () => { prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); prisma.planDay.updateMany.mockResolvedValue({ count: 1 }); - await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({ ok: true }); + // bez wiersza endedAt w mocku findUnique — podsumowanie niekrytyczne = null + await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({ ok: true, summary: null }); // warunkowe updateMany: sesja tylko IN_PROGRESS, dzień tylko PLANNED expect(prisma.trainingSession.updateMany).toHaveBeenCalledWith({ where: { id: 's1', status: 'IN_PROGRESS' }, @@ -336,7 +339,104 @@ describe('completeSession', () => { prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); prisma.planDay.updateMany.mockResolvedValue({ count: 1 }); - await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({ ok: true }); + await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({ ok: true, summary: null }); + }); + + it('buduje podsumowanie celebracyjne: liczby sesji + killstreak z centylem + średnie tonażu', async () => { + const prisma = mockPrisma(); + const effDay = (daysAgo: number) => ({ + date: new Date(Date.now() - daysAgo * 86_400_000), + status: 'COMPLETED' as const, + sessions: [ + { + exercises: [ + { + hidden: false, + removed: false, + planExercise: { sets: [{ id: 'ps1' }] }, + sets: [{ planSetId: 'ps1', reps: 10 }], + }, + ], + }, + ], + }); + // findUnique: (1) getSessionOwned, (2) blokada w tx, (3) wiersz do podsumowania + prisma.trainingSession.findUnique + .mockResolvedValueOnce(ownedInProgress) + .mockResolvedValueOnce(ownedInProgress) + .mockResolvedValue({ + startedAt: new Date('2026-08-24T07:00:00.000Z'), + endedAt: new Date('2026-08-24T08:10:00.000Z'), + exercises: [ + { + removed: false, + sets: [ + { planSetId: 'ps1', reps: 10, planSet: { loadKg: 60 } }, + { planSetId: 'ps2', reps: 8, planSet: { loadKg: 62.5 } }, + { planSetId: null, reps: 12, planSet: null }, // bonus bez obciążenia — poza tonażem + ], + }, + ], + }); + prisma.sessionExercise.findMany.mockResolvedValue([ + { + id: 'se1', + removed: false, + sets: [ + { id: 'st1', planSetId: 'ps1', reps: 10, removed: false }, + { id: 'st2', planSetId: 'ps2', reps: 8, removed: false }, + { id: 'st3', planSetId: null, reps: 12, removed: false }, + ], + }, + ]); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + prisma.planDay.updateMany.mockResolvedValue({ count: 1 }); + + // planDay.findMany: (1) getKillstreakStats — 2 skuteczne dni u1, (2) getAllKillstreaks — próbka + prisma.planDay.findMany.mockResolvedValueOnce([effDay(2), effDay(1)]).mockResolvedValueOnce([ + { ...effDay(2), week: { plan: { userId: 'u1' } } }, // własny wiersz — wypada z próbki centyla + { ...effDay(2), week: { plan: { userId: 'u2' } } }, // passa 1 — pobita + { + week: { plan: { userId: 'u3' } }, + date: new Date(Date.now() - 86_400_000), + status: 'SKIPPED', + sessions: [], + }, // zero — poza próbką + ]); + prisma.trainingPlan.findMany.mockResolvedValue([ + { userId: 'u1' }, + { userId: 'u2' }, + { userId: 'u3' }, + ]); + + // trainingSession.findMany: (1) średnia własna 30 dni, (2) średnia globalna 30 dni + prisma.trainingSession.findMany + .mockResolvedValueOnce([ + { + id: 's-old', + exercises: [{ removed: false, sets: [{ planSet: { loadKg: 50 }, reps: 10 }] }], + }, + ]) + .mockResolvedValue( + Array.from({ length: 12 }, (_, i) => ({ + id: `g${i}`, + exercises: [{ removed: false, sets: [{ planSet: { loadKg: 100 }, reps: 5 }] }], + })), + ); + + await expect(completeSession(prisma, 's1', 'u1')).resolves.toEqual({ + ok: true, + summary: { + durationSec: 4200, + exercises: 1, + sets: 3, + bonusSets: 1, + reps: 30, + tonnageKg: 1100, + killstreak: { current: 2, best: 2, newRecord: true, sampleSize: 1, beatCount: 1 }, + volume: { ownAvgKg: 500, ownAvgSessions: 1, globalAvgKg: 500, globalSample: 12 }, + }, + }); }); }); diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index 6801167..56f5439 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -6,6 +6,7 @@ import type { AnnouncementDetail, Availability, CalendarDay, + CompletionSummary, Conversation, ConversationThread, Dashboard, @@ -848,7 +849,9 @@ export function deleteSessionSet(setId: string) { } export function completeSession(sessionId: string) { - return api(`/sessions/${sessionId}/complete`, { method: 'POST' }); + return api<{ ok: true; summary: CompletionSummary | null }>(`/sessions/${sessionId}/complete`, { + method: 'POST', + }); } export function abandonSession(sessionId: string) { diff --git a/app/src/api/types.ts b/app/src/api/types.ts index d472302..07b9cf0 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -591,6 +591,35 @@ export interface ActiveSession { startedAt: string; } +/** + * Podsumowanie z POST /sessions/{id}/complete — dane celebracyjnego okna po + * treningu (liczby sesji + killstreak z centylem + tonaż wobec średnich 30 dni). + * null = serwer nie zbudował podsumowania (niekrytyczne) — front pokaże toast. + */ +export interface CompletionSummary { + durationSec: number; + exercises: number; + sets: number; + bonusSets: number; + reps: number; + tonnageKg: number | null; + killstreak: { + current: number; + best: number; + newRecord: boolean; + /** Ilu innych trenujących ma już historia (przez front próg min. 10). */ + sampleSize: number; + /** Ilu z próbki ma krótszą passę niż aktualna. */ + beatCount: number; + }; + volume: { + ownAvgKg: number | null; + ownAvgSessions: number; + globalAvgKg: number | null; + globalSample: number; + }; +} + export interface Dashboard { killstreak: number; /** Najlepsza passa z całej historii (planów ACTIVE/SUSPENDED/COMPLETED). */ diff --git a/app/src/i18n/locales/en/plans.json b/app/src/i18n/locales/en/plans.json index 728ccb7..090dc2d 100644 --- a/app/src/i18n/locales/en/plans.json +++ b/app/src/i18n/locales/en/plans.json @@ -319,6 +319,27 @@ "noActiveSession": "The day is {{status}}. No active session.", "confirmAbandonTitle": "Abandon session?", "confirmAbandonDesc": "The session will be marked as abandoned and the training day as skipped — the workout cannot be retaken. Entered sets will remain saved.", - "confirmAbandonLabel": "Abandon" + "confirmAbandonLabel": "Abandon", + "doneTitle": "Workout logged!", + "doneSubtitle": "Session closed in {{duration}} — here are your numbers.", + "streakLabel": "Killstreak", + "streakRecord": "new streak record", + "streakNone": "This session was not fully effective — the killstreak restarts from zero. Next time complete every planned set.", + "setsTile": "Sets", + "repsTile": "Reps", + "exercisesTile": "Exercises", + "tonnageTile": "Tonnage", + "cmpSteps_one": "Every rep is movement — today that is ≈ {{count}} walking step.", + "cmpSteps_other": "Every rep is movement — today that is ≈ {{count}} walking steps.", + "cmpStreak_one": "Your streak beats {{count}} of {{total}} FitOS trainees.", + "cmpStreak_other": "Your streak beats {{count}} of {{total}} FitOS trainees.", + "cmpOwnAbove": "Tonnage {{pct}}% above your 30-day average.", + "cmpOwnBelow": "Tonnage {{pct}}% below your 30-day average — form will come back.", + "cmpOwnPar": "Tonnage right at your 30-day average.", + "cmpGlobalAbove": "More than the FitOS trainee average ({{avg}} over 30 days).", + "cmpGlobalBelow": "The FitOS trainee average is {{avg}} — worth chasing.", + "cmpGlobalPar": "Right at the FitOS trainee average ({{avg}} over 30 days).", + "cmpBonus_one": "+{{count}} set beyond the plan — bonus counted.", + "cmpBonus_other": "+{{count}} sets beyond the plan — bonuses counted." } } diff --git a/app/src/i18n/locales/pl/plans.json b/app/src/i18n/locales/pl/plans.json index 97c6823..b1d9208 100644 --- a/app/src/i18n/locales/pl/plans.json +++ b/app/src/i18n/locales/pl/plans.json @@ -330,6 +330,33 @@ "noActiveSession": "Dzień jest {{status}}. Brak aktywnej sesji.", "confirmAbandonTitle": "Porzucić sesję?", "confirmAbandonDesc": "Sesja zostanie oznaczona jako porzucona, a dzień treningowy jako pominięty — treningu nie będzie można ponownie wykonać. Wpisane serie pozostaną zapisane.", - "confirmAbandonLabel": "Porzuć" + "confirmAbandonLabel": "Porzuć", + "doneTitle": "Trening zaliczony!", + "doneSubtitle": "Sesja domknięta w {{duration}} — oto Twoje liczby.", + "streakLabel": "Killstreak", + "streakRecord": "nowy rekord passy", + "streakNone": "Ta sesja nie była w pełni skuteczna — killstreak startuje od zera. Następnym razem dowieź wszystkie serie planowe.", + "setsTile": "Serie", + "repsTile": "Powtórzenia", + "exercisesTile": "Ćwiczenia", + "tonnageTile": "Tonaż", + "cmpSteps_one": "Każde powtórzenie to ruch — dziś to ≈ {{count}} krok marszu.", + "cmpSteps_few": "Każde powtórzenie to ruch — dziś to ≈ {{count}} kroki marszu.", + "cmpSteps_many": "Każde powtórzenie to ruch — dziś to ≈ {{count}} kroków marszu.", + "cmpSteps_other": "Każde powtórzenie to ruch — dziś to ≈ {{count}} kroków marszu.", + "cmpStreak_one": "Twoja passa jest lepsza niż u {{count}} z {{total}} trenujących na FitOS.", + "cmpStreak_few": "Twoja passa jest lepsza niż u {{count}} z {{total}} trenujących na FitOS.", + "cmpStreak_many": "Twoja passa jest lepsza niż u {{count}} z {{total}} trenujących na FitOS.", + "cmpStreak_other": "Twoja passa jest lepsza niż u {{count}} z {{total}} trenujących na FitOS.", + "cmpOwnAbove": "Tonaż o {{pct}}% powyżej Twojej średniej z 30 dni.", + "cmpOwnBelow": "Tonaż o {{pct}}% poniżej Twojej średniej z 30 dni — forma wróci.", + "cmpOwnPar": "Tonaż dokładnie w Twojej trzydziestodniowej formie.", + "cmpGlobalAbove": "Więcej niż średnia trenujących na FitOS ({{avg}} w 30 dni).", + "cmpGlobalBelow": "Średnia trenujących na FitOS to {{avg}} — jest co gonić.", + "cmpGlobalPar": "Równo w średniej trenujących na FitOS ({{avg}} w 30 dni).", + "cmpBonus_one": "+{{count}} seria ponad plan — bonus doliczony.", + "cmpBonus_few": "+{{count}} serie ponad plan — bonusy doliczone.", + "cmpBonus_many": "+{{count}} serii ponad plan — bonusy doliczone.", + "cmpBonus_other": "+{{count}} serii ponad plan — bonusy doliczone." } } diff --git a/app/src/lib/format.ts b/app/src/lib/format.ts index 7c89d15..317b802 100644 --- a/app/src/lib/format.ts +++ b/app/src/lib/format.ts @@ -179,7 +179,12 @@ export function parseLoadInput(v: string): number | null { /** Czas trwania sesji: „45 min”, „1 h 30 min”. */ export function fmtDuration(startIso: string, endIso: string): string { - const min = Math.round((new Date(endIso).getTime() - new Date(startIso).getTime()) / 60000); + return fmtDurationSec((new Date(endIso).getTime() - new Date(startIso).getTime()) / 1000); +} + +/** Czas trwania w sekundach (podsumowanie po treningu z API): „45 min”, „1 h 30 min”. */ +export function fmtDurationSec(sec: number): string { + const min = Math.round(sec / 60); if (min < 1) return t('fmt.lt1m'); if (min < 60) return t('fmt.mins', { count: min }); const h = Math.floor(min / 60); @@ -187,6 +192,11 @@ export function fmtDuration(startIso: string, endIso: string): string { return m > 0 ? t('fmt.hoursMins', { h, m }) : t('fmt.hours', { h }); } +/** Liczba całkowa z podziałami tysięcy wg języka (4200 → „4 200”). */ +export function fmtInt(n: number): string { + return n.toLocaleString(currentTag()); +} + export function todayStr(): string { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; diff --git a/app/src/pages/DayExecution.tsx b/app/src/pages/DayExecution.tsx index 3cd2c7d..ccaa18b 100644 --- a/app/src/pages/DayExecution.tsx +++ b/app/src/pages/DayExecution.tsx @@ -2,7 +2,7 @@ import { useEffect, useRef, useState, type ReactNode } from 'react'; import { useParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useQueryClient } from '@tanstack/react-query'; -import { Check, ChevronDown, Plus, Trash2 } from 'lucide-react'; +import { Check, ChevronDown, Flame, Plus, Trash2 } from 'lucide-react'; import { abandonSession, addSessionExercise, @@ -21,10 +21,26 @@ import { useSession, updateSessionSet, } from '../api/queries'; -import { fmtDate, fmtLoadKg, dayName, setsPlural } from '../lib/format'; +import { + fmtDate, + fmtDurationSec, + fmtInt, + fmtLoadKg, + fmtVolume, + dayName, + daysPlural, + setsPlural, +} from '../lib/format'; import { localizedName } from '../lib/localizedName'; import { SESSION_STATUS, muscleName } from '../lib/labels'; -import type { Exercise, PlanSet, Session, SessionExercise, SessionSet } from '../api/types'; +import type { + CompletionSummary, + Exercise, + PlanSet, + Session, + SessionExercise, + SessionSet, +} from '../api/types'; import { api } from '../api/client'; import { playAlarm } from '../lib/sound'; import { useToast } from '../components/toast'; @@ -534,6 +550,121 @@ function AddExerciseModal({ ); } +/* tile statystyki w oknie podsumowania (mała etykieta + duża liczba). */ +function SummaryStat({ label, value }: { label: string; value: string }) { + return ( +
+
+ {value} +
+
{label}
+
+ ); +} + +/* Próg próbki centyla killstreaka — poniżej porównanie wprowadza w błąd. */ +const STREAK_PCT_MIN_SAMPLE = 10; +/* Tolerancja „równo w średniej” przy porównaniach tonażu (±10%). */ +const VOLUME_PAR_BAND = 0.1; + +/* + * Celebracyjne okno po ukończeniu sesji: gratulacja, killstreak (z rekordem) + * i abstrakcyjne porównania — ekwiwalent kroków, centyl passy wobec innych + * trenujących, tonaż wobec średniej własnej/globalnej z 30 dni. Serwer liczy + * liczby (POST /sessions/{id}/complete), front tylko składa zdania przez t(). + */ +function CelebrationModal({ + summary, + onClose, +}: { + summary: CompletionSummary | null; + onClose: () => void; +}) { + const { t } = useTranslation('plans'); + if (!summary) return null; + const ks = summary.killstreak; + + const comparisons: string[] = []; + // Ekwiwalent ruchu: każde powtórzenie to w przybliżeniu jeden krok (ruch w serii + // + dojście do sprzętu) — umowne, ale przemawia do wyobraźni. + if (summary.reps > 0) comparisons.push(t('exec.cmpSteps', { count: summary.reps })); + if (ks.current > 0 && ks.sampleSize >= STREAK_PCT_MIN_SAMPLE) + comparisons.push(t('exec.cmpStreak', { count: ks.beatCount, total: ks.sampleSize })); + if (summary.tonnageKg != null) { + const { ownAvgKg, globalAvgKg } = summary.volume; + if (ownAvgKg != null) { + const d = summary.tonnageKg / ownAvgKg - 1; + if (Math.abs(d) <= VOLUME_PAR_BAND) comparisons.push(t('exec.cmpOwnPar')); + else if (d > 0) comparisons.push(t('exec.cmpOwnAbove', { pct: Math.round(d * 100) })); + else comparisons.push(t('exec.cmpOwnBelow', { pct: Math.round(-d * 100) })); + } + if (globalAvgKg != null) { + const d = summary.tonnageKg / globalAvgKg - 1; + if (Math.abs(d) <= VOLUME_PAR_BAND) + comparisons.push(t('exec.cmpGlobalPar', { avg: fmtVolume(globalAvgKg) })); + else if (d > 0) comparisons.push(t('exec.cmpGlobalAbove', { avg: fmtVolume(globalAvgKg) })); + else comparisons.push(t('exec.cmpGlobalBelow', { avg: fmtVolume(globalAvgKg) })); + } + } + if (summary.bonusSets > 0) comparisons.push(t('exec.cmpBonus', { count: summary.bonusSets })); + + return ( + +

+ {t('exec.doneSubtitle', { duration: fmtDurationSec(summary.durationSec) })} +

+ + {ks.current > 0 ? ( +
+ +
+
+ {daysPlural(ks.current)} +
+
+ {t('exec.streakLabel')} + {ks.newRecord ? ` — ${t('exec.streakRecord')}` : ''} +
+
+
+ ) : ( +

{t('exec.streakNone')}

+ )} + +
+ + + + {summary.tonnageKg != null && ( + + )} +
+ + {comparisons.length > 0 && ( +
+ {comparisons.map((line) => ( +

+ {line} +

+ ))} +
+ )} + +
+ +
+
+ ); +} + export default function DayExecution() { const { dayId } = useParams(); const queryClient = useQueryClient(); @@ -554,6 +685,8 @@ export default function DayExecution() { const [addExerciseOpen, setAddExerciseOpen] = useState(false); // alert blokowanej akcji („Dodaj serię" / „Ukończ sesję") — powód w oknie modalnym const [actionAlert, setActionAlert] = useState<{ title: string; message: string } | null>(null); + // podsumowanie z API po ukończeniu sesji — celebracyjne okno (null = brak / zamknięte) + const [completion, setCompletion] = useState(null); // Seria edytowana w oknie „Uzupełnij serię" (wsadowo: wszystkie pola naraz). // `planned` = wartości wyznaczonej normy (do przycisku „Norma spełniona"), // `restSec` = zaplanowany czas przerwy po serii (do timera). @@ -817,14 +950,16 @@ export default function DayExecution() { setBusy(true); setError(''); try { - await completeSession(session.id); + const res = await completeSession(session.id); storeRest(session.id, null); await queryClient.invalidateQueries({ queryKey: ['sessions'] }); await queryClient.invalidateQueries({ queryKey: ['dashboard'] }); await queryClient.invalidateQueries({ queryKey: ['calendar'] }); await queryClient.invalidateQueries({ queryKey: ['active-session'] }); await fetchDayInfo(); - push(t('exec.completedToast'), 'success'); + // podsumowanie z serwera = okno celebracji; bez niego (awaria liczeń) — zwykły toast + if (res.summary) setCompletion(res.summary); + else push(t('exec.completedToast'), 'success'); } catch (e) { setError(e instanceof Error ? e.message : t('exec.genericError')); } finally { @@ -1152,6 +1287,8 @@ export default function DayExecution() { )} + setCompletion(null)} /> + setStartModalOpen(false)} diff --git a/app/test/DayExecution.test.tsx b/app/test/DayExecution.test.tsx index 823a478..725b220 100644 --- a/app/test/DayExecution.test.tsx +++ b/app/test/DayExecution.test.tsx @@ -190,6 +190,8 @@ interface MockApiOptions { failSets?: boolean; /** Serie z planu bez obciążenia (loadKg null) — trening z masą ciała. */ noLoad?: boolean; + /** Podsumowanie zwracane przez POST /sessions/sess-1/complete (null = serwer bez podsumowania). */ + completionSummary?: unknown; } function mockApi( @@ -257,6 +259,12 @@ function mockApi( daySkipped = true; return jsonResponse(200, { ok: true }); } + if (url.includes('/sessions/sess-1/complete') && method === 'POST') { + completed = true; + abandoned = false; + daySkipped = false; + return jsonResponse(200, { ok: true, summary: opts.completionSummary ?? null }); + } if (url.includes('/sessions/sess-1/reopen') && method === 'POST') { if (!completed) return jsonResponse(400, { @@ -499,6 +507,67 @@ describe('Kolejka serii w sesji', () => { ).toBeInTheDocument(); }); + it('po ukończeniu sesji pokazuje okno podsumowania: killstreak, liczby i porównania', async () => { + mockApi( + { 'ss-1': 10, 'ss-2': 8, 'ss-3': 12 }, + {}, + { + completionSummary: { + durationSec: 3660, + exercises: 2, + sets: 3, + bonusSets: 1, + reps: 30, + tonnageKg: 1240, + killstreak: { current: 5, best: 5, newRecord: true, sampleSize: 12, beatCount: 9 }, + volume: { ownAvgKg: 1000, ownAvgSessions: 4, globalAvgKg: 600, globalSample: 25 }, + }, + }, + ); + const user = userEvent.setup(); + renderApp(); + await openActiveDay(user); + + expect(await screen.findByText('100%')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Ukończ sesję' })); + + const dialog = await screen.findByRole('dialog', { name: /Trening zaliczony/ }); + // killstreak z rekordem (odmiana: 5 dni) + expect(within(dialog).getByText('5 dni')).toBeInTheDocument(); + expect(within(dialog).getByText(/nowy rekord passy/)).toBeInTheDocument(); + // kafelki: serie / powtórzenia / ćwiczenia / tonaż + expect(within(dialog).getByText('3 serii')).toBeInTheDocument(); + expect(within(dialog).getByText('30')).toBeInTheDocument(); + expect(within(dialog).getByText('2 ćwiczenia')).toBeInTheDocument(); + expect(within(dialog).getByText('1,2 t')).toBeInTheDocument(); + // abstrakcyjne porównania: kroki, centyl passy, tonaż vs średnie, bonus + expect(within(dialog).getByText(/≈ 30 kroków marszu/)).toBeInTheDocument(); + expect(within(dialog).getByText(/lepsza niż u 9 z 12 trenujących/)).toBeInTheDocument(); + expect(within(dialog).getByText(/o 24% powyżej Twojej średniej z 30 dni/)).toBeInTheDocument(); + expect( + within(dialog).getByText(/Więcej niż średnia trenujących na FitOS \(600 kg/), + ).toBeInTheDocument(); + expect(within(dialog).getByText('+1 seria ponad plan — bonus doliczony.')).toBeInTheDocument(); + // okno zastępuje toast — brak dublowania komunikatu + expect(screen.queryByText('Sesja ukończona')).not.toBeInTheDocument(); + + await user.click(within(dialog).getByRole('button', { name: 'OK' })); + expect(screen.queryByRole('dialog', { name: /Trening zaliczony/ })).not.toBeInTheDocument(); + }); + + it('gdy serwer nie zwrócił podsumowania, ukończenie daje zwykły toast bez okna', async () => { + mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': 12 }); + const user = userEvent.setup(); + renderApp(); + await openActiveDay(user); + + expect(await screen.findByText('100%')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Ukończ sesję' })); + + expect(await screen.findByText('Sesja ukończona')).toBeInTheDocument(); + expect(screen.queryByRole('dialog', { name: /Trening zaliczony/ })).not.toBeInTheDocument(); + }); + it('przewija widok do następnej serii do uzupełnienia (auto-nawigacja)', async () => { const spy = vi.fn(); const orig = Element.prototype.scrollIntoView; diff --git a/app/test/e2e/mock-api.ts b/app/test/e2e/mock-api.ts index a9b6415..99fa1be 100644 --- a/app/test/e2e/mock-api.ts +++ b/app/test/e2e/mock-api.ts @@ -1191,6 +1191,26 @@ export function mockDayExecutionAbandon(page: Page) { 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 }, + }, + }), + }); + }); } /** diff --git a/ops/docs/README.md b/ops/docs/README.md index df595f0..a1833e1 100644 --- a/ops/docs/README.md +++ b/ops/docs/README.md @@ -145,6 +145,7 @@ Uruchamianie: `npm test` (pojedynczy przebieg) lub `npm run test:watch`; e2e (ap - Wznowienie ukończonej sesji (naprawa pomyłki): sesja completed wraca do in_progress, a dzień completed z powrotem do planned (startedAt = moment wznowienia, żeby nie zbierać reguły 24h); wymaga braku innej aktywnej sesji; dnia skipped ani sesji abandoned nie wznawiamy. - Serie nadmiarowe (bonus): dostępne, gdy własne serie planowe danego ćwiczenia są zapisane (ćwiczenia dodane do sesji nie mają normy — warunek spełniony z definicji); norma innych ćwiczeń nie blokuje przekraczania; maksymalnie jedna niezapisana seria bonusowa na ćwiczenie; dodanie ćwiczenia do sesji automatycznie tworzy mu pierwszą (pustą) serię; **niezapisana seria bonusowa blokuje ukończenie sesji** (trzeba ją domknąć wynikiem lub usunąć) — niepełne ukończenie treningu pozostaje możliwe przez porzucenie sesji, gdy nie dowożone są serie planowe. - 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. +- Podsumowanie po treningu: POST `/sessions/{id}/complete` zwraca `{ ok, summary }` — summary liczone na serwerze PO commitcie (liczby sesji: czas/serie/bonusy/powtórzenia/tonaż; killstreak + rekord + centyl passy wobec innych trenujących z próbką min. 10; tonaż wobec średniej własnej i globalnej z 30 dni, tonaż = Σ(loadKg×reps) wg jednej definicji). To kontrakt liczbowy — front składa zdania celebracyjnego okna przez i18n (ekwiwalent kroków, centyl, porównania tonażu). Liczenie summary jest niekrytyczne: przy awarii `summary = null`, a aplikacja pokazuje zwykły toast zamiast okna. - 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).