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-11-26 00:37:17 +01:00
|
|
|
|
import { ROLE_KEYS } from '../lib/permissions.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';
|
2026-11-06 02:59:12 +01:00
|
|
|
|
import {
|
|
|
|
|
|
aggregateActualByMuscle,
|
|
|
|
|
|
aggregatePlannedByMuscle,
|
|
|
|
|
|
buildMuscleReports,
|
|
|
|
|
|
loadFocusRanges,
|
|
|
|
|
|
type MuscleReport,
|
|
|
|
|
|
} from './planVolume.js';
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
|
|
|
|
|
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({
|
2026-11-06 02:59:12 +01:00
|
|
|
|
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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> {
|
2026-11-26 00:37:17 +01:00
|
|
|
|
const grant = await prisma.userRoleGrant.findFirst({
|
|
|
|
|
|
where: { userId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_TRAINER } },
|
|
|
|
|
|
select: { id: true },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
});
|
2026-11-26 00:37:17 +01:00
|
|
|
|
return !!grant;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Sygnatura trainera w konkretnej siłowni (grant GYM_TRAINER). */
|
|
|
|
|
|
async function isTrainerInGym(
|
|
|
|
|
|
prisma: PrismaClient,
|
|
|
|
|
|
userId: string,
|
|
|
|
|
|
gymId: string,
|
|
|
|
|
|
): Promise<boolean> {
|
|
|
|
|
|
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<string> {
|
|
|
|
|
|
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];
|
2026-09-04 19:06:19 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
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-11-26 00:37:17 +01:00
|
|
|
|
export async function sendInvitation(
|
|
|
|
|
|
prisma: PrismaClient,
|
|
|
|
|
|
requesterId: string,
|
|
|
|
|
|
targetId: string,
|
|
|
|
|
|
gymId?: string | null,
|
|
|
|
|
|
) {
|
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;
|
2026-11-26 00:37:17 +01:00
|
|
|
|
const coachingGymId = await resolveCoachingGym(prisma, trainerId, userId, gymId);
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
|
|
|
|
|
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 },
|
2026-11-26 00:37:17 +01:00
|
|
|
|
data: {
|
|
|
|
|
|
status: 'PENDING',
|
|
|
|
|
|
invitedBy: requesterId,
|
|
|
|
|
|
invitedAt: now,
|
|
|
|
|
|
expiresAt,
|
|
|
|
|
|
note: null,
|
|
|
|
|
|
gymId: coachingGymId,
|
|
|
|
|
|
},
|
2026-10-11 17:56:41 +02:00
|
|
|
|
})
|
|
|
|
|
|
: await prisma.coaching.create({
|
2026-11-26 00:37:17 +01:00
|
|
|
|
data: { trainerId, userId, invitedBy: requesterId, expiresAt, gymId: coachingGymId },
|
2026-10-11 17:56:41 +02:00
|
|
|
|
});
|
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
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-26 00:37:17 +01:00
|
|
|
|
/** 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. */
|
2026-09-04 19:06:19 +02:00
|
|
|
|
export async function listTrainees(prisma: PrismaClient, trainerId: string, gymId?: string) {
|
2026-11-26 00:37:17 +01:00
|
|
|
|
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 } } } },
|
|
|
|
|
|
},
|
2026-09-04 19:06:19 +02:00
|
|
|
|
},
|
|
|
|
|
|
},
|
2026-11-26 00:37:17 +01:00
|
|
|
|
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));
|
2026-09-04 19:06:19 +02:00
|
|
|
|
const trainees = await Promise.all(
|
2026-11-26 00:37:17 +01:00
|
|
|
|
visible.map(async (c) => {
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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 };
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-26 00:37:17 +01:00
|
|
|
|
/** 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). */
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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');
|
2026-11-26 00:37:17 +01:00
|
|
|
|
if (coaching.gymId && !(await isTrainerInGym(prisma, trainerId, coaching.gymId)))
|
|
|
|
|
|
throw notFound('Trainee not found');
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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);
|
2026-11-09 03:39:29 +01:00
|
|
|
|
return getHistory(prisma, userId, undefined, trainerId);
|
2026-09-04 19:06:19 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-11-06 02:59:12 +01:00
|
|
|
|
export type { MuscleReport };
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
2026-11-01 09:41:05 +01:00
|
|
|
|
/** Pojedyncza seria ćwiczenia w raporcie: plan vs. wykonane. */
|
|
|
|
|
|
export interface ExerciseReportSet {
|
|
|
|
|
|
/** Numeracja ciągła w obrębie ćwiczenia (chronologicznie po sesjach). */
|
|
|
|
|
|
index: number;
|
2026-11-05 21:23:15 +01:00
|
|
|
|
planned: {
|
|
|
|
|
|
reps: number | null;
|
|
|
|
|
|
loadKg: number | null;
|
|
|
|
|
|
restSec: number | null;
|
|
|
|
|
|
rir: number | null;
|
|
|
|
|
|
} | null;
|
2026-11-01 09:41:05 +01:00
|
|
|
|
/** 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[];
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-04 19:06:19 +02:00
|
|
|
|
export interface TraineeReport {
|
|
|
|
|
|
plan: { id: string; title: string; startDate: string | null } | null;
|
|
|
|
|
|
muscles: MuscleReport[];
|
|
|
|
|
|
days: { date: string; status: 'PLANNED' | 'COMPLETED' | 'SKIPPED'; moved: boolean }[];
|
2026-11-01 09:41:05 +01:00
|
|
|
|
/**
|
|
|
|
|
|
* Szczegóły per ćwiczenie (plan vs. wykonane per seria). Opcjonalne dla
|
|
|
|
|
|
* kompatybilności wstecznej — front fallbackuje do pasków per partia.
|
|
|
|
|
|
*/
|
|
|
|
|
|
exercises?: ExerciseReport[];
|
2026-09-04 19:06:19 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* Plan vs. actual per muscle group (decision 20) with the recommended volume
|
2026-11-01 09:41:05 +01:00
|
|
|
|
* range (decision 13) and plan days for the discipline heatmap; plus
|
|
|
|
|
|
* exercise-level detail (plan vs. actual per set) from completed sessions.
|
2026-09-04 19:06:19 +02:00
|
|
|
|
*/
|
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({
|
2026-11-06 02:59:12 +01:00
|
|
|
|
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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: {
|
2026-11-01 09:41:05 +01:00
|
|
|
|
exercise: { select: { id: true, primaryMuscle: true } },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
sets: { select: { reps: true } },
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
});
|
2026-11-01 09:41:05 +01:00
|
|
|
|
if (!plan) return { plan: null, muscles: [], days: [], exercises: [] };
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
2026-11-06 02:59:12 +01:00
|
|
|
|
const rangeByMuscle = await loadFocusRanges(prisma);
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
2026-11-01 09:41:05 +01:00
|
|
|
|
// kolejność pierwszego wystąpienia ćwiczenia w planie — sortowanie szczegółów
|
|
|
|
|
|
const planExerciseOrder = new Map<string, number>();
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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) {
|
2026-11-01 09:41:05 +01:00
|
|
|
|
if (!planExerciseOrder.has(pe.exercise.id)) {
|
|
|
|
|
|
planExerciseOrder.set(pe.exercise.id, planExerciseOrder.size);
|
|
|
|
|
|
}
|
2026-09-04 19:06:19 +02:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-11-06 02:59:12 +01:00
|
|
|
|
const planned = aggregatePlannedByMuscle(plan.weeks.flatMap((w) => w.days));
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
|
|
|
|
|
const sessions = await prisma.trainingSession.findMany({
|
|
|
|
|
|
where: { status: 'COMPLETED', dayId: { in: dayIds } },
|
2026-11-01 09:41:05 +01:00
|
|
|
|
orderBy: { startedAt: 'asc' },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
select: {
|
|
|
|
|
|
exercises: {
|
|
|
|
|
|
select: {
|
|
|
|
|
|
removed: true,
|
|
|
|
|
|
hidden: true,
|
2026-11-01 09:41:05 +01:00
|
|
|
|
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 } },
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
2026-09-04 19:06:19 +02:00
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
},
|
|
|
|
|
|
});
|
2026-11-06 02:59:12 +01:00
|
|
|
|
const { actual, extra } = aggregateActualByMuscle(sessions);
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
2026-11-01 09:41:05 +01:00
|
|
|
|
// agregacja per ćwiczenie (plan vs. wykonane per seria) po zakończonych sesjach
|
|
|
|
|
|
const detail = new Map<string, ExerciseReport>();
|
|
|
|
|
|
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) {
|
2026-11-05 21:23:15 +01:00
|
|
|
|
const hasResult =
|
|
|
|
|
|
st.reps != null || st.rir != null || st.difficulty != null || st.note != null;
|
2026-11-01 09:41:05 +01:00
|
|
|
|
// 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;
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-11-06 02:59:12 +01:00
|
|
|
|
const muscles = buildMuscleReports(planned, actual, extra, rangeByMuscle, plan.weeksCount);
|
2026-09-04 19:06:19 +02:00
|
|
|
|
|
|
|
|
|
|
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,
|
2026-11-01 09:41:05 +01:00
|
|
|
|
exercises,
|
2026-09-04 19:06:19 +02:00
|
|
|
|
};
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** 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({
|
2026-11-06 02:59:12 +01:00
|
|
|
|
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
|
2026-09-04 19:06:19 +02:00
|
|
|
|
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' } });
|
|
|
|
|
|
}
|