diff --git a/README.md b/README.md index 9a907ff..7ae7de5 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ Uruchamianie: `npm test` (pojedynczy przebieg) lub `npm run test:watch`; e2e (ap - 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 po upływie dnia (scheduler, co 60 s; strefa serwera = `TZ`, domyślnie Europe/Warsaw) → skipped; dzień z aktywną sesją nie wygasa (północ nie przerywa treningu) — domknie go ukończenie sesji albo reguła 24h. - Sesja: in_progress → completed/abandoned; auto-abandon po 24h od startu (scheduler) — twardy limit trwania sesji; 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. +- 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. - Pula ćwiczeń: seed (idempotentny upsert po slug + seed_version), cała pula dostępna w MVP (bez filtrowania przez sprzęt siłowni). diff --git a/admin/src/pages/Logs.tsx b/admin/src/pages/Logs.tsx index aaae429..2b76815 100644 --- a/admin/src/pages/Logs.tsx +++ b/admin/src/pages/Logs.tsx @@ -24,6 +24,7 @@ export const ACTION_LABELS: Record = { 'session.started': 'Sesja rozpoczęta', 'session.completed': 'Sesja zakończona', 'session.abandoned': 'Sesja porzucona', + 'session.reopened': 'Sesja wznowiona', 'gym.created': 'Siłownia utworzona', 'gym.updated': 'Siłownia zaktualizowana', 'gym.deleted': 'Siłownia usunięta', @@ -226,17 +227,32 @@ export default function Logs() { - - - - - + + + + + {filtered.map((log) => ( - - + + diff --git a/api/src/routes/sessions.ts b/api/src/routes/sessions.ts index 33c8b39..78bcc07 100644 --- a/api/src/routes/sessions.ts +++ b/api/src/routes/sessions.ts @@ -8,6 +8,7 @@ import { addExercise, addSet, completeSession, + reopenSession, deleteSet, getDay, getSession, @@ -241,5 +242,31 @@ export function createSessionRoutes({ prisma }: AppDeps) { }), ); + /** + * @openapi + * /sessions/{id}/reopen: + * post: + * summary: Reopen completed session (naprawa pomyłki; session -> in progress, + * day -> planned; requires no other active session) + * tags: [Sessions] + * responses: + * 200: { description: OK — session is in progress again } + * 400: { description: Session is not completed } + * 409: { description: Another session is active or the day is no longer completed } + */ + router.post( + '/sessions/:id/reopen', + asyncHandler(async (req, res) => { + const result = await reopenSession(prisma, req.params.id, req.user!.id); + await logActivity(prisma, { + actorId: req.user!.id, + action: 'session.reopened', + entityType: 'session', + entityId: req.params.id, + }); + res.json(result); + }), + ); + return router; } diff --git a/api/src/services/sessions.ts b/api/src/services/sessions.ts index 151b05c..bb0fc29 100644 --- a/api/src/services/sessions.ts +++ b/api/src/services/sessions.ts @@ -403,3 +403,39 @@ export async function abandonSession(prisma: PrismaClient, sessionId: string, us }); return { ok: true }; } + +/** + * Reopen a COMPLETED session — naprawa pomyłki w zapisanych wynikach. + * Sesja wraca do IN_PROGRESS (startedAt = moment wznowienia, bo stary start + * natychmiast zbiłby regułę 24h w schedulerze), a dzień z powrotem do PLANNED. + * Dnia SKIPPED nie wskrzeszamy; sesji ABANDONED nie wznawiamy (porzuconego + * treningu nie da się wykonać ponownie — tak stanowi reguła porzucenia). + */ +export async function reopenSession(prisma: PrismaClient, sessionId: string, userId: string) { + const session = await getSessionOwned(prisma, sessionId, userId); + if (session.status !== 'COMPLETED') throw badRequest('Only a completed session can be reopened'); + // Jak przy starcie: jedna aktywna sesja na użytkownika — wznowiona nie może + // być drugą (skrót active-session i dashboard liczą na findFirst IN_PROGRESS). + const active = await prisma.trainingSession.findFirst({ + where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } }, id: { not: sessionId } }, + select: { id: true }, + }); + if (active) throw conflict('You already have an active session'); + const now = new Date(); + await prisma.$transaction(async (tx) => { + await tx.$executeRaw`SELECT id FROM "TrainingSession" WHERE id = ${session.id} FOR UPDATE`; + const s = await tx.trainingSession.updateMany({ + where: { id: session.id, status: 'COMPLETED' }, + data: { status: 'IN_PROGRESS', startedAt: now, endedAt: null }, + }); + if (s.count === 0) throw conflict('Session is no longer completed'); + // Dzień wraca do PLANNED tylko gdy wciąż jest COMPLETED — wygasły (SKIPPED) + // pozostaje zamknięty. + const d = await tx.planDay.updateMany({ + where: { id: session.dayId, status: 'COMPLETED' }, + data: { status: 'PLANNED', completedAt: null }, + }); + if (d.count === 0) throw conflict('Training day is no longer completed'); + }); + return { sessionId: session.id, status: 'IN_PROGRESS' }; +} diff --git a/api/src/swagger.ts b/api/src/swagger.ts index 175578e..0062ab5 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -876,6 +876,15 @@ export const openapi: Record = { parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], }, }, + '/sessions/{id}/reopen': { + post: { + tags: ['Sessions'], + summary: + 'Reopen completed session (naprawa pomyłki; session -> in progress, day -> planned; requires no other active session)', + security: [{ bearerAuth: [] }], + parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], + }, + }, '/dashboard': { get: { tags: ['Dashboard'], diff --git a/api/test/integration/sessions.test.ts b/api/test/integration/sessions.test.ts index cafc757..6663142 100644 --- a/api/test/integration/sessions.test.ts +++ b/api/test/integration/sessions.test.ts @@ -353,6 +353,17 @@ describe('sessions routes', () => { ); }); + it('rejects reopening a session that is not completed with 400', async () => { + const app = buildApp(); + const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`); + const sessionId = session.body.day.sessions[0].id; + const res = await app + .post(`/api/v1/sessions/${sessionId}/reopen`) + .set('Authorization', `Bearer ${token}`); + expect(res.status).toBe(400); + expect(res.body.error.message).toBe('Only a completed session can be reopened'); + }); + it('removes an extra set without consequence (data kept)', async () => { const app = buildApp(); const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`); @@ -558,6 +569,39 @@ describe('sessions routes', () => { expect(res.body.error.message).toBe('Day is not in planned state'); }); + it('reopens the completed session (naprawa pomyłki), allows fixing a set, completes again', async () => { + const app = buildApp(); + const sess = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`); + const sessionId = sess.body.day.sessions.find((s: any) => s.status === 'COMPLETED').id; + + const reopened = await app + .post(`/api/v1/sessions/${sessionId}/reopen`) + .set('Authorization', `Bearer ${token}`); + expect(reopened.status).toBe(200); + expect(reopened.body).toEqual({ sessionId, status: 'IN_PROGRESS' }); + + const day = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`); + expect(day.body.day.status).toBe('PLANNED'); + + // po wznowieniu da się poprawić zapisaną serię + const detail = await app + .get(`/api/v1/sessions/${sessionId}`) + .set('Authorization', `Bearer ${token}`); + const setId = detail.body.session.exercises[0].sets[0].id; + const fixed = await app + .patch(`/api/v1/sessions/sets/${setId}`) + .send({ reps: 999 }) + .set('Authorization', `Bearer ${token}`); + expect(fixed.status).toBe(200); + + const done = await app + .post(`/api/v1/sessions/${sessionId}/complete`) + .set('Authorization', `Bearer ${token}`); + expect(done.status).toBe(200); + const dayAgain = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`); + expect(dayAgain.body.day.status).toBe('COMPLETED'); + }); + it('abandons a session and marks the day skipped', async () => { const app = buildApp(); const start = await app diff --git a/api/test/unit/services-sessions.test.ts b/api/test/unit/services-sessions.test.ts index 1b59944..ee4eed3 100644 --- a/api/test/unit/services-sessions.test.ts +++ b/api/test/unit/services-sessions.test.ts @@ -6,6 +6,7 @@ import { completeSession, deleteSet, getActiveSession, + reopenSession, startSession, updateExercise, } from '../../src/services/sessions.js'; @@ -246,8 +247,7 @@ describe('completeSession', () => { ]); await expect(completeSession(prisma, 's1', 'u1')).rejects.toMatchObject({ status: 400, - message: - 'Extra sets must be recorded or removed before completing the session (1 remaining)', + message: 'Extra sets must be recorded or removed before completing the session (1 remaining)', }); expect(prisma.trainingSession.updateMany).not.toHaveBeenCalled(); }); @@ -394,6 +394,73 @@ describe('abandonSession', () => { }); }); +describe('reopenSession', () => { + const ownedCompleted = { + id: 's1', + status: 'COMPLETED', + dayId: 'd1', + day: { week: { plan: { userId: 'u1' } } }, + }; + + it('400 when the session is not completed', async () => { + const prisma = mockPrisma(); + prisma.trainingSession.findUnique.mockResolvedValue({ + ...ownedCompleted, + status: 'ABANDONED', + }); + await expect(reopenSession(prisma, 's1', 'u1')).rejects.toMatchObject({ + status: 400, + message: 'Only a completed session can be reopened', + }); + }); + + it('409 when the user already has another active session', async () => { + const prisma = mockPrisma(); + prisma.trainingSession.findUnique.mockResolvedValue(ownedCompleted); + prisma.trainingSession.findFirst.mockResolvedValue({ id: 's2' }); + await expect(reopenSession(prisma, 's1', 'u1')).rejects.toMatchObject({ + status: 409, + message: 'You already have an active session', + }); + expect(prisma.$transaction).not.toHaveBeenCalled(); + }); + + it('reopens the session and returns the day to planned (start reset to now)', async () => { + const prisma = mockPrisma(); + prisma.trainingSession.findUnique.mockResolvedValue(ownedCompleted); + prisma.trainingSession.findFirst.mockResolvedValue(null); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + prisma.planDay.updateMany.mockResolvedValue({ count: 1 }); + + await expect(reopenSession(prisma, 's1', 'u1')).resolves.toEqual({ + sessionId: 's1', + status: 'IN_PROGRESS', + }); + // stary endedAt/usunięty, startedAt = teraz — inaczej reguła 24h zbiłaby wznowienie + expect(prisma.trainingSession.updateMany).toHaveBeenCalledWith({ + where: { id: 's1', status: 'COMPLETED' }, + data: { status: 'IN_PROGRESS', startedAt: expect.any(Date), endedAt: null }, + }); + expect(prisma.planDay.updateMany).toHaveBeenCalledWith({ + where: { id: 'd1', status: 'COMPLETED' }, + data: { status: 'PLANNED', completedAt: null }, + }); + }); + + it('409 when the day is no longer completed (e.g. concurrently expired)', async () => { + const prisma = mockPrisma(); + prisma.trainingSession.findUnique.mockResolvedValue(ownedCompleted); + prisma.trainingSession.findFirst.mockResolvedValue(null); + prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 }); + prisma.planDay.updateMany.mockResolvedValue({ count: 0 }); + + await expect(reopenSession(prisma, 's1', 'u1')).rejects.toMatchObject({ + status: 409, + message: 'Training day is no longer completed', + }); + }); +}); + describe('updateExercise', () => { it('400 when removing an exercise that comes from the plan', async () => { const prisma = mockPrisma(); diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index d22b26c..39568a7 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -535,6 +535,10 @@ export function abandonSession(sessionId: string) { return api(`/sessions/${sessionId}/abandon`, { method: 'POST' }); } +export function reopenSession(sessionId: string) { + return api(`/sessions/${sessionId}/reopen`, { method: 'POST' }); +} + // ---------- dashboard / calendar ---------- export function useDashboard() { return useQuery({ queryKey: ['dashboard'], queryFn: () => api('/dashboard') }); diff --git a/app/src/pages/DayExecution.tsx b/app/src/pages/DayExecution.tsx index 9bc0e14..0dbb869 100644 --- a/app/src/pages/DayExecution.tsx +++ b/app/src/pages/DayExecution.tsx @@ -8,6 +8,7 @@ import { addSessionSet, completeSession, deleteSessionSet, + reopenSession, setSessionExerciseState, startSession, useExercises, @@ -641,13 +642,19 @@ export default function DayExecution() { date: string | null; status: string; dayOfWeek: number; - sessions: { id: string; status: string }[]; + sessions: { id: string; status: string; startedAt: string | null }[]; }; }>(`/days/${dayId}`); setDayInfo({ date: data.day.date, status: data.day.status, dayOfWeek: data.day.dayOfWeek }); + // startujemy od aktywnej; inaczej najnowsza sesja dnia — po porzuconej i + // drugiej sesji sessions[0] to stara (abandonowana), która zasłaniałaby + // ukończoną i blokowała „Wznów trening" const active = data.day.sessions.find((s) => s.status === 'IN_PROGRESS'); - if (active) setSessionId(active.id); - else if (data.day.sessions.length > 0) setSessionId(data.day.sessions[0].id); + const sorted = [...data.day.sessions].sort((a, b) => + (a.startedAt ?? '').localeCompare(b.startedAt ?? ''), + ); + const newest = sorted[sorted.length - 1]; + setSessionId(active?.id ?? newest?.id ?? null); } catch { // day may not exist } @@ -717,6 +724,26 @@ export default function DayExecution() { } }; + // wznowienie ukończonej sesji — naprawa pomyłki w wynikach (serwer: day -> planned) + const reopen = async () => { + if (!session) return; + setBusy(true); + setError(''); + try { + await reopenSession(session.id); + await queryClient.invalidateQueries({ queryKey: ['sessions'] }); + await queryClient.invalidateQueries({ queryKey: ['active-session'] }); + await queryClient.invalidateQueries({ queryKey: ['calendar'] }); + await queryClient.invalidateQueries({ queryKey: ['dashboard'] }); + await fetchDayInfo(); + push('Sesja wznowiona — możesz poprawić wyniki', 'success'); + } catch (e) { + setError(e instanceof Error ? e.message : 'Błąd'); + } finally { + setBusy(false); + } + }; + // menu top: akcje sesji (dodawanie ćwiczenia przez modal; ukończenie wymaga serie normowe; porzucenie przez dialog) useTopbar({ title: 'Dzień treningowy', @@ -735,7 +762,9 @@ export default function DayExecution() { disabled: busy, }, ] - : undefined, + : session?.status === 'COMPLETED' + ? [{ label: 'Wznów trening', onClick: reopen, disabled: busy }] + : undefined, }); // podwójny klik nie może wysłać dwóch żądań (serwer zbiłby drugie 400) diff --git a/app/test/DayExecution.test.tsx b/app/test/DayExecution.test.tsx index 6b3c353..1687b65 100644 --- a/app/test/DayExecution.test.tsx +++ b/app/test/DayExecution.test.tsx @@ -135,6 +135,8 @@ function jsonResponse(status: number, body: unknown) { interface MockApiOptions { /** Początkowy stan: sesja ABANDONED (np. po auto-porzuceniu przez scheduler). */ abandoned?: boolean; + /** Początkowy stan: sesja COMPLETED (dzień COMPLETED) — test „Wznów trening”. */ + completed?: boolean; /** Początkowy stan: dzień SKIPPED (domyślnie: jak `abandoned`). */ daySkipped?: boolean; /** Dashboard zwraca nextTraining day-1 (przycisk „Wykonaj trening”). */ @@ -157,6 +159,7 @@ function mockApi( // Stateful: POST /sessions/sess-1/abandon oznacza sesję jako ABANDONED, // a dzień jako SKIPPED (treningu nie da się ponownie wykonać). let abandoned = opts.abandoned ?? false; + let completed = opts.completed ?? false; let daySkipped = opts.daySkipped ?? abandoned; const { nextTraining = false } = opts; const catalog = opts.exerciseCatalog ?? CATALOG; @@ -205,6 +208,14 @@ function mockApi( daySkipped = true; return jsonResponse(200, { ok: true }); } + if (url.includes('/sessions/sess-1/reopen') && method === 'POST') { + if (!completed) + return jsonResponse(400, { + error: { code: 'BAD_REQUEST', message: 'Only a completed session can be reopened' }, + }); + completed = false; + return jsonResponse(200, { sessionId: 'sess-1', status: 'IN_PROGRESS' }); + } if (url.includes('/sessions/sess-1/exercises') && method === 'POST') { const body = JSON.parse(String(init?.body)) as { exerciseId: string }; const ex = catalog.find((c) => c.id === body.exerciseId); @@ -224,10 +235,18 @@ function mockApi( day: { id: 'day-1', date: '2026-08-24', - status: daySkipped ? 'SKIPPED' : 'PLANNED', + status: completed ? 'COMPLETED' : daySkipped ? 'SKIPPED' : 'PLANNED', dayOfWeek: 1, sessions: [ - { id: 'sess-1', status: abandoned ? 'ABANDONED' : 'IN_PROGRESS', startedAt: '2026-08-24T07:00:00.000Z' }, + { + id: 'sess-1', + status: completed + ? 'COMPLETED' + : abandoned + ? 'ABANDONED' + : 'IN_PROGRESS', + startedAt: '2026-08-24T07:00:00.000Z', + }, ], }, }); @@ -237,7 +256,7 @@ function mockApi( sessionBody( reps, indices, - abandoned ? 'ABANDONED' : 'IN_PROGRESS', + completed ? 'COMPLETED' : abandoned ? 'ABANDONED' : 'IN_PROGRESS', added, notes, rirOnly, @@ -362,6 +381,31 @@ describe('Kolejka serii w sesji', () => { ).not.toBeInTheDocument(); }); + it('ukończona sesja daje „Wznów trening” i po wznowieniu wraca do edycji', async () => { + mockApi({ 'ss-1': 10, 'ss-2': 10, 'ss-3': 5 }, {}, { completed: true }); + const user = userEvent.setup(); + renderApp(); + + expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument(); + const email = document.querySelector('input[type="email"]') as HTMLInputElement; + const password = document.querySelector('input[type="password"]') as HTMLInputElement; + await user.type(email, 'jan@test.local'); + await user.type(password, 'Password123!'); + await user.click(screen.getByRole('button', { name: 'Zaloguj' })); + await screen.findByRole('heading', { name: 'Dashboard' }); + await user.click(screen.getByRole('link', { name: 'Trening', exact: true })); + expect(await screen.findByText('Ukończona')).toBeInTheDocument(); + + // tryb tylko do odczytu: brak akcji sesji, jest za to wznowienie + expect(screen.queryByRole('button', { name: 'Ukończ sesję' })).not.toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Wznów trening' })); + await waitFor(() => + expect(screen.getByText('Sesja wznowiona — możesz poprawić wyniki')).toBeInTheDocument(), + ); + expect(await screen.findByText('W trakcie')).toBeInTheDocument(); + expect(await screen.findByRole('button', { name: 'Ukończ sesję' })).toBeInTheDocument(); + }); + it('blokuje ukończenie sesji alertem, gdy trwa niezapisana seria bonusowa', async () => { mockApi({ 'ss-1': 10, 'ss-2': 10, 'ss-3': null }); const user = userEvent.setup();
DataUżytkownikAkcjaObiektSzczegóły + Data + + Użytkownik + + Akcja + + Obiekt + + Szczegóły +
{formatLogDate(log.createdAt)}
+ {formatLogDate(log.createdAt)} +
{actorName(log)}
{log.actor.email}
@@ -249,7 +265,9 @@ export default function Logs() {
{ENTITY_LABELS[log.entityType] ?? log.entityType}
- {entityName(log) &&
{entityName(log)}
} + {entityName(log) && ( +
{entityName(log)}
+ )}
{detailsText(log) ?? '—'}