400 lines
15 KiB
TypeScript
400 lines
15 KiB
TypeScript
import type { Prisma, PrismaClient } from '@prisma/client';
|
|
import { badRequest, conflict, notFound } from '../lib/errors.js';
|
|
|
|
export interface UpdateExerciseInput {
|
|
hidden?: boolean;
|
|
removed?: boolean;
|
|
}
|
|
|
|
export interface UpdateSetInput {
|
|
reps?: number | null;
|
|
rir?: number | null;
|
|
difficulty?: number | null;
|
|
note?: string | null;
|
|
}
|
|
|
|
async function getSessionOwned(prisma: PrismaClient, sessionId: string, userId: string) {
|
|
const session = await prisma.trainingSession.findUnique({
|
|
where: { id: sessionId },
|
|
include: { day: { include: { week: { include: { plan: true } } } } },
|
|
});
|
|
if (!session || session.day.week.plan.userId !== userId) throw notFound('Session not found');
|
|
return session;
|
|
}
|
|
|
|
async function getExerciseOwned(prisma: PrismaClient, exerciseId: string, userId: string) {
|
|
const exercise = await prisma.sessionExercise.findUnique({
|
|
where: { id: exerciseId },
|
|
include: { session: { include: { day: { include: { week: { include: { plan: true } } } } } } },
|
|
});
|
|
if (!exercise || exercise.session.day.week.plan.userId !== userId)
|
|
throw notFound('Exercise not found');
|
|
return exercise;
|
|
}
|
|
|
|
/**
|
|
* Wszystkie modyfikacje i zakończenie sesji serializujemy na wierszu sesji
|
|
* (SELECT ... FOR UPDATE), więc sprawdzenie statusu IN_PROGRESS i kontrola
|
|
* „wszystkie serie planowe zapisane" przy ukończeniu są wolne od wyścigu —
|
|
* równoległe nadpisanie serii przez klienta nie może przejść między kontrolę
|
|
* a zapis COMPLETED.
|
|
*/
|
|
async function inSessionTransaction<T>(
|
|
prisma: PrismaClient,
|
|
sessionId: string,
|
|
fn: (tx: Prisma.TransactionClient) => Promise<T>,
|
|
): Promise<T> {
|
|
return prisma.$transaction(async (tx) => {
|
|
await tx.$executeRaw`SELECT id FROM "TrainingSession" WHERE id = ${sessionId} FOR UPDATE`;
|
|
const s = await tx.trainingSession.findUnique({
|
|
where: { id: sessionId },
|
|
select: { status: true },
|
|
});
|
|
if (!s) throw notFound('Session not found');
|
|
if (s.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
|
return fn(tx);
|
|
});
|
|
}
|
|
|
|
export async function startSession(prisma: PrismaClient, dayId: string, userId: string) {
|
|
const day = await prisma.planDay.findUnique({
|
|
where: { id: dayId },
|
|
include: {
|
|
week: { include: { plan: true } },
|
|
exercises: {
|
|
orderBy: { order: 'asc' },
|
|
include: { sets: { orderBy: { index: 'asc' } } },
|
|
},
|
|
},
|
|
});
|
|
if (!day || day.week.plan.userId !== userId) throw notFound('Day not found');
|
|
if (day.status !== 'PLANNED') throw badRequest('Day is not in planned state');
|
|
// dzień należy do planu — trening ma sens tylko w aktywnym planie (bez DRAFT/ABANDONED/COMPLETED)
|
|
if (day.week.plan.status !== 'ACTIVE') throw badRequest('Training plan is not active');
|
|
// Szybka ścieżka — rozstrzygające sprawdzenie jest w transakcji (pod blokadą).
|
|
const active = await prisma.trainingSession.findFirst({
|
|
where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } } },
|
|
orderBy: { startedAt: 'desc' },
|
|
});
|
|
if (active) throw conflict('You already have an active session');
|
|
// Całość musi być atomowa: kopiowanie dnia (sesja + ćwiczenia + serie) nie może
|
|
// zostawić „pół-sesji" przy błędzie w połowie zapisu.
|
|
// Blokada doradcza per użytkownik serializuje równoległe starty, więc sprawdzenie
|
|
// „jedna aktywna sesja" + wstawienie jest wolne od wyścigu; częściowy indeks
|
|
// unikalny (dayId WHERE IN_PROGRESS) jest ostatnią linią obrony w bazie.
|
|
const session = await prisma.$transaction(async (tx) => {
|
|
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${userId}))`;
|
|
const activeInTx = await tx.trainingSession.findFirst({
|
|
where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } } },
|
|
select: { id: true },
|
|
});
|
|
if (activeInTx) throw conflict('You already have an active session');
|
|
return tx.trainingSession.create({
|
|
data: {
|
|
dayId: day.id,
|
|
exercises: {
|
|
create: day.exercises.map((e) => ({
|
|
exerciseId: e.exerciseId,
|
|
planExerciseId: e.id,
|
|
order: e.order,
|
|
sets: {
|
|
create: e.sets.map((ps) => ({ planSetId: ps.id, index: ps.index })),
|
|
},
|
|
})),
|
|
},
|
|
},
|
|
select: { id: true, status: true },
|
|
});
|
|
});
|
|
return { sessionId: session.id, status: session.status };
|
|
}
|
|
|
|
/** Active (IN_PROGRESS) session of the user — for the sidebar link and dashboard shortcut. */
|
|
export async function getActiveSession(prisma: PrismaClient, userId: string) {
|
|
const session = await prisma.trainingSession.findFirst({
|
|
where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } } },
|
|
orderBy: { startedAt: 'desc' },
|
|
include: {
|
|
day: {
|
|
select: {
|
|
id: true,
|
|
date: true,
|
|
dayOfWeek: true,
|
|
week: { select: { plan: { select: { title: true } } } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
if (!session) return { session: null };
|
|
return {
|
|
session: {
|
|
id: session.id,
|
|
dayId: session.dayId,
|
|
dayDate: session.day.date,
|
|
dayOfWeek: session.day.dayOfWeek,
|
|
planTitle: session.day.week.plan.title,
|
|
startedAt: session.startedAt,
|
|
},
|
|
};
|
|
}
|
|
|
|
export async function getDay(prisma: PrismaClient, dayId: string, userId: string) {
|
|
const day = await prisma.planDay.findUnique({
|
|
where: { id: dayId },
|
|
include: {
|
|
week: { include: { plan: true } },
|
|
sessions: { orderBy: { startedAt: 'desc' } },
|
|
exercises: {
|
|
orderBy: { order: 'asc' },
|
|
include: { exercise: { select: { name: true, primaryMuscle: true } } },
|
|
},
|
|
},
|
|
});
|
|
if (!day || day.week.plan.userId !== userId) throw notFound('Day not found');
|
|
return {
|
|
day: {
|
|
id: day.id,
|
|
date: day.date,
|
|
status: day.status,
|
|
dayOfWeek: day.dayOfWeek,
|
|
planId: day.week.planId,
|
|
sessions: day.sessions.map((s) => ({ id: s.id, status: s.status, startedAt: s.startedAt })),
|
|
exercises: day.exercises.map((e) => ({
|
|
id: e.id,
|
|
name: e.exercise.name,
|
|
muscle: e.exercise.primaryMuscle,
|
|
})),
|
|
},
|
|
};
|
|
}
|
|
|
|
export async function getSession(prisma: PrismaClient, sessionId: string, userId: string) {
|
|
await getSessionOwned(prisma, sessionId, userId);
|
|
const session = await prisma.trainingSession.findUnique({
|
|
where: { id: sessionId },
|
|
include: {
|
|
day: {
|
|
include: {
|
|
week: { include: { plan: { select: { id: true, title: true, status: true } } } },
|
|
moveLog: { orderBy: { movedAt: 'desc' } },
|
|
},
|
|
},
|
|
exercises: {
|
|
orderBy: { order: 'asc' },
|
|
include: {
|
|
exercise: true,
|
|
sets: { where: { removed: false }, orderBy: { index: 'asc' } },
|
|
planExercise: { include: { sets: { orderBy: { index: 'asc' } } } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
return { session };
|
|
}
|
|
|
|
export async function addExercise(
|
|
prisma: PrismaClient,
|
|
sessionId: string,
|
|
userId: string,
|
|
exerciseId: string,
|
|
) {
|
|
const session = await getSessionOwned(prisma, sessionId, userId);
|
|
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
|
const template = await prisma.exercise.findUnique({ where: { id: exerciseId } });
|
|
if (!template) throw notFound('Exercise not found');
|
|
// Kolejność i kontrola statusu pod blokadą sesji — dwa równoległe dodania
|
|
// nie mogą trafić na ten sam `order` (unikalny indeks w bazie dałby 500).
|
|
const exercise = await inSessionTransaction(prisma, sessionId, async (tx) => {
|
|
const maxOrder = await tx.sessionExercise.aggregate({
|
|
where: { sessionId },
|
|
_max: { order: true },
|
|
});
|
|
return tx.sessionExercise.create({
|
|
data: {
|
|
sessionId,
|
|
exerciseId: template.id,
|
|
order: (maxOrder._max.order ?? -1) + 1,
|
|
},
|
|
});
|
|
});
|
|
return { exerciseId: exercise.id, order: exercise.order };
|
|
}
|
|
|
|
export async function updateExercise(
|
|
prisma: PrismaClient,
|
|
exerciseId: string,
|
|
userId: string,
|
|
data: UpdateExerciseInput,
|
|
) {
|
|
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
|
|
// Ćwiczenie z planu można ukryć, ale nie usunąć — usuwanie nie może „wybaczać"
|
|
// nieodpisanych serii planowych; kasować wolno tylko ćwiczenia dodane do sesji.
|
|
if (data.removed === true && exercise.planExerciseId != null) {
|
|
throw badRequest('Only exercises added to the session can be removed');
|
|
}
|
|
await inSessionTransaction(prisma, exercise.sessionId, (tx) =>
|
|
tx.sessionExercise.update({ where: { id: exercise.id }, data }),
|
|
);
|
|
return { ok: true };
|
|
}
|
|
|
|
/**
|
|
* Add an extra (bonus) set to a session exercise.
|
|
* 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 pendingNorm = await tx.sessionSet.count({
|
|
where: { exerciseId: exercise.id, planSetId: { not: null }, reps: null, removed: false },
|
|
});
|
|
if (pendingNorm > 0)
|
|
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 },
|
|
_max: { index: true },
|
|
});
|
|
return tx.sessionSet.create({
|
|
data: { exerciseId: exercise.id, index: (maxIndex._max.index ?? -1) + 1 },
|
|
});
|
|
});
|
|
return { setId: set.id, index: set.index };
|
|
}
|
|
|
|
export async function updateSet(
|
|
prisma: PrismaClient,
|
|
setId: string,
|
|
userId: string,
|
|
data: UpdateSetInput,
|
|
) {
|
|
const set = await prisma.sessionSet.findUnique({
|
|
where: { id: setId },
|
|
include: {
|
|
exercise: {
|
|
include: {
|
|
session: { include: { day: { include: { week: { include: { plan: true } } } } } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
if (!set || set.exercise.session.day.week.plan.userId !== userId) throw notFound('Set not found');
|
|
// status + zapis pod blokadą sesji (patrz inSessionTransaction)
|
|
const updated = await inSessionTransaction(prisma, set.exercise.sessionId, (tx) =>
|
|
tx.sessionSet.update({ where: { id: set.id }, data }),
|
|
);
|
|
return { set: updated };
|
|
}
|
|
|
|
/**
|
|
* Remove an extra (bonus) set from a session. Only extra sets (no planned
|
|
* counterpart) can be removed — and without consequence for the norm.
|
|
*/
|
|
export async function deleteSet(prisma: PrismaClient, setId: string, userId: string) {
|
|
const set = await prisma.sessionSet.findUnique({
|
|
where: { id: setId },
|
|
include: {
|
|
exercise: {
|
|
include: {
|
|
session: { include: { day: { include: { week: { include: { plan: true } } } } } },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
if (!set || set.exercise.session.day.week.plan.userId !== userId) throw notFound('Set not found');
|
|
if (set.planSetId != null) throw badRequest('Only extra sets can be removed');
|
|
await inSessionTransaction(prisma, set.exercise.sessionId, (tx) =>
|
|
tx.sessionSet.update({ where: { id: set.id }, data: { removed: true } }),
|
|
);
|
|
return { ok: true };
|
|
}
|
|
|
|
export async function completeSession(prisma: PrismaClient, sessionId: string, userId: string) {
|
|
const session = await getSessionOwned(prisma, sessionId, userId);
|
|
// Szybka ścieżka dla czytelnego 400; rozstrzygnięcie pod blokadą w transakcji.
|
|
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
|
const now = new Date();
|
|
// Atomowe zamknięcie sesji i dnia: kontrola „wszystkie serie planowe zapisane"
|
|
// musi nastąpić PO zablokowaniu wiersza sesji — inaczej równoległe
|
|
// wyczyszczenie serii (updateSet) weszłoby między kontrolę a COMPLETED.
|
|
// Dzień można oznaczyć jako wykonany tylko gdy wciąż jest zaplanowany —
|
|
// wygasły (SKIPPED) nie może „ożyć" jako COMPLETED.
|
|
await prisma.$transaction(async (tx) => {
|
|
await tx.$executeRaw`SELECT id FROM "TrainingSession" WHERE id = ${session.id} FOR UPDATE`;
|
|
const s0 = await tx.trainingSession.findUnique({
|
|
where: { id: session.id },
|
|
select: { status: true },
|
|
});
|
|
if (!s0 || s0.status !== 'IN_PROGRESS') throw conflict('Session is no longer in progress');
|
|
const exercises = await tx.sessionExercise.findMany({
|
|
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.
|
|
const pending = exercises.reduce(
|
|
(n, e) =>
|
|
n + e.sets.filter((s) => !s.removed && s.planSetId != null && s.reps == null).length,
|
|
0,
|
|
);
|
|
if (pending > 0)
|
|
throw badRequest(
|
|
`All planned sets must be recorded before completing the session (${pending} remaining)`,
|
|
);
|
|
const s = await tx.trainingSession.updateMany({
|
|
where: { id: session.id, status: 'IN_PROGRESS' },
|
|
data: { status: 'COMPLETED', endedAt: now },
|
|
});
|
|
if (s.count === 0) throw conflict('Session is no longer in progress');
|
|
const d = await tx.planDay.updateMany({
|
|
where: { id: session.dayId, status: 'PLANNED' },
|
|
data: { status: 'COMPLETED', completedAt: now },
|
|
});
|
|
if (d.count === 0) throw conflict('Training day is no longer planned');
|
|
});
|
|
return { ok: true };
|
|
}
|
|
|
|
/**
|
|
* Abandon an in-progress session. The day is marked SKIPPED so the abandoned
|
|
* training cannot be executed again (no new session can be started for it).
|
|
*/
|
|
export async function abandonSession(prisma: PrismaClient, sessionId: string, userId: string) {
|
|
const session = await getSessionOwned(prisma, sessionId, userId);
|
|
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
|
|
const now = new Date();
|
|
// Dzień w przyszłości nie zostaje „skipnięty" przez porzuconą sesję — wraca do
|
|
// PLANNED i da się go wykonać normalnie; SKIPPED tylko dla dni, które nadszedł czas.
|
|
const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
|
|
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: 'IN_PROGRESS' },
|
|
data: { status: 'ABANDONED', endedAt: now },
|
|
});
|
|
if (s.count === 0) throw conflict('Session is no longer in progress');
|
|
// Dzień oznaczamy jako pominięty tylko gdy wciąż jest zaplanowany
|
|
// (mógł już wygasnąć w schedulerze — wtedy nie nadpisujemy).
|
|
await tx.planDay.updateMany({
|
|
where: { id: session.dayId, status: 'PLANNED', date: { lt: startOfTomorrow } },
|
|
data: { status: 'SKIPPED', skippedAt: now },
|
|
});
|
|
});
|
|
return { ok: true };
|
|
}
|