Trening: wznowienie ukonczonej sesji (naprawa pomyly) - endpoint /reopen, akcja w UI, koniec wraca do edycji
This commit is contained in:
@@ -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' };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user