Trening: ukonczenie sesji zablokowane przy niezapisanej serii bonusowej (serwer 400 + alert modal); niepelne ukonczenie pozostaje przez porzucenie
This commit is contained in:
@@ -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 ćwiczenie; dodanie ćwiczenia do sesji automatycznie tworzy mu pierwszą (pustą) serię.
|
||||
- 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).
|
||||
- PWA: tylko instalowalność (manifest), bez cache offline.
|
||||
|
||||
@@ -196,12 +196,12 @@ export function createSessionRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /sessions/{id}/complete:
|
||||
* post:
|
||||
* summary: Complete session (requires all planned/norm sets recorded; extra sets are
|
||||
* a bonus and don't block; day -> completed)
|
||||
* summary: Complete session (requires all planned/norm sets recorded and no extra set
|
||||
* still in progress — recorded bonus sets don't block; day -> completed)
|
||||
* tags: [Sessions]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 400: { description: Session not in progress or planned sets still pending }
|
||||
* 400: { description: Session not in progress, planned sets still pending, or an extra set in progress }
|
||||
*/
|
||||
router.post(
|
||||
'/sessions/:id/complete',
|
||||
|
||||
@@ -341,7 +341,7 @@ export async function completeSession(prisma: PrismaClient, sessionId: string, u
|
||||
where: { sessionId: session.id, removed: false },
|
||||
include: { sets: true },
|
||||
});
|
||||
// Only planned (norm) sets must be recorded; extra sets are a bonus and don't block.
|
||||
// Tylko serie planowe (normowe) muszą być zapisane, żeby trening był ważny.
|
||||
const pending = exercises.reduce(
|
||||
(n, e) =>
|
||||
n + e.sets.filter((s) => !s.removed && s.planSetId != null && s.reps == null).length,
|
||||
@@ -351,6 +351,17 @@ export async function completeSession(prisma: PrismaClient, sessionId: string, u
|
||||
throw badRequest(
|
||||
`All planned sets must be recorded before completing the session (${pending} remaining)`,
|
||||
);
|
||||
// Seria bonusowa „w toku" nie może przeżyć sesji — koniec treningu wymaga jej
|
||||
// domknięcia (zapis lub usunięcie), inaczej kończenie sprzyja niechlujstwu.
|
||||
const pendingExtra = exercises.reduce(
|
||||
(n, e) =>
|
||||
n + e.sets.filter((s) => !s.removed && s.planSetId == null && s.reps == null).length,
|
||||
0,
|
||||
);
|
||||
if (pendingExtra > 0)
|
||||
throw badRequest(
|
||||
`Extra sets must be recorded or removed before completing the session (${pendingExtra} remaining)`,
|
||||
);
|
||||
const s = await tx.trainingSession.updateMany({
|
||||
where: { id: session.id, status: 'IN_PROGRESS' },
|
||||
data: { status: 'COMPLETED', endedAt: now },
|
||||
|
||||
@@ -339,6 +339,20 @@ describe('sessions routes', () => {
|
||||
expect(res.body.error.message).toBe('An extra set is already in progress');
|
||||
});
|
||||
|
||||
it('rejects completing the session while a bonus set is still pending 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}/complete`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe(
|
||||
'Extra sets must be recorded or removed before completing the session (1 remaining)',
|
||||
);
|
||||
});
|
||||
|
||||
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}`);
|
||||
|
||||
@@ -230,7 +230,7 @@ describe('completeSession', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('completes the session when all norm sets are recorded (extra sets pending = bonus)', async () => {
|
||||
it('400 when an extra (bonus) set is still pending (niechlujny koniec zablokowany)', async () => {
|
||||
const prisma = mockPrisma();
|
||||
prisma.trainingSession.findUnique.mockResolvedValue(ownedInProgress);
|
||||
prisma.sessionExercise.findMany.mockResolvedValue([
|
||||
@@ -244,6 +244,29 @@ 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)',
|
||||
});
|
||||
expect(prisma.trainingSession.updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('completes the session when all norm sets are recorded (bonusy zapisane/usuniete = OK)', 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 },
|
||||
{ id: 'st2', planSetId: 'ps2', reps: 8, removed: false },
|
||||
{ id: 'st3', planSetId: null, reps: 12, removed: false },
|
||||
{ id: 'st4', planSetId: null, reps: null, removed: true },
|
||||
],
|
||||
},
|
||||
]);
|
||||
prisma.trainingSession.updateMany.mockResolvedValue({ count: 1 });
|
||||
prisma.planDay.updateMany.mockResolvedValue({ count: 1 });
|
||||
|
||||
|
||||
@@ -511,8 +511,8 @@ export default function DayExecution() {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmAbandon, setConfirmAbandon] = useState(false);
|
||||
const [addExerciseOpen, setAddExerciseOpen] = useState(false);
|
||||
// powód zablokowania „Dodaj serię" pokazany w alercie (null = alert zamknięty)
|
||||
const [addSetAlert, setAddSetAlert] = useState<string | null>(null);
|
||||
// alert blokowanej akcji („Dodaj serię" / „Ukończ sesję") — powód w oknie modalnym
|
||||
const [actionAlert, setActionAlert] = useState<{ title: string; message: string } | null>(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).
|
||||
@@ -571,6 +571,7 @@ 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.
|
||||
@@ -671,6 +672,14 @@ export default function DayExecution() {
|
||||
|
||||
const complete = async () => {
|
||||
if (!session) return;
|
||||
// niezapisany bonus nie może przeżyć sesji — koniec dopiero po jego domknięciu
|
||||
if (extraPending > 0) {
|
||||
setActionAlert({
|
||||
title: 'Nie można ukończyć sesji',
|
||||
message: `Masz niezapisane serie bonusowe (${extraPending}) — najpierw uzupełnij je lub usuń, potem ukończ trening.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
@@ -768,7 +777,7 @@ export default function DayExecution() {
|
||||
// blokada po stronie klienta z komunikatem w alercie (serwer broni się dodatkowo)
|
||||
const blocked = addSetBlockedReason(session.exercises.find((e) => e.id === exerciseId));
|
||||
if (blocked) {
|
||||
setAddSetAlert(blocked);
|
||||
setActionAlert({ title: 'Nie można dodać serii', message: blocked });
|
||||
return;
|
||||
}
|
||||
addingRef.current = true;
|
||||
@@ -943,10 +952,10 @@ export default function DayExecution() {
|
||||
/>
|
||||
|
||||
<AlertModal
|
||||
open={addSetAlert !== null}
|
||||
onClose={() => setAddSetAlert(null)}
|
||||
title="Nie można dodać serii"
|
||||
message={addSetAlert ?? ''}
|
||||
open={actionAlert !== null}
|
||||
onClose={() => setActionAlert(null)}
|
||||
title={actionAlert?.title ?? ''}
|
||||
message={actionAlert?.message ?? ''}
|
||||
/>
|
||||
|
||||
<SetEditDialog
|
||||
|
||||
@@ -362,6 +362,25 @@ describe('Kolejka serii w sesji', () => {
|
||||
).not.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();
|
||||
renderApp();
|
||||
await openActiveDay(user);
|
||||
|
||||
// normy zrobione (100%) => przycisk aktywny, ale niewidoczny bonus w toku blokuje koniec
|
||||
expect(await screen.findByText('100%')).toBeInTheDocument();
|
||||
const completeBtn = screen.getByRole('button', { name: 'Ukończ sesję' });
|
||||
expect(completeBtn).toBeEnabled();
|
||||
await user.click(completeBtn);
|
||||
expect(screen.getByRole('dialog', { name: /Nie można ukończyć sesji/ })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Masz niezapisane serie bonusowe (1) — najpierw uzupełnij je lub usuń, potem ukończ trening.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('przewija widok do następnej serii do uzupełnienia (auto-nawigacja)', async () => {
|
||||
const spy = vi.fn();
|
||||
const orig = Element.prototype.scrollIntoView;
|
||||
|
||||
Reference in New Issue
Block a user