Trening: seria nadmiarowa dostepna po dowiezieniu wlasnej normy cwiczenia (norma innych cwiczen wiecej nie blokuje; cwiczenia dodane od razu; limit 1 bonusu na sesje bez zmian)

This commit is contained in:
Tilumca
2026-10-14 21:32:23 +02:00
parent edb21efb44
commit 19d87ef4a6
9 changed files with 99 additions and 32 deletions

View File

@@ -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.
- 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ę.
- 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.

View File

@@ -138,12 +138,13 @@ export function createSessionRoutes({ prisma }: AppDeps) {
* @openapi
* /sessions/exercises/{id}/sets:
* post:
* summary: Add an extra (bonus) set. Only when all planned sets of the session are
* recorded and no extra set is still pending (at most one pending extra per session).
* 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).
* tags: [Sessions]
* responses:
* 201: { description: Created }
* 400: { description: Norm not done or an extra set is already in progress }
* 400: { description: Norm of this exercise not done or an extra set is already in progress }
*/
router.post(
'/sessions/exercises/:id/sets',

View File

@@ -240,21 +240,32 @@ export async function updateExercise(
/**
* Add an extra (bonus) set to a session exercise.
* Allowed only when every planned (norm) set of the session is recorded and no
* extra set is still pending — at most one pending extra set per session.
* 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.
* Norm of other exercises must not block exceeding one that is already done:
* "nie dowożę / dowożę / przekraczam" is an option per exercise, in order.
*/
export async function addSet(prisma: PrismaClient, exerciseId: string, userId: string) {
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
// Cała kontrola + wstawienie pod blokadą sesji: dwa równoległe żądania nie mogą
// przejść obiecyjnie warunku „brak serii dodatkowej w toku".
const set = await inSessionTransaction(prisma, exercise.sessionId, async (tx) => {
const sets = await tx.sessionSet.findMany({
where: { exercise: { sessionId: exercise.sessionId }, removed: false },
const pendingNorm = await tx.sessionSet.count({
where: { exerciseId: exercise.id, planSetId: { not: null }, reps: null, removed: false },
});
const pendingNorm = sets.filter((s) => s.planSetId != null && s.reps == null).length;
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;
throw badRequest(
'All planned sets of this exercise must be recorded before adding an extra set',
);
const pendingExtra = await tx.sessionSet.count({
where: {
exercise: { sessionId: exercise.sessionId },
planSetId: null,
reps: null,
removed: false,
},
});
if (pendingExtra > 0) throw badRequest('An extra set is already in progress');
const maxIndex = await tx.sessionSet.aggregate({
where: { exerciseId: exercise.id },

View File

@@ -830,7 +830,8 @@ export const openapi: Record<string, unknown> = {
'/sessions/exercises/{id}/sets': {
post: {
tags: ['Sessions'],
summary: 'Add set to session exercise',
summary:
"Add extra (bonus) set to session exercise (requires this exercise's planned sets recorded; at most one pending extra per session)",
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},

View File

@@ -257,7 +257,7 @@ describe('sessions routes', () => {
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
expect(res.body.error.message).toBe(
'All planned sets must be recorded before adding an extra set',
'All planned sets of this exercise must be recorded before adding an extra set',
);
});
@@ -274,6 +274,29 @@ describe('sessions routes', () => {
);
});
it('allows adding a set to an exercise added to the session while another exercise norm is pending', 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 added = detail.body.session.exercises.find(
(e: { planExerciseId: string | null }) => !e.planExerciseId,
);
const res = await app
.post(`/api/v1/sessions/exercises/${added.id}/sets`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(201);
// sprzątanie: usuń bonusową serię, by nie zaburzać późniejszych asercji limitu
const cleanup = await app
.delete(`/api/v1/sessions/sets/${res.body.setId}`)
.set('Authorization', `Bearer ${token}`);
expect(cleanup.status).toBe(200);
});
it('records the norm sets and adds an extra set once the norm is done', async () => {
const app = buildApp();
const session = await app.get(`/api/v1/days/${dayId}`).set('Authorization', `Bearer ${token}`);

View File

@@ -32,6 +32,7 @@ function mockPrisma() {
sessionSet: {
findUnique: vi.fn(),
findMany: vi.fn(),
count: vi.fn(),
create: vi.fn(),
createMany: vi.fn(),
update: vi.fn(),
@@ -441,18 +442,15 @@ describe('addSet', () => {
});
});
it('400 when planned (norm) sets are still pending', async () => {
it('400 when planned (norm) sets of this exercise are still pending', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.findMany.mockResolvedValue([
{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false },
{ id: 'st2', planSetId: 'ps2', reps: null, removed: false },
]);
prisma.sessionSet.count.mockResolvedValueOnce(1);
await expect(addSet(prisma, 'se1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'All planned sets must be recorded before adding an extra set',
message: 'All planned sets of this exercise must be recorded before adding an extra set',
});
});
@@ -461,10 +459,7 @@ describe('addSet', () => {
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.findMany.mockResolvedValue([
{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false },
{ id: 'st2', planSetId: null, reps: null, removed: false },
]);
prisma.sessionSet.count.mockResolvedValueOnce(0).mockResolvedValueOnce(1);
await expect(addSet(prisma, 'se1', 'u1')).rejects.toMatchObject({
status: 400,
message: 'An extra set is already in progress',
@@ -476,10 +471,7 @@ describe('addSet', () => {
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.findMany.mockResolvedValue([
{ id: 'st1', planSetId: 'ps1', reps: 10, removed: false },
{ id: 'st2', planSetId: null, reps: 8, removed: false },
]);
prisma.sessionSet.count.mockResolvedValueOnce(0).mockResolvedValueOnce(0);
prisma.sessionSet.aggregate.mockResolvedValue({ _max: { index: 1 } });
prisma.sessionSet.create.mockResolvedValue({ id: 'st3', index: 2 });
@@ -490,6 +482,27 @@ describe('addSet', () => {
data: { exerciseId: 'se1', index: 2 },
});
});
it('dodaje serie tylko po normie tego cwiczenia — liczy normy per cwiczenie, a nie per sesja', async () => {
const prisma = mockPrisma();
mockSessionRow(prisma, 'IN_PROGRESS');
prisma.sessionExercise.findUnique.mockResolvedValue(ownedExercise);
prisma.sessionSet.count.mockResolvedValueOnce(0).mockResolvedValueOnce(0);
prisma.sessionSet.aggregate.mockResolvedValue({ _max: { index: 0 } });
prisma.sessionSet.create.mockResolvedValue({ id: 'st2', index: 1 });
await expect(addSet(prisma, 'se1', 'u1')).resolves.toEqual({ setId: 'st2', index: 1 });
// zapytanie o normy musi byc zawezone do cwiczenia (se1), nie do calej sesji
expect(prisma.sessionSet.count).toHaveBeenNthCalledWith(1, {
where: {
exerciseId: 'se1',
planSetId: { not: null },
reps: null,
removed: false,
},
});
});
});
describe('deleteSet', () => {

View File

@@ -482,8 +482,10 @@ export default function DayExecution() {
const session = sessionData?.session;
// Serie normowe (zaplanowane) to norma; serie nadmiarowe (bez planSetId) to bonus.
// Ukończenie sesji wymaga tylko serii normowych. Serię nadmiarową można dodać dopiero,
// gdy norma jest zrobiona i nie ma aktywnej (niezapisanej) serii nadmiarowej (max 1 na sesję).
// Ukończenie sesji wymaga tylko serii normowych. Serię nadmiarową można dodać, gdy
// WŁASNA norma danego ćwiczenia jest dowieziona (ćwiczenia dodane nie mają normy —
// warunek spełniony z definicji); norma innych ćwiczeń nie blokuje przekraczania.
// W sesji aktywna może być tylko jedna niezapisana seria bonusowa (max 1 na sesję).
const allSets = (session?.exercises ?? []).filter((ex) => !ex.removed).flatMap((ex) => ex.sets);
const normSets = allSets.filter((s) => s.planSetId != null);
const extraSets = allSets.filter((s) => s.planSetId == null);
@@ -493,7 +495,8 @@ export default function DayExecution() {
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;
const canAddExtra = normPending === 0 && extraPending === 0;
const canAddExtra = (exSets: { planSetId: string | null; reps: number | null }[]) =>
extraPending === 0 && !exSets.some((s) => s.planSetId != null && s.reps == null);
// Akordeon: rozwinięte jest ćwiczenie zawierające następną serię (aktywne);
// kliknięcie nagłówka przełącza rozwinięcie (jedno ćwiczenie naraz).
@@ -790,7 +793,7 @@ export default function DayExecution() {
expanded={expandedExId === ex.id}
inProgress={session.status === 'IN_PROGRESS'}
nextSetId={nextSetId}
canAddExtra={canAddExtra}
canAddExtra={canAddExtra(ex.sets)}
onToggle={() => toggleEx(ex.id)}
onRemove={() => removeExercise(ex)}
onEditSet={(s, i) => {

View File

@@ -302,10 +302,23 @@ describe('Kolejka serii w sesji', () => {
expect(completeBtn).toBeDisabled();
expect(screen.getByText(/została 1 seria/)).toBeInTheDocument();
// „Dodaj serię” zablokowany, dopóki norma nie jest zrobiona
// „Dodaj serię” zablokowany: własna norma niedokończona + aktywna seria bonusowa (1 na sesję)
expect(screen.getAllByRole('button', { name: 'Dodaj serię' })[0]).toBeDisabled();
});
it('odblokowuje „Dodaj serię” dla ćwiczenia bez normy mimo niedokończonej normy innego ćwiczenia', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': 12 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// Przysiady (rozwinięte): własna norma niedokończona (ss-2) => brak bonusu
expect(screen.getByRole('button', { name: 'Dodaj serię' })).toBeDisabled();
// Wyciskanie (dodane do sesji) nie ma normy planowej => bonus dostępny mimo ss-2
await user.click(screen.getByRole('button', { name: /Wyciskanie/ }));
expect(screen.getByRole('button', { name: 'Dodaj serię' })).toBeEnabled();
});
it('po zakończeniu wszystkich serii normowych odblokowuje ukończenie sesji', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': 12 });
const user = userEvent.setup();

View File

@@ -25,7 +25,8 @@ test('wyszczególnia założenia zaplanowanej serii i oznacza ćwiczenie dodane'
await expect(page.getByText('0%')).toBeVisible();
await expect(page.getByText('Następna', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: 'Ukończ sesję' })).toBeDisabled();
// „Dodaj serię” zablokowany, dopóki norma nie jest zrobiona (przycisk per ćwiczenie)
// Przysiady: własna norma (ss-1) niedokończona => brak bonusu; Wyciskanie blokuje
// limit jednej aktywnej serii bonusowej w sesji (ss-2 niezapisana)
await expect(page.getByRole('button', { name: 'Dodaj serię' }).first()).toBeDisabled();
});