Trening: wznowienie ukonczonej sesji (naprawa pomyly) - endpoint /reopen, akcja w UI, koniec wraca do edycji

This commit is contained in:
Tilumca
2026-10-14 22:37:52 +02:00
parent 9f7a0afdec
commit 931d54a89d
10 changed files with 296 additions and 17 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.
- 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).

View File

@@ -24,6 +24,7 @@ export const ACTION_LABELS: Record<string, string> = {
'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() {
<table className="w-full text-[0.95rem]">
<thead>
<tr className="border-b border-line text-left text-dim">
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Data</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Użytkownik</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Akcja</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Obiekt</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">Szczegóły</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
Data
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
Użytkownik
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
Akcja
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
Obiekt
</th>
<th className="px-4 py-3 text-[10.5px] font-bold uppercase tracking-[0.11em]">
Szczegóły
</th>
</tr>
</thead>
<tbody>
{filtered.map((log) => (
<tr key={log.id} className="border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20">
<td className="whitespace-nowrap px-4 py-3 font-display text-dim tabular-nums">{formatLogDate(log.createdAt)}</td>
<tr
key={log.id}
className="border-b border-line/60 transition-colors last:border-b-0 hover:bg-line/20"
>
<td className="whitespace-nowrap px-4 py-3 font-display text-dim tabular-nums">
{formatLogDate(log.createdAt)}
</td>
<td className="px-4 py-3">
<div className="font-semibold">{actorName(log)}</div>
<div className="text-[0.875rem] text-dim">{log.actor.email}</div>
@@ -249,7 +265,9 @@ export default function Logs() {
</td>
<td className="px-4 py-3">
<div>{ENTITY_LABELS[log.entityType] ?? log.entityType}</div>
{entityName(log) && <div className="text-[0.875rem] text-dim">{entityName(log)}</div>}
{entityName(log) && (
<div className="text-[0.875rem] text-dim">{entityName(log)}</div>
)}
</td>
<td className="px-4 py-3 text-dim">{detailsText(log) ?? '—'}</td>
</tr>

View File

@@ -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;
}

View File

@@ -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' };
}

View File

@@ -876,6 +876,15 @@ export const openapi: Record<string, unknown> = {
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'],

View File

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

View File

@@ -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();

View File

@@ -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>('/dashboard') });

View File

@@ -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)

View File

@@ -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();