From 7d89f5bcca7e53dc3a010e4fcf3425a7787e70e9 Mon Sep 17 00:00:00 2001 From: Tilumca Date: Wed, 14 Oct 2026 22:11:49 +0200 Subject: [PATCH] Trening: dodanie cwiczenia tworzy automatycznie pierwsza serie; limit niezapisanego bonusu liczony na cwiczenie (wczesniej na sesje) --- README.md | 2 +- api/src/routes/sessions.ts | 4 +-- api/src/services/sessions.ts | 12 ++------ api/src/swagger.ts | 2 +- api/test/integration/sessions.test.ts | 40 +++++++++++++++++++++++++ api/test/unit/services-sessions.test.ts | 4 +-- app/src/pages/DayExecution.tsx | 15 ++++++---- app/test/DayExecution.test.tsx | 40 ++++++++++++++++++++++--- 8 files changed, 95 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 36d906d..823549a 100644 --- a/README.md +++ b/README.md @@ -110,7 +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. -- 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 sesję. +- 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ę. - 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. diff --git a/api/src/routes/sessions.ts b/api/src/routes/sessions.ts index 3c5b0ab..b255d59 100644 --- a/api/src/routes/sessions.ts +++ b/api/src/routes/sessions.ts @@ -139,8 +139,8 @@ export function createSessionRoutes({ prisma }: AppDeps) { * /sessions/exercises/{id}/sets: * post: * summary: Add an extra (bonus) set. Only when all planned sets of this exercise are - * recorded (added exercises have no norm) and no extra set is still pending - * (at most one pending extra per session). + * recorded (added exercises have no norm) and this exercise has no extra set + * still pending (at most one pending extra per exercise). * tags: [Sessions] * responses: * 201: { description: Created } diff --git a/api/src/services/sessions.ts b/api/src/services/sessions.ts index 774f503..699a5fb 100644 --- a/api/src/services/sessions.ts +++ b/api/src/services/sessions.ts @@ -241,8 +241,8 @@ export async function updateExercise( /** * Add an extra (bonus) set to a session exercise. * Allowed once every planned (norm) set of THIS exercise is recorded (exercises - * added to the session have no norm — vacuously satisfied), and no extra set is - * still pending — at most one pending extra set per session. + * added to the session have no norm — vacuously satisfied), and this exercise has + * no extra set still pending — at most one pending extra set per exercise. * Norm of other exercises must not block exceeding one that is already done: * "nie dowożę / dowożę / przekraczam" is an option per exercise, in order. */ @@ -259,13 +259,7 @@ export async function addSet(prisma: PrismaClient, exerciseId: string, userId: s 'All planned sets of this exercise must be recorded before adding an extra set', ); const pendingExtra = await tx.sessionSet.count({ - where: { - // usunięte ćwiczenia nie liczą się do limitu — ich seria „w toku" jest nietykalna - exercise: { sessionId: exercise.sessionId, removed: false }, - planSetId: null, - reps: null, - removed: false, - }, + where: { exerciseId: exercise.id, planSetId: null, reps: null, removed: false }, }); if (pendingExtra > 0) throw badRequest('An extra set is already in progress'); const maxIndex = await tx.sessionSet.aggregate({ diff --git a/api/src/swagger.ts b/api/src/swagger.ts index c6c7880..175578e 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -831,7 +831,7 @@ export const openapi: Record = { post: { tags: ['Sessions'], summary: - "Add extra (bonus) set to session exercise (requires this exercise's planned sets recorded; at most one pending extra per session)", + "Add extra (bonus) set to session exercise (requires this exercise's planned sets recorded; at most one pending extra per exercise)", security: [{ bearerAuth: [] }], parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }], }, diff --git a/api/test/integration/sessions.test.ts b/api/test/integration/sessions.test.ts index aaf6946..6c64381 100644 --- a/api/test/integration/sessions.test.ts +++ b/api/test/integration/sessions.test.ts @@ -424,6 +424,46 @@ describe('sessions routes', () => { expect(cleanup.status).toBe(200); }); + it('allows one pending extra per exercise (równolegle w różnych ćwiczeniach, nie dwa w tym samym)', 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 detail = await app + .get(`/api/v1/sessions/${sessionId}`) + .set('Authorization', `Bearer ${token}`); + const ex = detail.body.session.exercises[0]; + + const a = await app + .post(`/api/v1/sessions/exercises/${ex.id}/sets`) + .set('Authorization', `Bearer ${token}`); + expect(a.status).toBe(201); + + // inne ćwiczenie może mieć własną niezapisaną serię bonusową w tym samym czasie + const added = await app + .post(`/api/v1/sessions/${sessionId}/exercises`) + .set('Authorization', `Bearer ${token}`) + .send({ exerciseId }); + expect(added.status).toBe(201); + const b = await app + .post(`/api/v1/sessions/exercises/${added.body.exerciseId}/sets`) + .set('Authorization', `Bearer ${token}`); + expect(b.status).toBe(201); + + // ale nie druga w tym samym ćwiczeniu + const dup = await app + .post(`/api/v1/sessions/exercises/${added.body.exerciseId}/sets`) + .set('Authorization', `Bearer ${token}`); + expect(dup.status).toBe(400); + expect(dup.body.error.message).toBe('An extra set is already in progress'); + + for (const setId of [a.body.setId, b.body.setId]) { + const del = await app + .delete(`/api/v1/sessions/sets/${setId}`) + .set('Authorization', `Bearer ${token}`); + expect(del.status).toBe(200); + } + }); + it('records actual set results', async () => { const app = buildApp(); const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`); diff --git a/api/test/unit/services-sessions.test.ts b/api/test/unit/services-sessions.test.ts index 1451e90..4ebbae3 100644 --- a/api/test/unit/services-sessions.test.ts +++ b/api/test/unit/services-sessions.test.ts @@ -503,10 +503,10 @@ describe('addSet', () => { removed: false, }, }); - // limit bonusu pomija serie nalezace do usunietych cwiczen + // limit bonusu jest liczony dla tego cwiczenia (nie dla sesji) expect(prisma.sessionSet.count).toHaveBeenNthCalledWith(2, { where: { - exercise: { sessionId: 's1', removed: false }, + exerciseId: 'se1', planSetId: null, reps: null, removed: false, diff --git a/app/src/pages/DayExecution.tsx b/app/src/pages/DayExecution.tsx index 2fb4ab1..29709d5 100644 --- a/app/src/pages/DayExecution.tsx +++ b/app/src/pages/DayExecution.tsx @@ -501,7 +501,6 @@ export default function DayExecution() { const normTotal = normSets.length; const normDone = normSets.filter((s) => s.reps != null).length; const normPending = normTotal - normDone; - const extraPending = extraSets.filter((s) => s.reps == null).length; const extraDone = extraSets.filter((s) => s.reps != null).length; const nextSetId = allSets.find((s) => s.reps == null)?.id ?? null; // Powód blokady „Dodaj serię" (null = można); pokazujemy go w alercie po kliknięciu. @@ -510,8 +509,8 @@ export default function DayExecution() { ? null : ex.sets.some((s) => s.planSetId != null && s.reps == null) ? 'Najpierw zapisz wszystkie serie normowe tego ćwiczenia' - : extraPending > 0 - ? 'W sesji jest już niezapisana seria dodatkowa — najpierw ją uzupełnij' + : ex.sets.some((s) => s.planSetId == null && s.reps == null) + ? 'W tym ćwiczeniu jest już niezapisana seria — najpierw ją uzupełnij' : null; // Akordeony niezależne: klik nagłówka rozwija/zwija swoje ćwiczenie bez zamykania @@ -661,12 +660,18 @@ export default function DayExecution() { addingRef.current = true; try { const res = await addSessionExercise(session.id, exerciseId); - // nowe ćwiczenie rozwija się samo — „Dodaj serię” widoczne od razu, bez szukania + // nowe ćwiczenie: od razu rozwinięte i z pierwszą pustą serią („Dodaj serię” + // wykonuje się samo) — użytkownik tylko wpisuje wynik + try { + await addSessionSet(res.exerciseId); + } catch { + // seria nie powstała (np. awaria) — ćwiczenie i tak dodane; przycisk zostanie w UI + } setExpandedIds((cur) => (cur.includes(res.exerciseId) ? cur : [...cur, res.exerciseId])); - await queryClient.invalidateQueries({ queryKey: ['sessions', session.id] }); } catch (e) { setError(e instanceof Error ? e.message : 'Błąd'); } finally { + await queryClient.invalidateQueries({ queryKey: ['sessions', session.id] }); addingRef.current = false; } }; diff --git a/app/test/DayExecution.test.tsx b/app/test/DayExecution.test.tsx index 065cfca..edf5215 100644 --- a/app/test/DayExecution.test.tsx +++ b/app/test/DayExecution.test.tsx @@ -49,6 +49,7 @@ function sessionBody( extra: CatalogExercise[] = [], notes: Record = {}, rirOnly: string[] = [], + addedSets: Record = {}, ) { const has = (id: string) => reps[id] != null; const secondary = (id: string) => has(id) || rirOnly.includes(id); @@ -108,7 +109,16 @@ function sessionBody( removed: false, exercise: { id: e.id, name: e.name, primaryMuscle: e.primaryMuscle }, planExercise: null, - sets: [], + // auto-seria po dodaniu ćwiczenia: POST /sessions/exercises/:id/sets dopisuje pending + sets: Array.from({ length: addedSets[e.id] ?? 0 }, (_, s) => ({ + id: `ss-ax-${i + 1}-${s}`, + planSetId: null, + index: s, + reps: null, + rir: null, + difficulty: null, + note: null, + })), })), ], }, @@ -153,6 +163,8 @@ function mockApi( const rirOnly = opts.rirOnly ?? []; // Stateful: POST /sessions/sess-1/exercises dodaje ćwiczenie do sesji (widoczne po refetchu). const added: CatalogExercise[] = []; + // Stateful: auto-serie nowo dodanych ćwiczeń (POST /sessions/exercises/:id/sets). + const addedSets: Record = {}; // Stateful: PATCH /sessions/sets/:id zapisuje komentarz serii (widoczny po refetchu). const notes: Record = {}; vi.stubGlobal( @@ -200,6 +212,13 @@ function mockApi( // id wiersza sesji jak w fixture (se-x1, se-x2…) — front używa go do rozwinięcia akordeonu return jsonResponse(200, { exerciseId: `se-x${added.length}` }); } + if (url.includes('/sessions/exercises/') && method === 'POST') { + // POST /sessions/exercises/se-x1/sets — auto-seria dla ćwiczenia dodanego do sesji + const exId = url.split('/sessions/exercises/')[1]?.split('/')[0] ?? ''; + const cat = added[parseInt(exId.replace('se-x', ''), 10) - 1]; + if (cat) addedSets[cat.id] = (addedSets[cat.id] ?? 0) + 1; + return jsonResponse(200, { setId: `ss-ax-${exId}`, index: (cat ? addedSets[cat.id] : 1) - 1 }); + } if (url.includes('/days/day-1')) return jsonResponse(200, { day: { @@ -213,7 +232,18 @@ function mockApi( }, }); if (url.includes('/sessions/sess-1')) - return jsonResponse(200, sessionBody(reps, indices, abandoned ? 'ABANDONED' : 'IN_PROGRESS', added, notes, rirOnly)); + return jsonResponse( + 200, + sessionBody( + reps, + indices, + abandoned ? 'ABANDONED' : 'IN_PROGRESS', + added, + notes, + rirOnly, + addedSets, + ), + ); if (url.includes('/sessions/sets/')) { if (method === 'PATCH') { if (opts.hangSets) return new Promise(() => undefined); @@ -314,7 +344,7 @@ describe('Kolejka serii w sesji', () => { ).not.toBeInTheDocument(); }); - it('pokazuje alert z przyczyną, gdy w sesji trwa niezapisana seria dodatkowa', async () => { + it('pokazuje alert z przyczyną, gdy w tym ćwiczeniu trwa niezapisana seria dodatkowa', async () => { mockApi({ 'ss-1': 10, 'ss-2': 10, 'ss-3': null }); const user = userEvent.setup(); renderApp(); @@ -324,7 +354,7 @@ describe('Kolejka serii w sesji', () => { expect(await screen.findByText('100%')).toBeInTheDocument(); await user.click(screen.getByRole('button', { name: 'Dodaj serię' })); expect( - await screen.findByText('W sesji jest już niezapisana seria dodatkowa — najpierw ją uzupełnij'), + await screen.findByText('W tym ćwiczeniu jest już niezapisana seria — najpierw ją uzupełnij'), ).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: /Nie można dodać serii/ })).toBeInTheDocument(); expect( @@ -776,6 +806,8 @@ describe('Dodawanie ćwiczenia do sesji', () => { ); // otwarte akordeony: Wyciskanie (auto, następna seria) + Martwy ciąg => 2 przyciski expect(screen.getAllByRole('button', { name: 'Dodaj serię' })).toHaveLength(2); + // auto-seria: Martwy ciąg dostał pierwszą niezapisaną serię (obok pending ss-3 w Wyciskaniu) + expect(screen.getAllByRole('button', { name: 'Uzupełnij serię' })).toHaveLength(2); }); it('pusty katalog ćwiczeń pokazuje komunikat w modalu', async () => {