Statystyki: podstrona Statystyki profilu + tablica silowni REAL z opt-in nicku

Profil: GET /me/stats (ulubiona silownia/sprzet/cwiczenie, partie ciala, heatma, tonaz 12 tyg., rekordy Epley top5) + widok /profile/stats i podsumowanie na przegladzie. Tablica: GET /gyms/:id/board + PATCH /gyms/:id/stats-consent (GymMembership.statsOptIn, migracja gym_membership_stats_opt_in) — anonimowe agregaty, ranking i rekordy 1RM z atrybucja nicka tylko po zgodzie; /gyms/:id/board + pelnoekranowy tryb TV /gyms/:id/board/tv (TvShell, auto-refetch co 5 min); kafelek na GymDetail. Wspolne: api lib/strengthStats (Epley/efektywne obciazenie), app lib/stats-equiv + components/stats (MuscleSplit, WeeklyTonnageChart), storey stats-range/board-range. Testy: api 322 unit + 12 integracji (board, me-stats); app 285 unit; e2e gym-board 4, profile-stats 3.
This commit is contained in:
tisachi
2026-10-29 17:47:05 +01:00
parent f0b24b4631
commit 389b8e30e8
38 changed files with 4160 additions and 20 deletions

View File

@@ -1,4 +1,5 @@
import type { PrismaClient } from '@prisma/client';
import { epleyOneRm, effectiveLoadKg } from '../lib/strengthStats.js';
import { assertActiveTrainee } from './trainer.js';
export interface ExerciseProgressPoint {
@@ -38,15 +39,6 @@ export interface RawSession {
exercises: RawExercise[];
}
/**
* Seria bez zaplanowanego obciążenia (loadKg = null/0) to trening z masą ciała:
* efektywne obciążenie = ostatnia podana waga z profilu (bodyKg) albo null,
* gdy pomiaru brak — wtedy seria nie wchodzi do 1RM/objętości.
*/
function effectiveLoadKg(st: RawSet, s: RawSession): number | null {
return st.loadKg ?? s.bodyKg ?? null;
}
/**
* Ostatnia waga (kg) z listy pomiarów (rosnąco) nie później niż dana sesji.
* Eksportowane — historia sesji (me.getHistory) używa tej samej reguły.
@@ -83,9 +75,9 @@ export function aggregateExerciseProgress(sessions: RawSession[]): ExerciseProgr
if (st.reps == null) continue;
reps += st.reps;
sets += 1;
const loadKg = effectiveLoadKg(st, s);
const loadKg = effectiveLoadKg(st, s.bodyKg ?? null);
if (loadKg != null) {
const epley = loadKg * (1 + st.reps / 30);
const epley = epleyOneRm(loadKg, st.reps);
if (oneRm == null || epley > oneRm) oneRm = epley;
volumeKg = (volumeKg ?? 0) + loadKg * st.reps;
}
@@ -172,9 +164,9 @@ export function latestExerciseResults(sessions: RawSession[]): LatestExerciseRes
let oneRm: number | null = null;
for (const st of v.sets) {
if (st.reps == null) continue;
const loadKg = st.loadKg ?? v.bodyKg;
const loadKg = effectiveLoadKg(st, v.bodyKg);
if (loadKg == null) continue;
const epley = loadKg * (1 + st.reps / 30);
const epley = epleyOneRm(loadKg, st.reps);
if (oneRm == null || epley > oneRm) oneRm = epley;
}
return {

View File

@@ -1,4 +1,5 @@
export * from './gyms/core.js';
export * from './gyms/board.js';
export * from './gyms/exceptions.js';
export * from './gyms/photos.js';
export * from './gyms/equipmentPhotos.js';

View File

@@ -0,0 +1,368 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, forbidden, notFound } from '../../lib/errors.js';
import { effectiveLoadKg, epleyOneRm, isCountedSet } from '../../lib/strengthStats.js';
import { isSessionEffective } from '../killstreak.js';
import { latestWeightAtOrBefore } from '../exerciseProgress.js';
export interface BoardMember {
userId: string;
statsOptIn: boolean;
status: 'ACTIVE' | 'SUSPENDED' | 'BANNED';
nickname: string | null;
firstName: string | null;
lastName: string | null;
}
export interface BoardSetRaw {
reps: number | null;
loadKg: number | null;
}
export interface BoardExerciseRaw {
exerciseId: string;
name: string;
nameEn: string | null;
muscle: string;
sets: BoardSetRaw[];
}
export interface BoardSessionRaw {
userId: string;
dayId: string;
/** ISO start sesji. */
startedAt: string;
/** Skuteczność wg definicji killstreaka (isSessionEffective). */
effective: boolean;
/** Masa ciała (kg) w dacie sesji — seria bez obciążenia = masa ciała. */
bodyKg: number | null;
exercises: BoardExerciseRaw[];
}
export interface GymBoardRankingRow {
userId: string;
nickname: string | null;
firstName: string | null;
lastName: string | null;
/** Skuteczne ukończone sesje w zakresie (metryka rankingu). */
sessions: number;
/** Tonaż w zakresie — dane wtórne w wierszu. */
tonnageKg: number;
/** Dni ze skuteczną sesją w zakresie. */
days: number;
}
export interface GymBoardRecord {
exerciseId: string;
name: string;
nameEn: string | null;
muscle: string;
oneRm: number;
date: string;
/** Atrybucja tylko dla członków z opt-in i kontem ACTIVE; inaczej null → „anonim". */
author: { nickname: string | null; firstName: string | null; lastName: string | null } | null;
}
export interface GymBoardData {
rangeDays: number;
ranking: GymBoardRankingRow[];
aggregate: {
tonnageKg: number;
sessions: number;
uniqueExercisers: number;
muscles: { muscle: string; sets: number; volumeKg: number }[];
};
records: GymBoardRecord[];
}
/** Reguła nazwy jak `displayName` w `app/src/lib/format.ts` — tylko do sortowania po stronie API. */
function displayNameOf(m: Pick<BoardMember, 'nickname' | 'firstName' | 'lastName'>): string {
return m.nickname || [m.firstName, m.lastName].filter(Boolean).join(' ');
}
/**
* Czysta agregacja tablicy siłowni (unit-testowalna). Zakres (`rangeDays`) tnie
* ranking i agregaty; rekordy Epley liczone są zawsze z pełnej historii.
* Agregaty liczą WSZYSTKIE sesje przypisane do siłowni (także osoby bez
* członkostwa — fakt przeszły); ranking i atrybucja rekordów tylko członków
* z `statsOptIn` i kontem `ACTIVE`.
*/
export function aggregateGymBoard(
raw: BoardSessionRaw[],
opts: { rangeDays: number; members: BoardMember[]; now?: Date },
): GymBoardData {
const now = opts.now ?? new Date();
const rangeStart = new Date(now.getTime() - opts.rangeDays * 24 * 60 * 60 * 1000);
const inRange = (s: BoardSessionRaw) => new Date(s.startedAt) >= rangeStart;
const memberByUser = new Map(opts.members.map((m) => [m.userId, m]));
const visibleAuthor = (userId: string): GymBoardRecord['author'] => {
const m = memberByUser.get(userId);
if (!m || !m.statsOptIn || m.status !== 'ACTIVE') return null;
return { nickname: m.nickname, firstName: m.firstName, lastName: m.lastName };
};
// --- Ranking: wiersze tworzą skuteczne sesje w zakresie (członkowie z opt-in i ACTIVE);
// wtórne tonaż/dni liczone od wszystkich sesji użytkownika w zakresie ---
const effectiveByUser = new Map<string, { sessions: number; dayIds: Set<string> }>();
const tonnageByUser = new Map<string, number>();
// --- Agregaty: wszystkie sesje w zakresie, anonimowo (także nie-członkowie) ---
let aggregateTonnageKg = 0;
let aggregateSessions = 0;
const exercisers = new Set<string>();
const muscleCounts = new Map<string, { muscle: string; sets: number; volumeKg: number }>();
for (const s of raw) {
if (!inRange(s)) continue;
aggregateSessions += 1;
exercisers.add(s.userId);
const member = memberByUser.get(s.userId);
if (s.effective && member != null && member.statsOptIn && member.status === 'ACTIVE') {
const cur = effectiveByUser.get(s.userId) ?? { sessions: 0, dayIds: new Set<string>() };
cur.sessions += 1;
cur.dayIds.add(s.dayId);
effectiveByUser.set(s.userId, cur);
}
for (const ex of s.exercises) {
const muscle = muscleCounts.get(ex.muscle) ?? { muscle: ex.muscle, sets: 0, volumeKg: 0 };
for (const st of ex.sets) {
if (!isCountedSet(st)) continue;
muscle.sets += 1;
const load = effectiveLoadKg(st, s.bodyKg);
if (load != null) {
const v = load * st.reps!;
aggregateTonnageKg += v;
muscle.volumeKg += v;
tonnageByUser.set(s.userId, (tonnageByUser.get(s.userId) ?? 0) + v);
}
}
muscleCounts.set(ex.muscle, muscle);
}
}
const ranking = [...effectiveByUser.entries()]
.filter(([, r]) => r.sessions > 0)
.map(([userId, r]) => {
const m = memberByUser.get(userId)!;
return {
userId,
nickname: m.nickname,
firstName: m.firstName,
lastName: m.lastName,
sessions: r.sessions,
tonnageKg: Math.round(tonnageByUser.get(userId) ?? 0),
days: r.dayIds.size,
};
})
.sort(
(a, b) =>
b.sessions - a.sessions ||
displayNameOf(a).localeCompare(displayNameOf(b), 'pl') ||
a.userId.localeCompare(b.userId),
)
.slice(0, 10);
// --- Rekordy: max Epley per ćwiczenie, cała historia, top 5 ---
const recordsByExercise = new Map<
string,
{
exerciseId: string;
name: string;
nameEn: string | null;
muscle: string;
oneRm: number;
date: string;
userId: 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 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,
userId: s.userId,
});
}
}
}
}
const records: GymBoardRecord[] = [...recordsByExercise.values()]
.sort((a, b) => b.oneRm - a.oneRm || a.name.localeCompare(b.name, 'pl'))
.slice(0, 5)
.map(({ userId, oneRm, ...rec }) => ({
...rec,
oneRm: Math.round(oneRm * 10) / 10,
author: visibleAuthor(userId),
}));
return {
rangeDays: opts.rangeDays,
ranking,
aggregate: {
tonnageKg: Math.round(aggregateTonnageKg),
sessions: aggregateSessions,
uniqueExercisers: exercisers.size,
muscles: [...muscleCounts.values()].sort(
(a, b) => b.sets - a.sets || a.muscle.localeCompare(b.muscle, 'pl'),
),
},
records,
};
}
/** Sesja do oceny skuteczności — kształt zgodny z `isSessionEffective` (killstreak). */
interface SessionForEffectiveness {
exercises: {
hidden: boolean;
removed: boolean;
planExercise: { sets: { id: string }[] } | null;
sets: { planSetId: string | null; reps: number | null }[];
}[];
}
/**
* Tablica statystyk siłowni REAL: anonimowe agregaty (WSZYSCY ćwiczący) +
* ranking i rekordy z atrybucją nicka tylko dla członków, którzy wyrazili
* zgodę (`statsOptIn`). Dostęp: admin LUB członkostwo (dowolna rola);
* 400 dla VIRTUAL; 404 gdy brak siłowni. Zakres tnie ranking/agregaty,
* rekordy są always-all-time.
*/
export async function getGymBoard(
prisma: PrismaClient,
gymId: string,
rangeDays: number,
caller: { userId: string; isAdmin: boolean },
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
select: { id: true, name: true, kind: true },
});
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL') throw badRequest('The stats board is available for real gyms');
let membership: { statsOptIn: boolean } | null = null;
if (!caller.isAdmin) {
membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: caller.userId, gymId } },
select: { statsOptIn: true },
});
if (!membership) throw forbidden('Only gym members can view the stats board');
}
const [sessions, members] = await Promise.all([
prisma.trainingSession.findMany({
where: {
status: 'COMPLETED',
day: { removedAt: null, week: { plan: { gymId } } },
},
orderBy: { startedAt: 'asc' },
include: {
day: { select: { id: true, week: { select: { plan: { select: { userId: true } } } } } },
exercises: {
include: {
exercise: { select: { id: true, name: true, nameEn: true, primaryMuscle: true } },
sets: { include: { planSet: { select: { loadKg: true } } } },
planExercise: { include: { sets: { select: { id: true } } } },
},
},
},
}),
prisma.gymMembership.findMany({
where: { gymId },
include: {
user: { select: { id: true, status: true, nickname: true, firstName: true, lastName: true } },
},
}),
]);
const userIds = [...new Set(sessions.map((s) => s.day.week.plan.userId))];
const weights =
userIds.length > 0
? await prisma.bodyMeasurement.findMany({
where: { userId: { in: userIds } },
orderBy: { date: 'asc' },
select: { userId: true, value: true, date: true },
})
: [];
const weightsByUser = new Map<string, { value: number; date: Date }[]>();
for (const w of weights) {
const list = weightsByUser.get(w.userId) ?? [];
list.push({ value: w.value, date: w.date });
weightsByUser.set(w.userId, list);
}
const raw: BoardSessionRaw[] = sessions.map((s) => {
const userId = s.day.week.plan.userId;
const exercisesForEffectiveness: SessionForEffectiveness = { exercises: s.exercises };
return {
userId,
dayId: s.day.id,
startedAt: s.startedAt.toISOString(),
effective: isSessionEffective(exercisesForEffectiveness),
bodyKg: latestWeightAtOrBefore(weightsByUser.get(userId) ?? [], s.startedAt),
exercises: s.exercises
.filter((e) => !e.removed && !e.hidden)
.map((e) => ({
exerciseId: e.exercise.id,
name: e.exercise.name,
nameEn: e.exercise.nameEn,
muscle: e.exercise.primaryMuscle,
sets: e.sets
.filter((st) => !st.removed)
.map((st) => ({ reps: st.reps, loadKg: st.planSet?.loadKg ?? null })),
})),
};
});
const boardMembers: BoardMember[] = members.map((m) => ({
userId: m.user.id,
statsOptIn: m.statsOptIn,
status: m.user.status,
nickname: m.user.nickname,
firstName: m.user.firstName,
lastName: m.user.lastName,
}));
return {
gym: { id: gym.id, name: gym.name },
myStatsOptIn: membership?.statsOptIn ?? null,
...aggregateGymBoard(raw, { rangeDays, members: boardMembers }),
};
}
/**
* Zgoda na wyświetlanie nicka w rankingu/rekordach tablicy (per siłownia).
* Tylko członek + REAL; 404 gdy brak siłowni; 403 gdy brak członkostwa.
*/
export async function setGymStatsConsent(
prisma: PrismaClient,
gymId: string,
userId: string,
enabled: boolean,
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL') throw badRequest('The stats board is available for real gyms');
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
if (!membership) throw forbidden('Only gym members can change the stats consent');
const updated = await prisma.gymMembership.update({
where: { id: membership.id },
data: { statsOptIn: enabled },
select: { statsOptIn: true },
});
return { statsOptIn: updated.statsOptIn };
}

View File

@@ -0,0 +1,382 @@
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<T extends { name: string }>(
counts: Map<string, T & { count: number }>,
): (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<string, { gymId: string; name: string; count: number }>();
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<string, { muscle: string; sets: number; volumeKg: number }>();
const weekdayCounts = new Map<number, number>();
const heatCounts = new Map<string, number>();
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<number>(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 },
};
}