Files
FitOS/api/src/services/killstreak.ts

85 lines
2.8 KiB
TypeScript

import type { PrismaClient } from '@prisma/client';
export interface EffectiveSession {
exercises: {
hidden: boolean;
removed: boolean;
planExercise: { sets: { id: string }[] } | null;
sets: { planSetId: string | null; reps: number | null }[];
}[];
}
/**
* A training is "effective" (counts toward killstreak) when the user performed
* 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) {
if (ex.hidden || ex.removed) continue;
if (ex.planExercise) {
for (const ps of ex.planExercise.sets) {
const done = ex.sets.some((s) => s.planSetId === ps.id && s.reps != null);
if (!done) return false;
}
} else {
// Ćwiczenie dodane: bez ani jednej zapisanej serii trening się nie liczy.
if (!ex.sets.some((s) => s.reps != null)) return false;
}
}
return true;
}
/**
* 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: { in: ['ACTIVE', 'COMPLETED'] } } },
date: { not: null },
},
orderBy: { date: 'asc' },
include: {
sessions: {
where: { status: 'COMPLETED' },
include: {
exercises: {
include: {
sets: { select: { planSetId: true, reps: true } },
planExercise: { include: { sets: { select: { id: true } } } },
},
},
},
},
},
});
const now = new Date();
const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
let streak = 0;
for (const day of days) {
if (day.date! >= startOfTomorrow) break; // future day — not yet relevant
if (day.status === 'COMPLETED') {
const session = day.sessions[0];
if (session && isSessionEffective(session)) {
streak++; // effective training
} else {
streak = 0; // partially completed day resets the streak
}
} else if (day.status === 'SKIPPED') {
streak = 0; // skipped (manual or auto-expired) resets the streak
}
// PLANNED days (today, not yet done) do not change the streak
}
return streak;
}