import type { PrismaClient } from '@prisma/client'; import { epleyOneRm, effectiveLoadKg, isCountedSet } from '../lib/strengthStats.js'; import { latestWeightAtOrBefore } from './exerciseProgress.js'; export interface StatsSetRaw { reps: number | null; loadKg: number | null; } export interface StatsEquipmentRaw { id: string; name: string; nameEn: string | null; } export interface StatsExerciseRaw { exerciseId: string; name: string; nameEn: string | null; muscle: string; equipment: StatsEquipmentRaw[]; sets: StatsSetRaw[]; } export interface RawStatsSession { /** ISO start sesji (heatma/pory dnia liczone po nim, jak w presence). */ startedAt: string; endedAt: string | null; gym: { id: string; name: string } | null; /** Masa ciała (kg) w dacie sesji — seria bez obciążenia = masa ciała. */ bodyKg: number | null; exercises: StatsExerciseRaw[]; } export interface UserStats { rangeDays: number | null; sessions: { count: number; sets: number; reps: number; avgMinutes: number | null }; /** Tonaż Σ obciążenie × powt. w wybranym zakresie (null obciążenie → seria poza tonażem). */ tonnageKg: number; /** Tonaż z całej historii (ekwiwalenty „przeniesione tony"). */ tonnageAllTimeKg: number; /** Ulubiona siłownia (sesje planów z tym gymem); null = brak atrybuowanych sesji. */ topGym: { gymId: string; name: string; sessions: number } | null; /** Ulubiony sprzęt (serie na ćwiczeniach używających sprzętu). */ topEquipment: { equipmentId: string; name: string; nameEn: string | null; sets: number } | null; /** Ulubione ćwiczenie (sesje z ćwiczeniem; serie z zapisanymi powt.). */ topExercise: { exerciseId: string; name: string; nameEn: string | null; muscle: string; sessions: number; sets: number; } | null; /** Serie i tonaż wg partii pierwotnej ćwiczenia (malejąco). */ muscles: { muscle: string; sets: number; volumeKg: number }[]; /** Sesje wg dnia tygodnia (0 = pon … 6 = nd). */ weekday: { dow: number; sessions: number }[]; /** Heatma: sesje dzień (0=pon) × godzina startu; tylko komórki niezerowe. */ heatmap: { day: number; hour: number; count: number }[]; /** Tonaż w 12 ostatnich tygodniach ISO (od poniedziałku, rosnąco) — zawsze all-time. */ weeklyTonnage: { weekStart: string; volumeKg: number }[]; /** Rekordy Epley 1RM (top 5, cała historia): wartość + data sesji z rekordem. */ records: { exerciseId: string; name: string; nameEn: string | null; muscle: string; oneRm: number; date: string; }[]; } function startOfIsoWeek(now: Date): Date { return new Date(now.getFullYear(), now.getMonth(), now.getDate() - ((now.getDay() + 6) % 7)); } /** Stabilny wybór „ulubionego": najwięcej użyć, przy remisie nazwa alfabetycznie (pl). */ function pickTop( counts: Map, ): (T & { count: number }) | null { const list = [...counts.values()]; if (list.length === 0) return null; list.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name, 'pl')); return list[0]; } /** * Czysta agregacja (unit-testowalna): statystyki osobiste użytkownika na podstawie * ukończonych sesji. Zakres (`rangeDays`) tnie karty ulubionych/rozkładów; tonaż * all-time, tonaż tygodniowy i rekordy liczone są zawsze z pełnej historii. */ export function aggregateUserStats( raw: RawStatsSession[], opts: { rangeDays: number | null; now?: Date }, ): UserStats { const now = opts.now ?? new Date(); const rangeStart = opts.rangeDays == null ? null : new Date(now.getTime() - opts.rangeDays * 24 * 3600 * 1000); const inRange = (s: RawStatsSession) => rangeStart == null || new Date(s.startedAt) >= rangeStart; const inRangeSessions = raw.filter(inRange); // --- Karty w zakresie: sesje, serie, tonaż, ulubione, rozkłady --- let sets = 0; let reps = 0; let tonnageKg = 0; let durationSum = 0; let durationCount = 0; const gymCounts = new Map(); const equipmentCounts = new Map< string, { equipmentId: string; name: string; nameEn: string | null; count: number } >(); const exerciseCounts = new Map< string, { exerciseId: string; name: string; nameEn: string | null; muscle: string; sessions: number; sets: number; count: number; } >(); const muscleCounts = new Map(); const weekdayCounts = new Map(); const heatCounts = new Map(); for (const s of inRangeSessions) { if (s.endedAt) { const min = (new Date(s.endedAt).getTime() - new Date(s.startedAt).getTime()) / 60000; if (min >= 0) { durationSum += min; durationCount += 1; } } if (s.gym) { const cur = gymCounts.get(s.gym.id) ?? { gymId: s.gym.id, name: s.gym.name, count: 0 }; cur.count += 1; gymCounts.set(s.gym.id, cur); } const start = new Date(s.startedAt); const dow = (start.getDay() + 6) % 7; weekdayCounts.set(dow, (weekdayCounts.get(dow) ?? 0) + 1); const heatKey = `${dow}:${start.getHours()}`; heatCounts.set(heatKey, (heatCounts.get(heatKey) ?? 0) + 1); for (const ex of s.exercises) { const exSets = ex.sets.filter(isCountedSet).length; if (exSets === 0) continue; const entry = exerciseCounts.get(ex.exerciseId) ?? { exerciseId: ex.exerciseId, name: ex.name, nameEn: ex.nameEn, muscle: ex.muscle, sessions: 0, sets: 0, count: 0, }; entry.sessions += 1; entry.sets += exSets; entry.count += exSets; exerciseCounts.set(ex.exerciseId, entry); const muscle = muscleCounts.get(ex.muscle) ?? { muscle: ex.muscle, sets: 0, volumeKg: 0 }; for (const st of ex.sets) { if (!isCountedSet(st)) continue; sets += 1; reps += st.reps!; muscle.sets += 1; const load = effectiveLoadKg(st, s.bodyKg); if (load != null) { const v = load * st.reps!; tonnageKg += v; muscle.volumeKg += v; } } muscleCounts.set(ex.muscle, muscle); for (const eq of ex.equipment) { const cur = equipmentCounts.get(eq.id) ?? { equipmentId: eq.id, name: eq.name, nameEn: eq.nameEn, count: 0, }; cur.count += exSets; equipmentCounts.set(eq.id, cur); } } } const topGymEntry = pickTop(gymCounts); const topEquipmentEntry = pickTop(equipmentCounts); const topExerciseEntry = pickTop(exerciseCounts); // --- All-time: tonaż życiowy, tonaż tygodniowy (12 tygodni), rekordy Epley --- let tonnageAllTimeKg = 0; const week0 = startOfIsoWeek(now); const weeklyBuckets = new Array(12).fill(0); const recordsByExercise = new Map< string, { exerciseId: string; name: string; nameEn: string | null; muscle: string; oneRm: number; date: string; } >(); for (const s of raw) { for (const ex of s.exercises) { for (const st of ex.sets) { if (!isCountedSet(st)) continue; const load = effectiveLoadKg(st, s.bodyKg); if (load == null) continue; const v = load * st.reps!; tonnageAllTimeKg += v; const wIdx = Math.floor( (week0.getTime() - startOfWeekOf(new Date(s.startedAt)).getTime()) / (7 * 24 * 3600 * 1000), ); if (wIdx >= 0 && wIdx < 12) weeklyBuckets[11 - wIdx] += v; const epley = epleyOneRm(load, st.reps!); const cur = recordsByExercise.get(ex.exerciseId); if (!cur || epley > cur.oneRm) { recordsByExercise.set(ex.exerciseId, { exerciseId: ex.exerciseId, name: ex.name, nameEn: ex.nameEn, muscle: ex.muscle, oneRm: epley, date: s.startedAt, }); } } } } const weeklyTonnage = Array.from({ length: 12 }, (_, i) => { const wStart = new Date(week0); wStart.setDate(week0.getDate() - (11 - i) * 7); return { weekStart: wStart.toISOString(), volumeKg: Math.round(weeklyBuckets[i]) }; }); const records = [...recordsByExercise.values()] .sort((a, b) => b.oneRm - a.oneRm || a.name.localeCompare(b.name, 'pl')) .slice(0, 5) .map((r) => ({ ...r, oneRm: Math.round(r.oneRm * 10) / 10 })); return { rangeDays: opts.rangeDays, sessions: { count: inRangeSessions.length, sets, reps, avgMinutes: durationCount > 0 ? Math.round(durationSum / durationCount) : null, }, tonnageKg: Math.round(tonnageKg), tonnageAllTimeKg: Math.round(tonnageAllTimeKg), topGym: topGymEntry ? { gymId: topGymEntry.gymId, name: topGymEntry.name, sessions: topGymEntry.count } : null, topEquipment: topEquipmentEntry ? { equipmentId: topEquipmentEntry.equipmentId, name: topEquipmentEntry.name, nameEn: topEquipmentEntry.nameEn, sets: topEquipmentEntry.count, } : null, topExercise: topExerciseEntry ? { exerciseId: topExerciseEntry.exerciseId, name: topExerciseEntry.name, nameEn: topExerciseEntry.nameEn, muscle: topExerciseEntry.muscle, sessions: topExerciseEntry.sessions, sets: topExerciseEntry.sets, } : null, muscles: [...muscleCounts.values()].sort( (a, b) => b.sets - a.sets || a.muscle.localeCompare(b.muscle, 'pl'), ), weekday: Array.from({ length: 7 }, (_, dow) => ({ dow, sessions: weekdayCounts.get(dow) ?? 0, })), heatmap: [...heatCounts.entries()] .map(([key, count]) => { const [day, hour] = key.split(':').map(Number); return { day, hour, count }; }) .sort((a, b) => a.day - b.day || a.hour - b.hour), weeklyTonnage, records, }; } /** Poniedziałek tygodnia zawierającego datę (godz. 0:00, czas lokalny kontenera). */ function startOfWeekOf(d: Date): Date { return new Date(d.getFullYear(), d.getMonth(), d.getDate() - ((d.getDay() + 6) % 7)); } /** * Statystyki osobiste (GET /me/stats): wszystkie ukończono sesje użytkownika * (bez usuniętych dni, usuniętych/ukrytych ćwiczeń i usuniętych serii) + * liczniki planów; agregacja w czystej funkcji `aggregateUserStats`. */ export async function getUserStats(prisma: PrismaClient, userId: string, rangeDays: number | null) { const [sessions, weights, completedPlans, abandonedPlans, daysCompleted, daysSkipped] = await Promise.all([ prisma.trainingSession.findMany({ where: { status: 'COMPLETED', day: { removedAt: null, week: { plan: { userId } } }, }, orderBy: { startedAt: 'asc' }, include: { day: { select: { week: { select: { plan: { select: { gymId: true, gym: { select: { name: true } } } } }, }, }, }, exercises: { where: { removed: false, hidden: false }, include: { exercise: { select: { id: true, name: true, nameEn: true, primaryMuscle: true, equipment: { select: { id: true, name: true, nameEn: true } }, }, }, sets: { where: { removed: false }, include: { planSet: { select: { loadKg: true } } }, }, }, }, }, }), // Reguła masy ciała identyczna jak w historii i postępach ćwiczeń. prisma.bodyMeasurement.findMany({ where: { userId }, orderBy: { date: 'asc' }, select: { value: true, date: true }, }), prisma.trainingPlan.count({ where: { userId, status: 'COMPLETED' } }), prisma.trainingPlan.count({ where: { userId, status: 'ABANDONED' } }), prisma.planDay.count({ where: { removedAt: null, status: 'COMPLETED', week: { plan: { userId } } }, }), prisma.planDay.count({ where: { removedAt: null, status: 'SKIPPED', week: { plan: { userId } } }, }), ]); const raw: RawStatsSession[] = sessions.map((s) => ({ startedAt: s.startedAt.toISOString(), endedAt: s.endedAt ? s.endedAt.toISOString() : null, gym: s.day.week.plan.gymId && s.day.week.plan.gym ? { id: s.day.week.plan.gymId, name: s.day.week.plan.gym.name } : null, bodyKg: latestWeightAtOrBefore(weights, s.startedAt), exercises: s.exercises.map((e) => ({ exerciseId: e.exercise.id, name: e.exercise.name, nameEn: e.exercise.nameEn, muscle: e.exercise.primaryMuscle, equipment: e.exercise.equipment, sets: e.sets.map((st) => ({ reps: st.reps, loadKg: st.planSet?.loadKg ?? null })), })), })); return { ...aggregateUserStats(raw, { rangeDays }), plans: { completed: completedPlans, abandoned: abandonedPlans, daysCompleted, daysSkipped }, }; }