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

677 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { isPrismaNotFound } from '../lib/prisma.js';
import { getKillstreak } from './killstreak.js';
import { getDashboard } from './dashboard.js';
import { getHistory } from './me.js';
import { getCalendar } from './calendar.js';
export const INVITATION_TTL_DAYS = 7;
export const MAX_PENDING_INVITATIONS = 10;
export type TraineeFlag = 'streak_reset' | 'no_session_7d' | 'high_deficit';
/**
* Attention flags for a trainee (pure — unit-testable):
* - streak_reset: killstreak is 0 although the plan already has resolved days,
* - no_session_7d: no completed session in the last 7 days (or ever),
* - high_deficit: more than 30% of planned sets left undone.
*/
export function computeFlags(args: {
hasActivePlan: boolean;
killstreak: number;
resolvedDays: number;
lastSessionAt: Date | null;
plannedSetCount: number;
donePlannedSetCount: number;
now?: Date;
}): TraineeFlag[] {
if (!args.hasActivePlan) return [];
const flags: TraineeFlag[] = [];
if (args.killstreak === 0 && args.resolvedDays > 0) flags.push('streak_reset');
const weekAgo = new Date((args.now ?? new Date()).getTime() - 7 * 24 * 60 * 60 * 1000);
if (!args.lastSessionAt || args.lastSessionAt < weekAgo) flags.push('no_session_7d');
if (
args.plannedSetCount > 0 &&
(args.plannedSetCount - args.donePlannedSetCount) / args.plannedSetCount > 0.3
) {
flags.push('high_deficit');
}
return flags;
}
export interface TraineeMetrics {
activePlan: {
id: string;
title: string;
progress: { completed: number; total: number; percent: number };
} | null;
killstreak: number;
lastSessionAt: string | null;
flags: TraineeFlag[];
}
/**
* Per-trainee metrics for the trainer's list/detail: active plan progress,
* killstreak, last completed session and attention flags.
*/
export async function computeTraineeMetrics(
prisma: PrismaClient,
userId: string,
): Promise<TraineeMetrics> {
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
select: {
id: true,
title: true,
weeks: { select: { days: { select: { status: true } } } },
},
});
const killstreak = activePlan ? await getKillstreak(prisma, userId) : 0;
let progress: { completed: number; total: number; percent: number } | null = null;
let resolvedDays = 0;
if (activePlan) {
const days = activePlan.weeks.flatMap((w) => w.days);
const total = days.length;
const completed = days.filter((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED').length;
resolvedDays = completed;
progress = {
completed: completed,
total,
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
};
}
const lastSession = await prisma.trainingSession.findFirst({
where: { status: 'COMPLETED', day: { week: { plan: { userId } } } },
orderBy: { startedAt: 'desc' },
select: { startedAt: true },
});
let flags: TraineeFlag[] = [];
if (activePlan) {
const [plannedSetCount, donePlannedSetCount] = await Promise.all([
prisma.planSet.count({ where: { exercise: { day: { week: { planId: activePlan.id } } } } }),
prisma.sessionSet.count({
where: {
reps: { not: null },
planSetId: { not: null },
exercise: {
removed: false,
hidden: false,
session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
},
},
}),
]);
flags = computeFlags({
hasActivePlan: true,
killstreak,
resolvedDays,
lastSessionAt: lastSession ? lastSession.startedAt : null,
plannedSetCount,
donePlannedSetCount,
});
}
return {
activePlan: activePlan
? { id: activePlan.id, title: activePlan.title, progress: progress! }
: null,
killstreak,
lastSessionAt: lastSession ? lastSession.startedAt.toISOString() : null,
flags,
};
}
async function hasTrainerRole(prisma: PrismaClient, userId: string): Promise<boolean> {
const membership = await prisma.gymMembership.findFirst({
where: { userId, roles: { has: 'TRAINER' } },
});
return !!membership;
}
export async function isTrainer(prisma: PrismaClient, userId: string): Promise<boolean> {
return hasTrainerRole(prisma, userId);
}
export interface UserSearchResult {
id: string;
firstName: string | null;
lastName: string | null;
nickname: string | null;
email: string;
phone: string | null;
gyms: { id: string; name: string }[];
}
/**
* Search users by first + last name (case-insensitive, partial match).
* Excludes the trainer and their current/pending trainees.
*/
export async function searchUsers(
prisma: PrismaClient,
trainerId: string,
firstName: string,
lastName: string,
) {
const relations = await prisma.coaching.findMany({
where: { trainerId, status: { in: ['ACTIVE', 'PENDING'] } },
select: { userId: true },
});
const excludeIds = new Set(relations.map((r) => r.userId));
excludeIds.add(trainerId);
const users = await prisma.user.findMany({
where: {
firstName: { contains: firstName, mode: 'insensitive' },
lastName: { contains: lastName, mode: 'insensitive' },
NOT: { id: { in: [...excludeIds] } },
},
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
email: true,
phone: true,
memberships: { select: { gym: { select: { id: true, name: true } } } },
},
take: 20,
orderBy: { createdAt: 'asc' },
});
return {
users: users.map((u) => ({
id: u.id,
firstName: u.firstName,
lastName: u.lastName,
nickname: u.nickname,
email: u.email,
phone: u.phone,
gyms: u.memberships.map((m) => m.gym),
})),
};
}
/**
* Send a coaching invitation. At least one party must hold the TRAINER role:
* - only the target is a trainer -> the target becomes the trainer (trainee invites trainer),
* - otherwise the requester is the trainer (trainer invites a trainee).
*/
export async function sendInvitation(prisma: PrismaClient, requesterId: string, targetId: string) {
if (targetId === requesterId) throw badRequest('Cannot invite yourself');
const target = await prisma.user.findUnique({ where: { id: targetId } });
if (!target) throw notFound('User not found');
const [requesterIsTrainer, targetIsTrainer] = await Promise.all([
hasTrainerRole(prisma, requesterId),
hasTrainerRole(prisma, targetId),
]);
if (!requesterIsTrainer && !targetIsTrainer) throw badRequest('Trainer role required');
const trainerId = targetIsTrainer && !requesterIsTrainer ? targetId : requesterId;
const userId = trainerId === requesterId ? targetId : requesterId;
const existing = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
});
if (existing && (existing.status === 'PENDING' || existing.status === 'ACTIVE')) {
throw conflict('Invitation already exists');
}
for (const accountId of [requesterId, targetId]) {
const pending = await prisma.coaching.count({
where: { status: 'PENDING', OR: [{ trainerId: accountId }, { userId: accountId }] },
});
if (pending >= MAX_PENDING_INVITATIONS) throw conflict('Too many pending invitations');
}
// Para (trainerId, userId) jest unikalna w bazie — po DECLINED/ARCHIVED
// aktualizujemy istniejący wiersz (te sama zasada co przy zaproszeniach do siłowni).
const now = new Date();
const expiresAt = new Date(now.getTime() + INVITATION_TTL_DAYS * 24 * 60 * 60 * 1000);
const coaching = existing
? await prisma.coaching.update({
where: { id: existing.id },
data: { status: 'PENDING', invitedBy: requesterId, invitedAt: now, expiresAt, note: null },
})
: await prisma.coaching.create({
data: { trainerId, userId, invitedBy: requesterId, expiresAt },
});
return { coaching, targetEmail: target.email };
}
interface PendingInvitation {
id: string;
trainerId: string;
userId: string;
invitedBy: string;
invitedAt: Date;
expiresAt: Date;
}
function otherPartyId(c: PendingInvitation, me: string): string {
return c.invitedBy === me ? (c.trainerId === me ? c.userId : c.trainerId) : c.invitedBy;
}
/** Pending (not expired) invitations involving the user — sent and received. */
export async function listInvitations(prisma: PrismaClient, userId: string) {
const now = new Date();
const coachings = await prisma.coaching.findMany({
where: {
status: 'PENDING',
expiresAt: { gt: now },
OR: [{ trainerId: userId }, { userId: userId }],
},
orderBy: { invitedAt: 'desc' },
});
const otherIds = [...new Set(coachings.map((c) => otherPartyId(c, userId)))];
const users = await prisma.user.findMany({
where: { id: { in: otherIds } },
select: { id: true, firstName: true, lastName: true, nickname: true, email: true, phone: true },
});
return {
invitations: coachings.map((c) => {
const otherId = otherPartyId(c, userId);
const u = users.find((x) => x.id === otherId);
return {
id: c.id,
direction: c.invitedBy === userId ? ('sent' as const) : ('received' as const),
other: u
? {
id: u.id,
firstName: u.firstName,
lastName: u.lastName,
nickname: u.nickname,
email: u.email,
phone: u.phone,
}
: null,
invitedAt: c.invitedAt.toISOString(),
expiresAt: c.expiresAt.toISOString(),
};
}),
};
}
async function loadPendingInvitation(prisma: PrismaClient, coachingId: string) {
const coaching = await prisma.coaching.findUnique({ where: { id: coachingId } });
if (!coaching) throw notFound('Invitation not found');
if (coaching.status !== 'PENDING') throw conflict('Invitation is not pending');
if (coaching.expiresAt <= new Date()) throw new AppError(410, 'GONE', 'Invitation expired');
return coaching;
}
/** Only the invited side of the pair (the party that did not send it) may respond. */
function assertInvitedParty(
coaching: { invitedBy: string; trainerId: string; userId: string },
userId: string,
) {
if (coaching.invitedBy === userId) throw forbidden('You sent this invitation');
if (coaching.trainerId !== userId && coaching.userId !== userId) {
throw forbidden('You are not a party to this invitation');
}
}
/** Accept an invitation (invited party only). */
export async function acceptInvitation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await loadPendingInvitation(prisma, coachingId);
assertInvitedParty(coaching, userId);
const updated = await respondToInvitation(prisma, coachingId, 'ACTIVE');
return { coaching: updated };
}
/** Decline an invitation (invited party only). */
export async function declineInvitation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await loadPendingInvitation(prisma, coachingId);
assertInvitedParty(coaching, userId);
const updated = await respondToInvitation(prisma, coachingId, 'DECLINED');
return { coaching: updated };
}
/**
* Zapis odpowiedzi na zaproszenie. Wiersz mógł zostać wycofany między
* sprawdzeniem a zapisem — wtedy zaproszenie nie jest już oczekujące (409),
* nie surowy błąd bazy (P2025).
*/
async function respondToInvitation(
prisma: PrismaClient,
coachingId: string,
status: 'ACTIVE' | 'DECLINED',
) {
try {
return await prisma.coaching.update({ where: { id: coachingId }, data: { status } });
} catch (e) {
if (isPrismaNotFound(e)) throw conflict('Invitation is not pending');
throw e;
}
}
/** Withdraw a pending invitation (sender only) — removes the relation. */
export async function withdrawInvitation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await prisma.coaching.findUnique({ where: { id: coachingId } });
if (!coaching) throw notFound('Invitation not found');
if (coaching.status !== 'PENDING') throw conflict('Invitation is not pending');
if (coaching.invitedBy !== userId) throw forbidden('Only the sender can withdraw the invitation');
try {
await prisma.coaching.delete({ where: { id: coachingId } });
} catch (e) {
// wyścig z akceptacją/drugim wycofaniem — wiersza już nie ma
if (isPrismaNotFound(e)) throw notFound('Invitation not found');
throw e;
}
}
/** Active trainees of the trainer (global list, optional gym filter by trainee membership). */
export async function listTrainees(prisma: PrismaClient, trainerId: string, gymId?: string) {
const coachings = await prisma.coaching.findMany({
where: {
trainerId,
status: 'ACTIVE',
...(gymId ? { user: { memberships: { some: { gymId } } } } : {}),
},
include: {
user: {
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
memberships: { select: { gym: { select: { id: true, name: true } } } },
},
},
},
orderBy: { createdAt: 'asc' },
});
const trainees = await Promise.all(
coachings.map(async (c) => {
const metrics = await computeTraineeMetrics(prisma, c.user.id);
return {
user: {
id: c.user.id,
firstName: c.user.firstName,
lastName: c.user.lastName,
nickname: c.user.nickname,
},
gyms: c.user.memberships.map((m) => m.gym),
...metrics,
};
}),
);
return { trainees };
}
/** The trainer must have an ACTIVE coaching relation with the user. */
export async function assertActiveTrainee(prisma: PrismaClient, trainerId: string, userId: string) {
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
});
if (!coaching || coaching.status !== 'ACTIVE') throw notFound('Trainee not found');
return coaching;
}
/**
* Restricted trainee detail: training metrics only (no body parameters, no profile).
*/
export async function getTraineeDetail(prisma: PrismaClient, trainerId: string, userId: string) {
const coaching = await assertActiveTrainee(prisma, trainerId, userId);
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
socialMedia: true,
// equipment = do limitowania ćwiczeń w edytorze planu podopiecznego
memberships: {
select: {
gym: { select: { id: true, name: true, equipment: { include: { equipment: true } } } },
},
},
},
});
if (!user) throw notFound('User not found');
const [dashboard, metrics] = await Promise.all([
getDashboard(prisma, userId),
computeTraineeMetrics(prisma, userId),
]);
return {
coachingId: coaching.id,
user: {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
nickname: user.nickname,
},
socialMedia: user.socialMedia,
gyms: user.memberships.map((m) => m.gym),
activePlan: dashboard.activePlan,
progress: dashboard.progress,
killstreak: dashboard.killstreak,
nextTraining: dashboard.nextTraining,
extra: dashboard.extra,
missing: dashboard.missing,
lastSessionAt: metrics.lastSessionAt,
flags: metrics.flags,
};
}
/** Trainee session history with plan vs. actual (restricted: training data only). */
export async function getTraineeHistory(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
return getHistory(prisma, userId);
}
export interface MuscleReport {
muscle: string;
planned: { sets: number; reps: number };
actual: { sets: number; reps: number };
extra: { sets: number };
missing: { sets: number };
completionPct: number;
/** Weekly FocusArea range scaled to the plan duration (null when the muscle has no range). */
recommendedRange: { setsMin: number; setsMax: number } | null;
outOfRange: boolean;
}
export interface TraineeReport {
plan: { id: string; title: string; startDate: string | null } | null;
muscles: MuscleReport[];
days: { date: string; status: 'PLANNED' | 'COMPLETED' | 'SKIPPED'; moved: boolean }[];
}
/**
* Plan vs. actual per muscle group (decision 20) with the recommended volume
* range (decision 13) and plan days for the discipline heatmap.
*/
export async function getTraineeReport(
prisma: PrismaClient,
trainerId: string,
userId: string,
): Promise<TraineeReport> {
await assertActiveTrainee(prisma, trainerId, userId);
const plan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
select: {
id: true,
title: true,
startDate: true,
weeksCount: true,
weeks: {
select: {
days: {
select: {
id: true,
date: true,
status: true,
moveLog: { select: { id: true } },
exercises: {
select: {
exercise: { select: { primaryMuscle: true } },
sets: { select: { reps: true } },
},
},
},
},
},
},
},
});
if (!plan) return { plan: null, muscles: [], days: [] };
const focusAreas = await prisma.focusArea.findMany({
select: { muscle: true, setsMin: true, setsMax: true },
});
const rangeByMuscle = new Map(focusAreas.map((f) => [f.muscle, f]));
const planned = new Map<string, { sets: number; reps: number }>();
const dayIds: string[] = [];
for (const week of plan.weeks) {
for (const day of week.days) {
dayIds.push(day.id);
for (const pe of day.exercises) {
const acc = planned.get(pe.exercise.primaryMuscle) ?? { sets: 0, reps: 0 };
for (const s of pe.sets) {
acc.sets += 1;
if (s.reps != null) acc.reps += s.reps;
}
planned.set(pe.exercise.primaryMuscle, acc);
}
}
}
const sessions = await prisma.trainingSession.findMany({
where: { status: 'COMPLETED', dayId: { in: dayIds } },
select: {
exercises: {
select: {
removed: true,
hidden: true,
exercise: { select: { primaryMuscle: true } },
sets: { select: { reps: true, planSetId: true } },
},
},
},
});
const actual = new Map<string, { sets: number; reps: number }>();
const extra = new Map<string, number>();
for (const session of sessions) {
for (const ex of session.exercises) {
if (ex.removed || ex.hidden) continue;
const muscle = ex.exercise.primaryMuscle;
for (const st of ex.sets) {
if (st.reps == null) continue;
if (st.planSetId != null) {
const acc = actual.get(muscle) ?? { sets: 0, reps: 0 };
acc.sets += 1;
acc.reps += st.reps;
actual.set(muscle, acc);
} else {
extra.set(muscle, (extra.get(muscle) ?? 0) + 1);
}
}
}
}
const muscles: MuscleReport[] = [...planned.entries()].map(([muscle, p]) => {
const a = actual.get(muscle) ?? { sets: 0, reps: 0 };
const e = extra.get(muscle) ?? 0;
const missing = Math.max(0, p.sets - a.sets);
const completionPct = p.sets > 0 ? Math.min(100, Math.round((a.sets / p.sets) * 100)) : 0;
const fa = rangeByMuscle.get(muscle);
const recommendedRange =
fa && fa.setsMin != null && fa.setsMax != null
? { setsMin: fa.setsMin * plan.weeksCount, setsMax: fa.setsMax * plan.weeksCount }
: null;
const outOfRange =
recommendedRange != null &&
(a.sets < recommendedRange.setsMin || a.sets > recommendedRange.setsMax);
return {
muscle,
planned: p,
actual: a,
extra: { sets: e },
missing: { sets: missing },
completionPct,
recommendedRange,
outOfRange,
};
});
const days = plan.weeks
.flatMap((w) => w.days)
.filter((d) => d.date != null)
.map((d) => ({
date: d.date!.toISOString(),
status: d.status,
moved: d.moveLog.length > 0,
}));
return {
plan: {
id: plan.id,
title: plan.title,
startDate: plan.startDate ? plan.startDate.toISOString() : null,
},
muscles,
days,
};
}
/** Moved-day log (DayMove) for the trainee's active plan (decision 21). */
export async function getTraineeMoves(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
const plan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
select: {
weeks: {
select: {
days: {
select: {
date: true,
moveLog: {
select: { dayId: true, fromDate: true, toDate: true, reason: true, movedAt: true },
orderBy: { movedAt: 'desc' },
},
},
},
},
},
},
});
const moves = plan
? plan.weeks.flatMap((w) =>
w.days.flatMap((d) =>
d.moveLog.map((m) => ({
dayId: m.dayId,
date: d.date ? d.date.toISOString() : null,
fromDate: m.fromDate.toISOString(),
toDate: m.toDate.toISOString(),
reason: m.reason,
movedAt: m.movedAt.toISOString(),
})),
),
)
: [];
return { moves };
}
/** Trainee calendar (days of the trainee's active plan in a month) for the trainer. */
export async function getTraineeCalendar(
prisma: PrismaClient,
trainerId: string,
userId: string,
month?: string,
) {
await assertActiveTrainee(prisma, trainerId, userId);
return getCalendar(prisma, userId, month);
}
/** Archive the trainer–trainee relation. */
export async function archiveTrainee(prisma: PrismaClient, trainerId: string, userId: string) {
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
});
if (!coaching || coaching.status !== 'ACTIVE') throw notFound('Trainee not found');
await prisma.coaching.update({ where: { id: coaching.id }, data: { status: 'ARCHIVED' } });
}