Api: atomowy start sesji i spojna semantyka schedulera/killstreaka (koniec wyscigow, regimen dni skipped, bonus bez wplywu)

This commit is contained in:
tisachi
2026-10-11 15:45:19 +02:00
parent d466bc4e50
commit d544f6521c
13 changed files with 366 additions and 136 deletions

View File

@@ -26,7 +26,10 @@ export async function logActivity(prisma: PrismaClient, input: ActivityLogInput)
},
});
} catch (e) {
logger.error({ err: e, action: input.action, actorId: input.actorId }, 'Failed to write activity log');
logger.error(
{ err: e, action: input.action, actorId: input.actorId },
'Failed to write activity log',
);
}
}
@@ -62,11 +65,12 @@ export async function listActivityLogs(prisma: PrismaClient, filters: ActivityLo
const where: Prisma.ActivityLogWhereInput = {
...(filters.action ? { action: filters.action } : {}),
...(filters.userId ? { actorId: filters.userId } : {}),
// Granice dat w strefie serwera (jak reszta systemu), nie w UTC.
createdAt:
filters.from || filters.to
? {
...(filters.from ? { gte: new Date(`${filters.from}T00:00:00.000Z`) } : {}),
...(filters.to ? { lte: new Date(`${filters.to}T23:59:59.999Z`) } : {}),
...(filters.from ? { gte: new Date(`${filters.from}T00:00:00`) } : {}),
...(filters.to ? { lte: new Date(`${filters.to}T23:59:59.999`) } : {}),
}
: undefined,
};

View File

@@ -6,7 +6,15 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
where: { userId, status: 'ACTIVE' },
});
const killstreak = activePlan ? await getKillstreak(prisma, userId) : 0;
// Killstreak liczy dni także ze skończonych planów — sam brak aktywnego planu
// (np. minutowa przerwa między planami) nie zeruje wyniku z wczoraj.
const planHistory = activePlan
? true
: !!(await prisma.trainingPlan.findFirst({
where: { userId, status: 'COMPLETED' },
select: { id: true },
}));
const killstreak = planHistory ? await getKillstreak(prisma, userId) : 0;
let nextTraining: {
dayId: string;
@@ -20,7 +28,9 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
if (activePlan) {
const days = await prisma.planDay.findMany({
where: { week: { planId: activePlan.id } },
include: { exercises: { include: { exercise: { select: { name: true, primaryMuscle: true } } } } },
include: {
exercises: { include: { exercise: { select: { name: true, primaryMuscle: true } } } },
},
});
const now = new Date();
@@ -40,9 +50,7 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
}
const total = days.length;
const done = days.filter(
(d) => d.status === 'COMPLETED' || d.status === 'SKIPPED',
).length;
const done = days.filter((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED').length;
progress = {
completed: done,
total,
@@ -66,28 +74,30 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
// Missing = planned sets left undone in completed sessions
// (planned set count minus planned sets with recorded reps).
const completedSessions = await prisma.trainingSession.findMany({
where: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
include: {
exercises: {
where: { removed: false, hidden: false },
include: {
planExercise: { include: { sets: true } },
sets: { select: { planSetId: true, reps: true } },
},
// Agregacje zamiast pełnego wczytywania historii sesji.
const sessionExercises = await prisma.sessionExercise.findMany({
where: {
removed: false,
hidden: false,
session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
},
select: { planExercise: { select: { sets: { select: { id: true } } } } },
});
const plannedSetCount = sessionExercises.reduce(
(n, ex) => n + (ex.planExercise ? ex.planExercise.sets.length : 0),
0,
);
const donePlannedSetCount = await prisma.sessionSet.count({
where: {
planSetId: { not: null },
reps: { not: null },
exercise: {
removed: false,
hidden: false,
session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
},
},
});
let plannedSetCount = 0;
let donePlannedSetCount = 0;
for (const s of completedSessions) {
for (const ex of s.exercises) {
if (ex.planExercise) plannedSetCount += ex.planExercise.sets.length;
for (const st of ex.sets) {
if (st.planSetId != null && st.reps != null) donePlannedSetCount++;
}
}
}
missing = { sets: plannedSetCount - donePlannedSetCount };
}

View File

@@ -11,7 +11,11 @@ export interface EffectiveSession {
/**
* A training is "effective" (counts toward killstreak) when the user performed
* all sets of the session: planned sets + sets of added exercises.
* the session: every planned (norm) set has reps recorded, and every exercise
* added beyond the plan has at least one recorded set.
* Extra (bonus) sets are exactly that — a bonus: recorded or not, they never
* affect effectiveness (same rule as completing the session, which extras
* never block).
*/
export function isSessionEffective(session: EffectiveSession): boolean {
for (const ex of session.exercises) {
@@ -22,10 +26,8 @@ export function isSessionEffective(session: EffectiveSession): boolean {
if (!done) return false;
}
} else {
if (ex.sets.length === 0) return false;
for (const s of ex.sets) {
if (s.reps == null) return false;
}
// Ćwiczenie dodane: bez ani jednej zapisanej serii trening się nie liczy.
if (!ex.sets.some((s) => s.reps != null)) return false;
}
}
return true;
@@ -35,11 +37,13 @@ export function isSessionEffective(session: EffectiveSession): boolean {
* Killstreak = number of consecutive effective trainings (regardless of day).
* Grows by 1 for each effective training; resets to 0 after a skip
* (including auto-expired days) or a partially completed day.
* Counts days of ACTIVE and COMPLETED plans — finishing a plan does not wipe
* the streak built the day before its end.
*/
export async function getKillstreak(prisma: PrismaClient, userId: string): Promise<number> {
const days = await prisma.planDay.findMany({
where: {
week: { plan: { userId, status: 'ACTIVE' } },
week: { plan: { userId, status: { in: ['ACTIVE', 'COMPLETED'] } } },
date: { not: null },
},
orderBy: { date: 'asc' },

View File

@@ -3,10 +3,13 @@ import { logger } from '../lib/logger.js';
/**
* Background jobs (every 60s):
* 1. Auto-expire training days at 23:59 of their date -> skipped.
* 2. Auto-abandon sessions after 24h.
* 3. Auto-complete active plans when all days are completed/skipped.
* 4. Remove gym schedule exceptions whose date is in the past.
* 1. Auto-expire training days whose date has passed -> skipped.
* 2. Abandon in-progress sessions belonging to expired days (the day is closed,
* the training can no longer be completed).
* 3. Auto-abandon sessions after 24h; the day they belong to is skipped too
* (same rule as manual abandonment — an abandoned training is not retryable).
* 4. Auto-complete active plans when all days are completed/skipped.
* 5. Remove gym schedule exceptions whose date is in the past.
*/
export function startScheduler(prisma: PrismaClient): void {
const tick = async () => {
@@ -20,13 +23,32 @@ export function startScheduler(prisma: PrismaClient): void {
});
if (expired.count > 0) logger.info({ count: expired.count }, 'Auto-expired days -> skipped');
const cutoff = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const abandoned = await prisma.trainingSession.updateMany({
where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } },
// Sesja dnia, który wygasł, nigdy nie zostanie już ukończona — porządek natychmiast.
const orphaned = await prisma.trainingSession.updateMany({
where: { status: 'IN_PROGRESS', day: { status: 'SKIPPED' } },
data: { status: 'ABANDONED', endedAt: now },
});
if (abandoned.count > 0)
logger.info({ count: abandoned.count }, 'Auto-abandoned sessions (24h)');
if (orphaned.count > 0)
logger.info({ count: orphaned.count }, 'Abandoned sessions of expired days');
const cutoff = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const stale = await prisma.trainingSession.findMany({
where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } },
select: { id: true, dayId: true },
});
if (stale.length > 0) {
await prisma.trainingSession.updateMany({
where: { id: { in: stale.map((s) => s.id) } },
data: { status: 'ABANDONED', endedAt: now },
});
// Porzucona sesja nie może pozwalać na ponowne wykonanie dnia —
// dokładnie tak samo jak przy ręcznym porzuceniu sesji.
await prisma.planDay.updateMany({
where: { id: { in: [...new Set(stale.map((s) => s.dayId))] }, status: 'PLANNED' },
data: { status: 'SKIPPED', skippedAt: now },
});
logger.info({ count: stale.length }, 'Auto-abandoned sessions (24h)');
}
const activePlans = await prisma.trainingPlan.findMany({
where: { status: 'ACTIVE' },

View File

@@ -45,37 +45,41 @@ export async function startSession(prisma: PrismaClient, dayId: string, userId:
});
if (!day || day.week.plan.userId !== userId) throw notFound('Day not found');
if (day.status !== 'PLANNED') throw badRequest('Day is not in planned state');
// 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');
const session = await prisma.trainingSession.create({ data: { dayId: day.id } });
if (day.exercises.length > 0) {
await prisma.sessionExercise.createMany({
data: day.exercises.map((e) => ({
sessionId: session.id,
exerciseId: e.exerciseId,
planExerciseId: e.id,
order: e.order,
})),
// 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 },
});
for (const e of day.exercises) {
if (e.sets.length === 0) continue;
const se = await prisma.sessionExercise.findFirst({
where: { sessionId: session.id, planExerciseId: e.id },
});
if (se) {
await prisma.sessionSet.createMany({
data: e.sets.map((ps) => ({
exerciseId: se.id,
planSetId: ps.id,
index: ps.index,
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 };
}
@@ -193,8 +197,7 @@ export async function updateExercise(
data: UpdateExerciseInput,
) {
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
if (exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
if (exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
await prisma.sessionExercise.update({
where: { id: exercise.id },
data,
@@ -209,8 +212,7 @@ export async function updateExercise(
*/
export async function addSet(prisma: PrismaClient, exerciseId: string, userId: string) {
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
if (exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
if (exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
const sets = await prisma.sessionSet.findMany({
where: { exercise: { sessionId: exercise.session.id }, removed: false },
});
@@ -218,8 +220,7 @@ export async function addSet(prisma: PrismaClient, exerciseId: string, userId: s
if (pendingNorm > 0)
throw badRequest('All planned sets must be recorded before adding an extra set');
const pendingExtra = sets.filter((s) => s.planSetId == null && s.reps == null).length;
if (pendingExtra > 0)
throw badRequest('An extra set is already in progress');
if (pendingExtra > 0) throw badRequest('An extra set is already in progress');
const maxIndex = await prisma.sessionSet.aggregate({
where: { exerciseId: exercise.id },
_max: { index: true },
@@ -238,12 +239,16 @@ export async function updateSet(
) {
const set = await prisma.sessionSet.findUnique({
where: { id: setId },
include: { exercise: { include: { session: { include: { day: { include: { week: { include: { plan: true } } } } } } } } },
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.exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
if (!set || set.exercise.session.day.week.plan.userId !== userId) throw notFound('Set not found');
if (set.exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
const updated = await prisma.sessionSet.update({
where: { id: set.id },
data,
@@ -258,14 +263,17 @@ export async function updateSet(
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 } } } } } } } } },
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');
if (set.exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
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');
if (set.exercise.session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
await prisma.sessionSet.update({ where: { id: set.id }, data: { removed: true } });
return { ok: true };
}
@@ -283,18 +291,24 @@ export async function completeSession(prisma: PrismaClient, sessionId: string, u
0,
);
if (pending > 0)
throw badRequest(`All planned sets must be recorded before completing the session (${pending} remaining)`);
throw badRequest(
`All planned sets must be recorded before completing the session (${pending} remaining)`,
);
const now = new Date();
await prisma.$transaction([
prisma.trainingSession.update({
where: { id: session.id },
// Atomowe zamknięcie sesji i dnia: 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) => {
const s = await tx.trainingSession.updateMany({
where: { id: session.id, status: 'IN_PROGRESS' },
data: { status: 'COMPLETED', endedAt: now },
}),
prisma.planDay.update({
where: { id: session.dayId },
});
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 };
}
@@ -306,15 +320,18 @@ export async function abandonSession(prisma: PrismaClient, sessionId: string, us
const session = await getSessionOwned(prisma, sessionId, userId);
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
const now = new Date();
await prisma.$transaction([
prisma.trainingSession.update({
where: { id: session.id },
await prisma.$transaction(async (tx) => {
const s = await tx.trainingSession.updateMany({
where: { id: session.id, status: 'IN_PROGRESS' },
data: { status: 'ABANDONED', endedAt: now },
}),
prisma.planDay.update({
where: { id: session.dayId },
});
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' },
data: { status: 'SKIPPED', skippedAt: now },
}),
]);
});
});
return { ok: true };
}