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

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