import type { PrismaClient } from '@prisma/client'; import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js'; import { isPrismaNotFound } from '../lib/prisma.js'; import { ROLE_KEYS } from '../lib/permissions.js'; import { getKillstreak } from './killstreak.js'; import { getDashboard } from './dashboard.js'; import { getHistory } from './me.js'; import { getCalendar } from './calendar.js'; import { aggregateActualByMuscle, aggregatePlannedByMuscle, buildMuscleReports, loadFocusRanges, type MuscleReport, } from './planVolume.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 { const activePlan = await prisma.trainingPlan.findFirst({ where: { userId, status: 'ACTIVE', kind: 'PLAN' }, select: { id: true, title: true, weeks: { select: { days: { where: { removedAt: null }, 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: { removedAt: null, 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 { const grant = await prisma.userRoleGrant.findFirst({ where: { userId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_TRAINER } }, select: { id: true }, }); return !!grant; } /** Sygnatura trainera w konkretnej siłowni (grant GYM_TRAINER). */ async function isTrainerInGym( prisma: PrismaClient, userId: string, gymId: string, ): Promise { const grant = await prisma.userRoleGrant.findFirst({ where: { userId, gymId, role: { key: ROLE_KEYS.GYM_TRAINER } }, select: { id: true }, }); return !!grant; } /** * Gym dla nowej relacji coachingu (faza 2, per-siłownia): kandydaci = siłownie, * w których TRAINER ma grant GYM_TRAINER, a podopieczny jest członkiem. * Jawny `gymId` → musi spełniać oba warunki; bez → dokładnie jeden kandydat. */ async function resolveCoachingGym( prisma: PrismaClient, trainerId: string, traineeId: string, explicitGymId?: string | null, ): Promise { if (explicitGymId) { if (!(await isTrainerInGym(prisma, trainerId, explicitGymId))) throw badRequest('Trainer has no trainer role in this gym'); const member = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId: traineeId, gymId: explicitGymId } }, select: { id: true }, }); if (!member) throw badRequest('Trainee is not a member of this gym'); return explicitGymId; } const grants = await prisma.userRoleGrant.findMany({ where: { userId: trainerId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_TRAINER } }, select: { gymId: true }, }); const gymIds = grants.map((g) => g.gymId).filter((id): id is string => !!id); if (gymIds.length === 0) throw badRequest('Trainer role required'); const memberships = await prisma.gymMembership.findMany({ where: { userId: traineeId, gymId: { in: gymIds } }, select: { gymId: true }, }); const shared = memberships.map((m) => m.gymId); if (shared.length === 0) throw badRequest('Trainer and trainee share no common gym with trainer role'); if (shared.length > 1) throw badRequest('Ambiguous gym; pass gymId'); return shared[0]; } export async function isTrainer(prisma: PrismaClient, userId: string): Promise { 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, gymId?: string | null, ) { 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 coachingGymId = await resolveCoachingGym(prisma, trainerId, userId, gymId); 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, gymId: coachingGymId, }, }) : await prisma.coaching.create({ data: { trainerId, userId, invitedBy: requesterId, expiresAt, gymId: coachingGymId }, }); 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 (optional gym filter by trainee membership). * Relacje per-gym (faza 2) widoczne tylko, gdy trainer nadal ma grant w danym gymie. */ export async function listTrainees(prisma: PrismaClient, trainerId: string, gymId?: string) { const [coachings, trainerGrants] = await Promise.all([ 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' }, }), prisma.userRoleGrant.findMany({ where: { userId: trainerId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_TRAINER } }, select: { gymId: true }, }), ]); const trainerGyms = new Set(trainerGrants.map((g) => g.gymId)); const visible = coachings.filter((c) => !c.gymId || trainerGyms.has(c.gymId)); const trainees = await Promise.all( visible.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 (and, for per-gym * relations since phase 2, the trainer role in that gym). */ 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'); if (coaching.gymId && !(await isTrainerInGym(prisma, trainerId, coaching.gymId))) 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, undefined, trainerId); } export type { MuscleReport }; /** Pojedyncza seria ćwiczenia w raporcie: plan vs. wykonane. */ export interface ExerciseReportSet { /** Numeracja ciągła w obrębie ćwiczenia (chronologicznie po sesjach). */ index: number; planned: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null; } | null; /** null = seria planowa niewykonana (brak zapisanych powtórzeń). */ actual: { reps: number | null; rir: number | null; difficulty: number | null } | null; /** Opcjonalny komentarz trenującego przy serii (widoczny trenerowi). */ note?: string | null; } /** Ćwiczenie zagregowane po wszystkich zakończonych sesjach aktywnego planu. */ export interface ExerciseReport { /** Id ćwiczenia z katalogu — klucz agregacji (nie SessionExercise). */ id: string; name: string; nameEn?: string | null; muscle: string; /** true = ćwiczenie występuje wyłącznie ponad plan (brak odpowiednika w planie). */ isExtra: boolean; sets: ExerciseReportSet[]; } export interface TraineeReport { plan: { id: string; title: string; startDate: string | null } | null; muscles: MuscleReport[]; days: { date: string; status: 'PLANNED' | 'COMPLETED' | 'SKIPPED'; moved: boolean }[]; /** * Szczegóły per ćwiczenie (plan vs. wykonane per seria). Opcjonalne dla * kompatybilności wstecznej — front fallbackuje do pasków per partia. */ exercises?: ExerciseReport[]; } /** * Plan vs. actual per muscle group (decision 20) with the recommended volume * range (decision 13) and plan days for the discipline heatmap; plus * exercise-level detail (plan vs. actual per set) from completed sessions. */ export async function getTraineeReport( prisma: PrismaClient, trainerId: string, userId: string, ): Promise { await assertActiveTrainee(prisma, trainerId, userId); const plan = await prisma.trainingPlan.findFirst({ where: { userId, status: 'ACTIVE', kind: 'PLAN' }, select: { id: true, title: true, startDate: true, weeksCount: true, weeks: { select: { days: { where: { removedAt: null }, select: { id: true, date: true, status: true, moveLog: { select: { id: true } }, exercises: { select: { exercise: { select: { id: true, primaryMuscle: true } }, sets: { select: { reps: true } }, }, }, }, }, }, }, }, }); if (!plan) return { plan: null, muscles: [], days: [], exercises: [] }; const rangeByMuscle = await loadFocusRanges(prisma); // kolejność pierwszego wystąpienia ćwiczenia w planie — sortowanie szczegółów const planExerciseOrder = new Map(); 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) { if (!planExerciseOrder.has(pe.exercise.id)) { planExerciseOrder.set(pe.exercise.id, planExerciseOrder.size); } } } } const planned = aggregatePlannedByMuscle(plan.weeks.flatMap((w) => w.days)); const sessions = await prisma.trainingSession.findMany({ where: { status: 'COMPLETED', dayId: { in: dayIds } }, orderBy: { startedAt: 'asc' }, select: { exercises: { select: { removed: true, hidden: true, exerciseId: true, planExerciseId: true, exercise: { select: { name: true, nameEn: true, primaryMuscle: true } }, sets: { orderBy: { index: 'asc' }, select: { index: true, reps: true, rir: true, difficulty: true, note: true, planSetId: true, planSet: { select: { reps: true, loadKg: true, restSec: true, rir: true } }, }, }, }, }, }, }); const { actual, extra } = aggregateActualByMuscle(sessions); // agregacja per ćwiczenie (plan vs. wykonane per seria) po zakończonych sesjach const detail = new Map(); for (const session of sessions) { for (const ex of session.exercises) { if (ex.removed || ex.hidden) continue; // powiązanie z planem: planExerciseId lub choćby jedna seria spięta z PlanSet const linked = ex.planExerciseId != null || ex.sets.some((st) => st.planSetId != null); let acc = detail.get(ex.exerciseId); if (!acc) { acc = { id: ex.exerciseId, name: ex.exercise.name, nameEn: ex.exercise.nameEn, muscle: ex.exercise.primaryMuscle, isExtra: !linked, sets: [], }; detail.set(ex.exerciseId, acc); } else if (linked) { acc.isExtra = false; } for (const st of ex.sets) { const hasResult = st.reps != null || st.rir != null || st.difficulty != null || st.note != null; // seria ponad plan bez żadnego zapisu nie niesie informacji dla raportu if (st.planSetId == null && !hasResult) continue; acc.sets.push({ // numeracja ciągła w obrębie ćwiczenia — ta sama kolejność chronologiczna index: acc.sets.length + 1, planned: st.planSet ? { reps: st.planSet.reps, loadKg: st.planSet.loadKg, restSec: st.planSet.restSec, rir: st.planSet.rir, } : null, actual: st.reps != null ? { reps: st.reps, rir: st.rir, difficulty: st.difficulty } : null, note: st.note, }); } } } // ćwiczenia planowe w kolejności z planu, dodane ponad plan — na końcu const exercises = [...detail.values()].sort((a, b) => { const oa = planExerciseOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER; const ob = planExerciseOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER; return oa - ob; }); const muscles = buildMuscleReports(planned, actual, extra, rangeByMuscle, plan.weeksCount); 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, exercises, }; } /** 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', kind: 'PLAN' }, 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' } }); }