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

138 lines
4.5 KiB
TypeScript

import type { PrismaClient } from '@prisma/client';
import { getKillstreak } from './killstreak.js';
export async function getDashboard(prisma: PrismaClient, userId: string) {
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
});
// 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;
date: string;
exercises: { name: string; muscle: string }[];
} | null = null;
let progress: { completed: number; total: number; percent: number } | null = null;
let extra: { sets: number } | null = null;
let missing: { sets: number } | null = null;
// Historia — globalna (ponad wszystkimi planami), w kontrze do progress/extra/missing,
// które dotyczą wyłącznie aktywnego planu.
const completedSessionWhere = {
status: 'COMPLETED' as const,
day: { week: { plan: { userId } } },
};
const [completedPlans, historySessions, historySets] = await Promise.all([
prisma.trainingPlan.count({ where: { userId, status: 'COMPLETED' } }),
prisma.trainingSession.count({ where: completedSessionWhere }),
prisma.sessionSet.count({
where: {
reps: { not: null },
exercise: { removed: false, hidden: false, session: completedSessionWhere },
},
}),
]);
const history = {
completedPlans,
sessions: historySessions,
sets: historySets,
};
if (activePlan) {
const days = await prisma.planDay.findMany({
where: { week: { planId: activePlan.id } },
include: {
exercises: { include: { exercise: { select: { name: true, primaryMuscle: true } } } },
},
});
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const upcoming = days
.filter((d) => d.status === 'PLANNED' && d.date && d.date >= startOfToday)
.sort((a, b) => a.date!.getTime() - b.date!.getTime())[0];
if (upcoming) {
nextTraining = {
dayId: upcoming.id,
date: upcoming.date!.toISOString(),
exercises: upcoming.exercises.map((e) => ({
name: e.exercise.name,
muscle: e.exercise.primaryMuscle,
})),
};
}
const total = days.length;
const done = days.filter((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED').length;
progress = {
completed: done,
total,
percent: total > 0 ? Math.round((done / total) * 100) : 0,
};
// Extra = sets performed beyond the plan (planSetId = null) in completed sessions:
// sets of exercises added beyond the plan + additional sets of planned exercises.
const extraSets = await prisma.sessionSet.count({
where: {
reps: { not: null },
planSetId: null,
exercise: {
removed: false,
hidden: false,
session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
},
},
});
extra = { sets: extraSets };
// Missing = planned sets left undone in completed sessions
// (planned set count minus planned sets with recorded reps).
// 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 } } },
},
},
});
missing = { sets: plannedSetCount - donePlannedSetCount };
}
return {
killstreak,
history,
nextTraining,
progress,
extra,
missing,
activePlan: activePlan
? { id: activePlan.id, title: activePlan.title, startDate: activePlan.startDate }
: null,
};
}