2026-09-04 19:06:19 +02:00
|
|
|
|
import type { PrismaClient } from '@prisma/client';
|
|
|
|
|
|
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
|
2026-10-11 17:56:41 +02:00
|
|
|
|
import { isPrismaNotFound } from '../lib/prisma.js';
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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 {
|
2026-10-11 17:56:41 +02:00
|
|
|
|
activePlan: {
|
|
|
|
|
|
id: string;
|
|
|
|
|
|
title: string;
|
|
|
|
|
|
progress: { completed: number; total: number; percent: number };
|
|
|
|
|
|
} | null;
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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.
|
|
|
|
|
|
*/
|
2026-10-11 17:56:41 +02:00
|
|
|
|
export async function computeTraineeMetrics(
|
|
|
|
|
|
prisma: PrismaClient,
|
|
|
|
|
|
userId: string,
|
|
|
|
|
|
): Promise<TraineeMetrics> {
|
2026-09-04 19:06:19 +02:00
|
|
|
|
const activePlan = await prisma.trainingPlan.findFirst({
|
|
|
|
|
|
where: { userId, status: 'ACTIVE' },
|
|
|
|
|
|
select: {
|
|
|
|
|
|
id: true,
|
|
|
|
|
|
title: true,
|
2026-10-27 21:16:53 +01:00
|
|
|
|
weeks: { select: { days: { where: { removedAt: null }, select: { status: true } } } },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
},
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
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;
|
2026-10-11 17:56:41 +02:00
|
|
|
|
progress = {
|
|
|
|
|
|
completed: completed,
|
|
|
|
|
|
total,
|
|
|
|
|
|
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
|
|
|
|
|
|
};
|
2026-09-04 19:06:19 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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([
|
2026-10-27 21:16:53 +01:00
|
|
|
|
prisma.planSet.count({
|
|
|
|
|
|
where: { exercise: { day: { removedAt: null, week: { planId: activePlan.id } } } },
|
|
|
|
|
|
}),
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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 {
|
2026-10-11 17:56:41 +02:00
|
|
|
|
activePlan: activePlan
|
|
|
|
|
|
? { id: activePlan.id, title: activePlan.title, progress: progress! }
|
|
|
|
|
|
: null,
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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).
|
|
|
|
|
|
*/
|
2026-10-11 17:56:41 +02:00
|
|
|
|
export async function sendInvitation(prisma: PrismaClient, requesterId: string, targetId: string) {
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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');
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-11 17:56:41 +02:00
|
|
|
|
// 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 },
|
|
|
|
|
|
});
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-11 16:17:32 +02:00
|
|
|
|
/** 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');
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-04 19:06:19 +02:00
|
|
|
|
/** Accept an invitation (invited party only). */
|
|
|
|
|
|
export async function acceptInvitation(prisma: PrismaClient, userId: string, coachingId: string) {
|
|
|
|
|
|
const coaching = await loadPendingInvitation(prisma, coachingId);
|
2026-10-11 16:17:32 +02:00
|
|
|
|
assertInvitedParty(coaching, userId);
|
2026-10-11 17:56:41 +02:00
|
|
|
|
const updated = await respondToInvitation(prisma, coachingId, 'ACTIVE');
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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);
|
2026-10-11 16:17:32 +02:00
|
|
|
|
assertInvitedParty(coaching, userId);
|
2026-10-11 17:56:41 +02:00
|
|
|
|
const updated = await respondToInvitation(prisma, coachingId, 'DECLINED');
|
2026-09-04 19:06:19 +02:00
|
|
|
|
return { coaching: updated };
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-11 17:56:41 +02:00
|
|
|
|
/**
|
|
|
|
|
|
* 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;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-04 19:06:19 +02:00
|
|
|
|
/** 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');
|
2026-10-11 17:56:41 +02:00
|
|
|
|
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;
|
|
|
|
|
|
}
|
2026-09-04 19:06:19 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 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) {
|
2026-09-04 23:19:28 +02:00
|
|
|
|
const coaching = await assertActiveTrainee(prisma, trainerId, userId);
|
2026-09-04 19:06:19 +02:00
|
|
|
|
const user = await prisma.user.findUnique({
|
|
|
|
|
|
where: { id: userId },
|
|
|
|
|
|
select: {
|
|
|
|
|
|
id: true,
|
|
|
|
|
|
firstName: true,
|
|
|
|
|
|
lastName: true,
|
|
|
|
|
|
nickname: true,
|
|
|
|
|
|
socialMedia: true,
|
2026-09-13 03:18:18 +02:00
|
|
|
|
// equipment = do limitowania ćwiczeń w edytorze planu podopiecznego
|
|
|
|
|
|
memberships: {
|
2026-10-11 17:56:41 +02:00
|
|
|
|
select: {
|
|
|
|
|
|
gym: { select: { id: true, name: true, equipment: { include: { equipment: true } } } },
|
|
|
|
|
|
},
|
2026-09-13 03:18:18 +02:00
|
|
|
|
},
|
2026-09-04 19:06:19 +02:00
|
|
|
|
},
|
|
|
|
|
|
});
|
|
|
|
|
|
if (!user) throw notFound('User not found');
|
|
|
|
|
|
const [dashboard, metrics] = await Promise.all([
|
|
|
|
|
|
getDashboard(prisma, userId),
|
|
|
|
|
|
computeTraineeMetrics(prisma, userId),
|
|
|
|
|
|
]);
|
|
|
|
|
|
return {
|
2026-09-04 23:19:28 +02:00
|
|
|
|
coachingId: coaching.id,
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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.
|
|
|
|
|
|
*/
|
2026-10-11 17:56:41 +02:00
|
|
|
|
export async function getTraineeReport(
|
|
|
|
|
|
prisma: PrismaClient,
|
|
|
|
|
|
trainerId: string,
|
|
|
|
|
|
userId: string,
|
|
|
|
|
|
): Promise<TraineeReport> {
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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: {
|
2026-10-27 21:16:53 +01:00
|
|
|
|
where: { removedAt: null },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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 =
|
2026-10-11 17:56:41 +02:00
|
|
|
|
recommendedRange != null &&
|
|
|
|
|
|
(a.sets < recommendedRange.setsMin || a.sets > recommendedRange.setsMax);
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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 {
|
2026-10-11 17:56:41 +02:00
|
|
|
|
plan: {
|
|
|
|
|
|
id: plan.id,
|
|
|
|
|
|
title: plan.title,
|
|
|
|
|
|
startDate: plan.startDate ? plan.startDate.toISOString() : null,
|
|
|
|
|
|
},
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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' } });
|
|
|
|
|
|
}
|