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

1243 lines
46 KiB
TypeScript

import type { Prisma, PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
import { createNotification } from './feed.js';
export interface PlanSetInput {
/** Istniejące id serii — pozwala zachować wiersz (i jego powiązania) przy edycji planu ACTIVE. */
id?: string;
index: number;
reps?: number | null;
loadKg?: number | null;
restSec?: number | null;
rir?: number | null;
cardioBpm?: number | null;
timeSec?: number | null;
speed?: number | null;
}
export interface PlanExerciseInput {
/** Istniejące id ćwiczenia w planie (edycja planu ACTIVE). */
id?: string;
exerciseId: string;
order: number;
sets: PlanSetInput[];
}
export interface PlanDayInput {
/** Istniejące id dnia (edycja planu ACTIVE — dzień z historią musi pozostać tym samym wierszem). */
id?: string;
dayOfWeek: number;
exercises: PlanExerciseInput[];
}
export interface PlanWeekInput {
index: number;
/** Opcjonalny alias tygodnia (np. „Deload"). */
customName?: string | null;
days: PlanDayInput[];
}
export interface CreatePlanInput {
title: string;
weeksCount: number;
/** Informacyjna — siłownia, w której realizowany jest plan (właściciel musi być jej członkiem). */
gymId?: string | null;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
}
export interface UpdatePlanInput extends CreatePlanInput {
/** Plan ACTIVE: notatka audytowa zmiany („co i dlaczego") — wymagana, gdy coś się różni. */
changeNote?: string;
/**
* Plan ACTIVE: zezwolenie na usunięcie dnia z historią (sesje/COMPLETED/SKIPPED).
* Dzień nie jest kasowany — dostaje `removedAt` (soft-remove): historia zostaje,
* a dzień znika z planu, kalendarza i statystyk. Bez flagi usunięcie takiego
* dnia jest odrzucane (PLAN_DAY_HAS_HISTORY).
*/
forceRemoveDays?: boolean;
}
/**
* The requester may access the plan when they are its owner (the trainee), a
* trainer with an ACTIVE coaching relation to the owner, or a recipient of an
* explicit plan share (read-only). Anything else — and a missing plan — is a
* 404 (no existence leak, matches assertActiveTrainee).
*/
async function assertPlanAccess(prisma: PrismaClient, planId: string, requesterId: string) {
const plan = await prisma.trainingPlan.findUnique({ where: { id: planId } });
if (!plan) throw notFound('Plan not found');
if (plan.userId === requesterId) return plan;
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId: requesterId, userId: plan.userId } },
});
if (coaching && coaching.status === 'ACTIVE') return plan;
const share = await prisma.planShare.findUnique({
where: { planId_sharedWithId: { planId, sharedWithId: requesterId } },
});
if (!share) throw notFound('Plan not found');
return plan;
}
/**
* Owner-only access for the owner-scoped mutation routes (PATCH/DELETE
* /plans/:id, activate/complete/abandon). A trainer keeps mutation rights via
* the /trainer/... routes (same services, no owner check there), and a share
* recipient is read-only — so the check lives on the route, not the service.
*/
export async function assertPlanOwner(prisma: PrismaClient, planId: string, userId: string) {
const plan = await prisma.trainingPlan.findUnique({ where: { id: planId } });
if (!plan) throw notFound('Plan not found');
if (plan.userId !== userId) throw notFound('Plan not found');
return plan;
}
async function validateExercises(prisma: PrismaClient, weeks: PlanWeekInput[]) {
const exerciseIds = new Set(
weeks.flatMap((w) => w.days.flatMap((d) => d.exercises.map((e) => e.exerciseId))),
);
if (exerciseIds.size === 0) return;
const exercises = await prisma.exercise.findMany({ where: { id: { in: [...exerciseIds] } } });
if (exercises.length !== exerciseIds.size) throw badRequest('Unknown exerciseId in plan');
}
/**
* Siłownia planu jest informacyjna, ale musi istnieć i właściciel planu
* (podopieczny w trybie trenera) musi być jej członkiem.
*/
async function validateGymMembership(
prisma: PrismaClient,
gymId: string | null | undefined,
ownerId: string,
) {
if (!gymId) return;
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw badRequest('Unknown gymId in plan');
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: ownerId, gymId } },
});
if (!membership) throw badRequest('Plan owner is not a member of the gym');
}
function weekData(weeks: PlanWeekInput[]) {
return weeks.map((w) => ({
index: w.index,
customName: w.customName ?? null,
days: {
create: w.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: {
create: d.exercises.map((e) => ({
exerciseId: e.exerciseId,
order: e.order,
sets: { create: e.sets },
})),
},
})),
},
}));
}
export async function listPlans(prisma: PrismaClient, userId: string) {
const plans = await prisma.trainingPlan.findMany({
where: { userId },
orderBy: { createdAt: 'desc' },
include: {
creator: { select: { id: true, firstName: true, lastName: true } },
gym: { select: { id: true, name: true } },
weeks: { select: { days: { where: { removedAt: null }, select: { status: true } } } },
},
});
return {
plans: plans.map((p) => {
const days = (p.weeks ?? []).flatMap((w) => w.days);
const completed = days.filter((d) => d.status === 'COMPLETED').length;
const total = days.length;
const { weeks: _weeks, ...rest } = p;
return {
...rest,
progress: {
completed,
total,
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
},
};
}),
};
}
export async function createPlan(
prisma: PrismaClient,
userId: string,
data: CreatePlanInput,
creatorId?: string,
) {
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, userId);
// Data startu: walidacja (poniedziałek) przed utworzeniem planu.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
const plan = await prisma.trainingPlan.create({
data: {
title: data.title,
userId,
creatorId: creatorId ?? userId,
status: 'DRAFT',
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
weeks: { create: weekData(data.weeks) },
},
include: { gym: { select: { id: true, name: true } } },
});
// Tworzenie planu jest zawsze możliwe, niezależnie od aktywnego planu — gdy
// właściciel już ma plan aktywny, aktywacja zostaje pominięta (plan = DRAFT).
const activationSkipped = await tryActivate(prisma, plan.id, userId, startOfStart);
// Plan tworzony przez trenera dla podopiecznego → powiadomienie „trener zrobił plan".
if (creatorId && creatorId !== userId) {
await createNotification(prisma, {
userId,
type: 'PLAN_READY',
title: `Trener utworzył dla Ciebie plan: ${data.title}`,
payload: { planId: plan.id, planTitle: data.title },
});
}
const updated = await prisma.trainingPlan.findUnique({
where: { id: plan.id },
include: { gym: { select: { id: true, name: true } } },
});
return {
plan: {
id: updated!.id,
title: updated!.title,
status: updated!.status,
weeksCount: updated!.weeksCount,
startDate: updated!.startDate,
gym: updated!.gym,
},
activationSkipped,
};
}
/**
* Zmiana informacyjnej siłowni planu — dozwolona również dla planu ACTIVE
* (modal rozpoczęcia treningu: user stawił się w innej siłowni niż zamierzona).
* Tylko właściciel; docelowa siłownia musi być siłownią, której jest członkiem.
*/
export async function updatePlanGym(
prisma: PrismaClient,
planId: string,
userId: string,
gymId: string | null,
) {
const plan = await prisma.trainingPlan.findUnique({
where: { id: planId },
select: { id: true, userId: true },
});
if (!plan || plan.userId !== userId) throw notFound('Plan not found');
await validateGymMembership(prisma, gymId, userId);
const updated = await prisma.trainingPlan.update({
where: { id: plan.id },
data: { gymId: gymId ?? null },
select: { id: true, gym: { select: { id: true, name: true } } },
});
return { plan: { id: updated.id, gym: updated.gym } };
}
export async function getPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
// `shares` eksponowane tylko dla właściciela (lista odbiorców do dialogu
// „Udostępnij”); trener i odbiorca share'a dostają ten sam widok bez tej sekcji.
const isOwner = plan.userId === userId;
// canManage: właściciel lub trener z AKTYWNYM coachingiem; odbiorca share'a = read-only.
let canManage = isOwner;
if (!isOwner) {
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId: userId, userId: plan.userId } },
});
canManage = coaching?.status === 'ACTIVE';
}
const full = await prisma.trainingPlan.findUnique({
where: { id: planId },
include: {
gym: { select: { id: true, name: true } },
shares: {
orderBy: { createdAt: 'asc' },
include: { sharedWith: { select: { id: true, firstName: true, lastName: true } } },
},
// historia zmian w trakcie realizacji (notatki audytowe edycji planu ACTIVE)
edits: {
orderBy: { createdAt: 'desc' },
take: 30,
include: { actor: { select: { id: true, firstName: true, lastName: true } } },
},
weeks: {
orderBy: { index: 'asc' },
include: {
days: {
where: { removedAt: null },
include: {
exercises: {
orderBy: { order: 'asc' },
include: { exercise: true, sets: { orderBy: { index: 'asc' } } },
},
moveLog: { orderBy: { movedAt: 'desc' } },
sessions: { orderBy: { startedAt: 'desc' } },
},
},
},
},
},
});
if (!full) throw notFound('Plan not found');
return {
plan: {
...full,
canManage,
// frontend shape: { userId, user: { id, firstName, lastName } }
shares: isOwner
? full.shares.map((s) => ({ userId: s.sharedWithId, user: s.sharedWith }))
: undefined,
},
};
}
export async function updatePlan(
prisma: PrismaClient,
planId: string,
userId: string,
data: UpdatePlanInput,
) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT' && plan.status !== 'ACTIVE')
throw badRequest('Only a draft or an active plan can be edited');
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, plan.userId);
// Plan w trakcie realizacji: zmiany rozliczamy wiersz po wierszu (bez rekolekcji),
// żeby nie skasować dni z historią i sesjami — i wymagamy notatki audytowej.
if (plan.status === 'ACTIVE') return updateActivePlan(prisma, plan, userId, data);
// Data startu (opcjonalna): walidacja (poniedziałek) przed aktualizacją struktury.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
await prisma.$transaction(async (tx) => {
await tx.planWeek.deleteMany({ where: { planId: plan.id } });
await tx.trainingPlan.update({
where: { id: plan.id },
data: {
title: data.title,
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
weeks: { create: weekData(data.weeks) },
},
});
});
// Zapis = aktualizacja + aktywacja w jednym kroku: applyStartDate musi działać PO
// rekolekcji tygodni (wylicza daty dla nowych ID dni). Gdy właściciel ma już
// aktywny plan, struktura zostaje zapisana, a aktywacja pominięta (DRAFT).
const activationSkipped = await tryActivate(prisma, plan.id, plan.userId, startOfStart);
return { ok: true, activationSkipped };
}
/* ---------------------------------------------------------------------------
* Edycja planu ACTIVE — rozliczenie różnicowe (bez rekolekcji tygodni)
* ------------------------------------------------------------------------- */
type SetFields = Pick<
PlanSetInput,
'reps' | 'loadKg' | 'restSec' | 'rir' | 'cardioBpm' | 'timeSec' | 'speed'
>;
type StoredSetFields = { [K in keyof SetFields]-?: number | null };
interface LoadedPlanSet extends StoredSetFields {
id: string;
index: number;
}
interface LoadedPlanExercise {
id: string;
exerciseId: string;
order: number;
sets: LoadedPlanSet[];
}
interface LoadedPlanDay {
id: string;
dayOfWeek: number;
status: string;
exercises: LoadedPlanExercise[];
sessions: { id: string; status: string }[];
}
interface LoadedPlanWeek {
id: string;
index: number;
customName: string | null;
days: LoadedPlanDay[];
}
interface ChangeCounters {
daysAdded: number;
daysRemoved: number;
daysForceRemoved: number;
exercisesAdded: number;
exercisesRemoved: number;
exercisesReplaced: number;
exercisesReordered: number;
setsAdded: number;
setsRemoved: number;
setsChanged: number;
setsReordered: number;
}
const noChanges = (): ChangeCounters => ({
daysAdded: 0,
daysRemoved: 0,
daysForceRemoved: 0,
exercisesAdded: 0,
exercisesRemoved: 0,
exercisesReplaced: 0,
exercisesReordered: 0,
setsAdded: 0,
setsRemoved: 0,
setsChanged: 0,
setsReordered: 0,
});
/**
* Walory serii z payloadu. `undefined` = pola nie wysłano (front edytuje tylko
* reps/obciążenie/przerwę/RIR) — zostawiamy wartość z bazy; `null` = świadome wyczyszczenie.
*/
function setFields(input: PlanSetInput, base?: StoredSetFields): StoredSetFields {
const pick = <K extends keyof SetFields>(key: K): number | null => {
const v = input[key];
if (v === undefined) return base ? base[key] : null;
return v ?? null;
};
return {
reps: pick('reps'),
loadKg: pick('loadKg'),
restSec: pick('restSec'),
rir: pick('rir'),
cardioBpm: pick('cardioBpm'),
timeSec: pick('timeSec'),
speed: pick('speed'),
};
}
function sameSetFields(a: StoredSetFields, b: StoredSetFields): boolean {
return (Object.keys(a) as (keyof StoredSetFields)[]).every((k) => a[k] === b[k]);
}
function newExerciseData(input: PlanExerciseInput) {
return {
exerciseId: input.exerciseId,
order: input.order,
sets: { create: input.sets.map((s) => ({ index: s.index, ...setFields(s) })) },
};
}
/** Data dnia planu liczona od startu — te same przesunięcia co `applyStartDate`. */
function planDayDate(startDate: Date, weekIndex: number, dayOfWeek: number): Date {
const d = new Date(startDate);
d.setDate(d.getDate() + weekIndex * 7 + (dayOfWeek - 1));
return d;
}
/** Dnia z historią (ukończona/porzuciona sesja albo stan COMPLETED/SKIPPED) */
function hasTrainingHistory(day: LoadedPlanDay): boolean {
return day.status !== 'PLANNED' || day.sessions.length > 0;
}
/**
* Dnia z historią (sesja albo stan COMPLETED/SKIPPED) nie wolno usunąć z aktywnego
* planu bez świadomej zgody (forceRemoveDays). Zezwolone usunięcie to soft-remove
* (`removedAt`), nie delete — historia treningowa zostaje.
*/
function assertDroppableDay(day: LoadedPlanDay, weekIndex: number, forced: boolean) {
if (!hasTrainingHistory(day) || forced) return;
throw new AppError(
400,
'PLAN_DAY_HAS_HISTORY',
`Week ${weekIndex + 1} day ${day.dayOfWeek} has training history — it cannot be removed from an active plan`,
{ weekIndex, dayOfWeek: day.dayOfWeek },
);
}
/**
* Serie kept-rowów są aktualizowane w miejscu (identyczność = id z payloadu, inaczej index).
* Kolejność operacji omija @@unique([exerciseId, index]): usuń -> numery tymczasowe
* (ujemne) -> dodaj nowe -> ustaw docelowe indexy.
*/
async function reconcileExerciseSets(
tx: Prisma.TransactionClient,
exercise: LoadedPlanExercise,
inputs: PlanSetInput[],
c: ChangeCounters,
) {
const used = new Set<string>();
const kept: { set: LoadedPlanSet; input: PlanSetInput }[] = [];
const fresh: PlanSetInput[] = [];
for (const input of inputs) {
const found =
(input.id ? exercise.sets.find((s) => s.id === input.id) : undefined) ??
exercise.sets.find((s) => s.index === input.index);
if (!found) {
fresh.push(input);
c.setsAdded += 1;
continue;
}
if (used.has(found.id)) throw badRequest('duplicated set id in plan payload');
used.add(found.id);
kept.push({ set: found, input });
}
for (const s of exercise.sets.filter((s) => !used.has(s.id))) {
await tx.planSet.delete({ where: { id: s.id } });
c.setsRemoved += 1;
}
const reordered = kept.filter((k) => k.set.index !== k.input.index);
for (const k of reordered) {
await tx.planSet.update({ where: { id: k.set.id }, data: { index: -(k.input.index + 1) } });
}
if (fresh.length > 0) {
await tx.planSet.createMany({
data: fresh.map((s) => ({ exerciseId: exercise.id, index: s.index, ...setFields(s) })),
});
}
for (const k of reordered) {
await tx.planSet.update({ where: { id: k.set.id }, data: { index: k.input.index } });
}
c.setsReordered += reordered.length;
for (const k of kept) {
const next = setFields(k.input, k.set);
if (!sameSetFields(next, k.set)) {
await tx.planSet.update({ where: { id: k.set.id }, data: next });
c.setsChanged += 1;
}
}
}
/** Ćwiczenia dnia — j/w: id z payloadu to ten sam wiersz, więc sesje zachowują powiązanie. */
async function reconcileDayExercises(
tx: Prisma.TransactionClient,
day: LoadedPlanDay,
inputs: PlanExerciseInput[],
c: ChangeCounters,
) {
const used = new Set<string>();
const kept: { exercise: LoadedPlanExercise; input: PlanExerciseInput }[] = [];
const fresh: PlanExerciseInput[] = [];
for (const input of inputs) {
const found =
(input.id ? day.exercises.find((e) => e.id === input.id) : undefined) ??
day.exercises.find((e) => e.exerciseId === input.exerciseId && e.order === input.order) ??
day.exercises.find((e) => e.exerciseId === input.exerciseId);
if (!found) {
fresh.push(input);
c.exercisesAdded += 1;
c.setsAdded += input.sets.length;
continue;
}
if (used.has(found.id)) throw badRequest('duplicated exercise id in plan payload');
used.add(found.id);
kept.push({ exercise: found, input });
}
for (const ex of day.exercises.filter((e) => !used.has(e.id))) {
await tx.planExercise.delete({ where: { id: ex.id } });
c.exercisesRemoved += 1;
c.setsRemoved += ex.sets.length;
}
const reordered = kept.filter((k) => k.exercise.order !== k.input.order);
for (const k of reordered) {
await tx.planExercise.update({
where: { id: k.exercise.id },
data: { order: -(k.input.order + 1) },
});
}
for (const input of fresh) {
await tx.planExercise.create({ data: { dayId: day.id, ...newExerciseData(input) } });
}
for (const k of reordered) {
await tx.planExercise.update({ where: { id: k.exercise.id }, data: { order: k.input.order } });
}
c.exercisesReordered += reordered.length;
for (const k of kept) {
if (k.exercise.exerciseId !== k.input.exerciseId) {
await tx.planExercise.update({
where: { id: k.exercise.id },
data: { exerciseId: k.input.exerciseId },
});
c.exercisesReplaced += 1;
}
await reconcileExerciseSets(tx, k.exercise, k.input.sets, c);
}
}
/**
* Edycja planu w trakcie realizacji. Zmiany są rozliczane wiersz po wierszu:
* dni z historią zostają nietknięte (ich usunięcie = 400), nowe dni dostają datę
* z szablonu planu, a każda faktyczna zmiana trafia do `PlanEdit` z wymaganą
* notatką („co i dlaczego”). Startu aktywnego planu nie zmienia się.
*/
async function updateActivePlan(
prisma: PrismaClient,
plan: { id: string; title: string; startDate: Date | null; gymId: string | null },
actorId: string,
data: UpdatePlanInput,
) {
if (!plan.startDate) throw badRequest('An active plan must have a start date');
if (data.startDate) {
const want = parseStartMonday(data.startDate);
if (startOfDay(plan.startDate).getTime() !== want.getTime())
throw badRequest('An active plan cannot change its start date');
}
const startDate = plan.startDate;
const weeks = (await prisma.planWeek.findMany({
where: { planId: plan.id },
include: {
days: {
where: { removedAt: null },
include: {
exercises: { include: { sets: true } },
sessions: { select: { id: true, status: true } },
},
},
},
})) as unknown as LoadedPlanWeek[];
const c = noChanges();
const forced = data.forceRemoveDays === true;
const titleChanged = data.title.trim() !== plan.title;
let aliasesChanged = false;
await prisma.$transaction(async (tx) => {
const byIndex = new Map(weeks.map((w) => [w.index, w]));
for (const wIn of data.weeks) {
const alias = wIn.customName?.trim() || null;
const wEx = byIndex.get(wIn.index);
if (!wEx) {
await tx.planWeek.create({
data: {
planId: plan.id,
index: wIn.index,
customName: alias,
days: {
create: wIn.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
date: planDayDate(startDate, wIn.index, d.dayOfWeek),
exercises: { create: d.exercises.map(newExerciseData) },
})),
},
},
});
c.daysAdded += wIn.days.length;
for (const d of wIn.days) {
c.exercisesAdded += d.exercises.length;
c.setsAdded += d.exercises.reduce((n, e) => n + e.sets.length, 0);
}
continue;
}
if ((wEx.customName ?? null) !== alias) aliasesChanged = true;
const usedDays = new Set<string>();
for (const dIn of wIn.days) {
const dEx =
(dIn.id ? wEx.days.find((d) => d.id === dIn.id) : undefined) ??
wEx.days.find((d) => d.dayOfWeek === dIn.dayOfWeek);
if (!dEx) {
await tx.planDay.create({
data: {
weekId: wEx.id,
dayOfWeek: dIn.dayOfWeek,
date: planDayDate(startDate, wIn.index, dIn.dayOfWeek),
exercises: { create: dIn.exercises.map(newExerciseData) },
},
});
c.daysAdded += 1;
c.exercisesAdded += dIn.exercises.length;
c.setsAdded += dIn.exercises.reduce((n, e) => n + e.sets.length, 0);
continue;
}
if (usedDays.has(dEx.id)) throw badRequest('duplicated day id in plan payload');
usedDays.add(dEx.id);
if (dEx.dayOfWeek !== dIn.dayOfWeek) {
// dzień zostaje tym samym wierszem (sesje, moveLog), tylko przesuwa się
// w szablonie — datę liczymy od nowa
await tx.planDay.update({
where: { id: dEx.id },
data: {
dayOfWeek: dIn.dayOfWeek,
date: planDayDate(startDate, wIn.index, dIn.dayOfWeek),
},
});
}
await reconcileDayExercises(tx, dEx, dIn.exercises, c);
}
for (const dEx of wEx.days) {
if (usedDays.has(dEx.id)) continue;
assertDroppableDay(dEx, wIn.index, forced);
if (hasTrainingHistory(dEx)) {
// soft-remove: wiersz zostaje (sesje/serie/PR-y), dzień znika z planu
await tx.planDay.update({ where: { id: dEx.id }, data: { removedAt: new Date() } });
c.daysForceRemoved += 1;
} else {
await tx.planDay.delete({ where: { id: dEx.id } });
c.daysRemoved += 1;
c.exercisesRemoved += dEx.exercises.length;
c.setsRemoved += dEx.exercises.reduce((n, e) => n + e.sets.length, 0);
}
}
if (aliasesChanged) {
await tx.planWeek.update({ where: { id: wEx.id }, data: { customName: alias } });
}
}
const wanted = new Set(data.weeks.map((w) => w.index));
const keptWeekIds = weeks.filter((w) => wanted.has(w.index)).map((w) => w.id);
for (const wEx of weeks) {
if (wanted.has(wEx.index)) continue;
for (const dEx of wEx.days) assertDroppableDay(dEx, wEx.index, forced);
const historyDays = wEx.days.filter(hasTrainingHistory);
for (const dEx of wEx.days) {
if (hasTrainingHistory(dEx)) continue;
c.exercisesRemoved += dEx.exercises.length;
c.setsRemoved += dEx.exercises.reduce((n, e) => n + e.sets.length, 0);
await tx.planDay.delete({ where: { id: dEx.id } });
c.daysRemoved += 1;
}
if (historyDays.length > 0) {
// usuwany tydzień kaskadowo skasowałby dni z historią — przenosimy je
// (jako soft-removed) do pierwszego pozostającego tygodnia tego planu
await tx.planDay.updateMany({
where: { id: { in: historyDays.map((d) => d.id) } },
data: { removedAt: new Date(), weekId: keptWeekIds[0] },
});
c.daysForceRemoved += historyDays.length;
}
await tx.planWeek.delete({ where: { id: wEx.id } });
}
await tx.trainingPlan.update({
where: { id: plan.id },
data: { title: data.title.trim(), weeksCount: data.weeksCount, gymId: data.gymId ?? null },
});
const changed = titleChanged || aliasesChanged || Object.values(c).some((n) => n > 0);
if (changed) {
const note = (data.changeNote ?? '').trim();
if (note.length < 3)
throw badRequest('A change note is required when editing an active plan');
await tx.planEdit.create({
data: {
planId: plan.id,
actorId,
note,
summary: { ...c, title: titleChanged, weekAliases: aliasesChanged },
},
});
}
});
return { ok: true, activationSkipped: false, edited: true };
}
export async function deletePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
// Usunąć można plan w każdym stanie — kaskada w bazie sprząta tygodnie, dni,
// serie i sesje; świadomość utraty historii przelewa się na potwierdzenie w UI.
await prisma.trainingPlan.delete({ where: { id: plan.id } });
return { ok: true, title: plan.title, status: plan.status };
}
/* ---------------------------------------------------------------------------
* Przesuwanie dnia treningowego (opóźnienie / zamiana dni)
* ------------------------------------------------------------------------- */
export interface MoveDayInput {
/** YYYY-MM-DD (data lokalna, północ) — nowy dzień treningu. */
date: string;
/** Powód przesunięcia (trafia do logu DayMove, widoczny w kalendarzu i u trenera). */
reason?: string | null;
/** Dzień zajmujący datę docelową — wymieniamy się z nim datami. */
swapWithDayId?: string;
}
const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
function parseDayDate(raw: string): Date {
const [y, m, d] = raw.split('-').map(Number);
if (!y || !m || !d) throw badRequest('Invalid date');
const date = new Date(y, m - 1, d);
if (date.getFullYear() !== y || date.getMonth() !== m - 1 || date.getDate() !== d)
throw badRequest('Invalid date');
return date;
}
/**
* Przesunięcie dnia treningowego aktywnego planu. Dzień SKIPPED wraca do PLANNED —
* przyczyna niezależna od ćwiczącego nie powinna skreślać treningu na zawsze, a
* przesunięcie w przyszłość musi „odskoczyć” od automatycznego wygaśnięcia.
* Każde przesunięcie (także dzień przesunięty przy zamianie) trafia do `DayMove`.
*/
export async function movePlanDay(
prisma: PrismaClient,
planId: string,
dayId: string,
userId: string,
input: MoveDayInput,
) {
const plan = await assertPlanOwner(prisma, planId, userId);
if (plan.status !== 'ACTIVE') throw badRequest('Only active plans have movable training days');
if (!plan.startDate) throw badRequest('An active plan must have a start date');
const day = await prisma.planDay.findFirst({
where: { id: dayId, removedAt: null, week: { planId: plan.id } },
include: { sessions: { select: { id: true, status: true } } },
});
if (!day) throw notFound('Training day not found');
if (day.status === 'COMPLETED') throw badRequest('A completed day cannot be moved');
if (day.sessions.some((s) => s.status === 'IN_PROGRESS'))
throw badRequest('A day with a training in progress cannot be moved');
if (!day.date) throw badRequest('Training day has no date yet');
const to = parseDayDate(input.date);
const from = startOfDay(day.date);
const startDate = startOfDay(plan.startDate);
const today = startOfDay(new Date());
const earliest = today > startDate ? today : startDate;
if (to < earliest) throw badRequest('Target date cannot be in the past');
const occupants = await prisma.planDay.findMany({
where: {
week: { planId: plan.id },
removedAt: null,
id: { not: day.id },
status: 'PLANNED',
date: to,
},
select: { id: true, date: true, sessions: { select: { id: true, status: true } } },
});
const swapWith = occupants.find((o) => o.id === input.swapWithDayId);
if (occupants.length > 0 && !swapWith) {
// kod + details.conflictDayId: klient proponuje zamianę dni bez zgadywania kolidanta
const clash = occupants[0];
throw new AppError(409, 'PLAN_DAY_TAKEN', 'Another training is already planned on that date', {
conflictDayId: clash.id,
conflictDate: clash.date,
});
}
if (input.swapWithDayId && occupants.length === 0)
throw badRequest('The target date has no planned training to swap with');
if (swapWith && swapWith.sessions.some((s) => s.status === 'IN_PROGRESS'))
throw badRequest('The day to swap with has a training in progress');
if (swapWith && from < earliest)
throw badRequest('The swapped day cannot be moved into the past');
const reason = input.reason?.trim() || null;
await prisma.$transaction(async (tx) => {
await tx.dayMove.create({ data: { dayId: day.id, fromDate: from, toDate: to, reason } });
await tx.planDay.update({
where: { id: day.id },
data: {
date: to,
// przesunięcie w przyszłość przywraca dzień do planu (inaczej zostałby
// SKIPPED na zawsze, mimo że trening wciąż przed nami); wyzerowanie
// decyzji: jeśli przesunięty dzień znowu minie, użytkownik zapyta ponownie
...(day.status === 'SKIPPED'
? { status: 'PLANNED', skippedAt: null, skipResolvedAt: null }
: {}),
},
});
if (swapWith) {
await tx.dayMove.create({
data: { dayId: swapWith.id, fromDate: to, toDate: from, reason },
});
await tx.planDay.update({ where: { id: swapWith.id }, data: { date: from } });
}
});
const updated = await prisma.planDay.findUnique({
where: { id: day.id },
select: { id: true, date: true, status: true, dayOfWeek: true },
});
return { day: updated, swappedWith: swapWith?.id ?? null };
}
/**
* Akceptacja pominiętego dnia: dzień zostaje SKIPPED, a decyzja zamyka dialog
* decyzji na Dashboardzie. Idempotentne — powtórna akceptacja nie zapisuje nic
* ponownie (podwójne kliknięcie jest nieszkodliwe).
*/
export async function acceptSkippedDay(
prisma: PrismaClient,
planId: string,
dayId: string,
userId: string,
) {
await assertPlanOwner(prisma, planId, userId);
const day = await prisma.planDay.findFirst({
where: { id: dayId, removedAt: null, week: { planId } },
});
if (!day) throw notFound('Training day not found');
if (day.status !== 'SKIPPED') throw badRequest('Only a skipped training day can be accepted');
if (day.skipResolvedAt) return { day };
const updated = await prisma.planDay.update({
where: { id: day.id },
data: { skipResolvedAt: new Date() },
});
return { day: updated };
}
export async function activatePlan(
prisma: PrismaClient,
planId: string,
userId: string,
rawStartDate: string,
) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be activated');
// Walidacja daty (poniedziałek) przed sprawdzeniem aktywnego planu.
const startOfStart = parseStartMonday(rawStartDate);
// Ograniczenie "jeden aktywny plan" dotyczy właściciela planu (podopiecznego),
// nie inicjatora (trener może zarządzać planami wielu podopiecznych).
// Pre-check dla szybkiej ścieżki; rozstrzygające sprawdzenie jest atomowo
// w transakcji applyStartDate (blokada działa też przy równoległych żądaniach).
await assertNoActivePlan(prisma, plan.userId);
await applyStartDate(prisma, planId, plan.userId, startOfStart);
return { ok: true, title: plan.title };
}
function parseStartMonday(rawStartDate: string): Date {
const [y, m, d] = rawStartDate.split('-').map(Number);
if (!y || !m || !d) throw badRequest('Invalid start date');
const start = new Date(y, m - 1, d); // local date
if (start.getDay() !== 1) throw badRequest('Start date must be a Monday');
const startOfStart = new Date(start.getFullYear(), start.getMonth(), start.getDate());
// Tydzień startu: bieżący lub przyszły (jednostka = cały tydzień) — nie można
// dodawać treningów z datą wstecz.
const now = new Date();
const currentMonday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
currentMonday.setDate(currentMonday.getDate() - ((currentMonday.getDay() + 6) % 7));
if (startOfStart < currentMonday) throw badRequest('Start date cannot be in the past');
return startOfStart;
}
async function assertNoActivePlan(prisma: PrismaClient, userId: string) {
const existingActive = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
});
if (existingActive) throw conflict('User already has an active plan');
}
/**
* Aktywuje plan, o ile właściciel nie ma już aktywnego planu. Zwraca true, gdy
* aktywacja została pominięta (plan zostaje DRAFT); inne błędy są rzucone dalej.
*/
async function tryActivate(
prisma: PrismaClient,
planId: string,
ownerId: string,
startOfStart: Date | null,
): Promise<boolean> {
if (!startOfStart) return false;
try {
await applyStartDate(prisma, planId, ownerId, startOfStart);
return false;
} catch (e) {
if (e instanceof AppError && e.status === 409) return true;
throw e;
}
}
/**
* Sets the start date on a plan: computes training day dates and marks the
* plan ACTIVE. The date must already be validated (a Monday).
*
* The "one active plan per owner" rule is enforced ATOMICALLY inside the same
* transaction: the active-plan check and the status flip happen together, so
* two concurrent activations of different plans cannot both win.
*/
async function applyStartDate(
prisma: PrismaClient,
planId: string,
ownerId: string,
startOfStart: Date,
) {
const weeks = await prisma.planWeek.findMany({
where: { planId },
include: { days: true },
});
try {
await prisma.$transaction(async (tx) => {
const existingActive = await tx.trainingPlan.findFirst({
where: { userId: ownerId, status: 'ACTIVE' },
});
if (existingActive) throw conflict('User already has an active plan');
for (const week of weeks) {
for (const day of week.days) {
const date = new Date(startOfStart);
date.setDate(date.getDate() + week.index * 7 + (day.dayOfWeek - 1));
await tx.planDay.update({ where: { id: day.id }, data: { date } });
}
}
await tx.trainingPlan.update({
where: { id: planId },
data: { status: 'ACTIVE', startDate: startOfStart },
});
});
} catch (e) {
// Partial unique index (TrainingPlan_userId_active_key) — the last line of
// defence for truly concurrent activations that both passed the check above.
if (isPrismaUnique(e)) throw conflict('User already has an active plan');
throw e;
}
}
export async function abandonPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
// Tylko aktywny plan można porzucić — DRAFT kończy się przez edycję/usunięcie.
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be abandoned');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'ABANDONED' },
});
return { ok: true, title: plan.title };
}
/**
* Zawieszenie aktywnego planu (ACTIVE -> SUSPENDED): pauza bez porzucania.
* Dni zostają nietknięte, a wstrzymany plan nie zajmuje slotu „jeden aktywny
* plan” (częściowy indeks dotyczy tylko ACTIVE) — można uruchomić inny plan.
* Scheduler nie wygasza dni wstrzymanego planu; minione dni PLANNED przesuwamy
* dopiero przy wznowieniu (resumePlan).
* Sesji w trakcie nie zawieszamy — trening musi zostać ukończony lub porzucony.
*/
export async function suspendPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be suspended');
const running = await prisma.trainingSession.count({
where: { status: 'IN_PROGRESS', day: { week: { planId: plan.id } } },
});
if (running > 0)
throw badRequest('A training is in progress — finish or abandon it before suspending the plan');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'SUSPENDED' },
});
return { ok: true, title: plan.title };
}
/**
* Wznowienie wstrzymanego planu (SUSPENDED -> ACTIVE). Zaplanowane dni NIE są
* usuwane: dni z datą dzisiejszą lub przyszłą zostają na swoich miejscach
* (bieżący tydzień), a minione przesuwamy do przodu o pełne tygodnie (ten sam
* dzień tygodnia) w pierwsze wolne miejsce — czyli w następne tygodnie.
* Każde przesunięcie trafia do logu DayMove; dni COMPLETED/SKIPPED zostają.
* Wznowić może wyłącznie właściciel; koliduje z innym aktywnym planem (409).
*/
export async function resumePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanOwner(prisma, planId, userId);
if (plan.status !== 'SUSPENDED') throw badRequest('Only a suspended plan can be resumed');
// Pre-check; rozstrzygnięcie jest atomowo w transakcji + częściowy indeks
// unikalny (TrainingPlan_userId_active_key) jako ostatnia linia obrony.
await assertNoOtherActivePlan(prisma, plan.userId, plan.id);
const today = startOfDay(new Date());
const planned = await prisma.planDay.findMany({
where: { week: { planId: plan.id }, removedAt: null, status: 'PLANNED' },
select: { id: true, date: true },
orderBy: { date: 'asc' },
});
// Daty zajęte przez dni, które zostają (przyszłe) — przesuwane nie mogą na nie wpaść.
const taken = new Set<number>();
for (const d of planned) if (d.date && d.date >= today) taken.add(d.date.getTime());
const moves: { dayId: string; from: Date; to: Date }[] = [];
for (const d of planned) {
if (!d.date || d.date >= today) continue;
const from = startOfDay(d.date);
const to = new Date(from);
// pełne tygodnie w przód: ten sam dzień tygodnia, dziś lub później...
while (to < today) to.setDate(to.getDate() + 7);
// ...a w razie kolizji z innym planowanym dniem tego planu — kolejny tydzień
while (taken.has(to.getTime())) to.setDate(to.getDate() + 7);
taken.add(to.getTime());
moves.push({ dayId: d.id, from, to });
}
try {
await prisma.$transaction(async (tx) => {
const existingActive = await tx.trainingPlan.findFirst({
where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id } },
});
if (existingActive) throw conflict('User already has an active plan');
for (const m of moves) {
await tx.dayMove.create({
data: { dayId: m.dayId, fromDate: m.from, toDate: m.to, reason: 'wznowienie planu' },
});
await tx.planDay.update({ where: { id: m.dayId }, data: { date: m.to } });
}
await tx.trainingPlan.update({
where: { id: plan.id },
data: { status: 'ACTIVE' },
});
});
} catch (e) {
if (isPrismaUnique(e)) throw conflict('User already has an active plan');
throw e;
}
return { ok: true, title: plan.title, movedDays: moves.length };
}
/** Wersja assertNoActivePlan dla wznowienia: ignoruje sam wznowiony plan. */
async function assertNoOtherActivePlan(prisma: PrismaClient, ownerId: string, planId: string) {
const otherActive = await prisma.trainingPlan.findFirst({
where: { userId: ownerId, status: 'ACTIVE', id: { not: planId } },
});
if (otherActive) throw conflict('User already has an active plan');
}
export async function completePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
// Tylko aktywny plan można ukończyć — DRAFT nie zaczął się jeszcze realizować.
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be completed');
// Ręczne ukończenie tylko po domknięciu wszystkich dni (completed/skipped —
// ta sama reguła co auto-ukończenie w schedulerze). Plan w trakcie realizacji
// (dzień PLANNED = trening przed nami) można wyłącznie porzucić.
const pending = await prisma.planDay.count({
where: { week: { planId: plan.id }, removedAt: null, status: 'PLANNED' },
});
if (pending > 0) throw badRequest('Plan has pending training days — it can only be abandoned');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'COMPLETED' },
});
return { ok: true, title: plan.title };
}
/**
* Cofnięcie zamknięcia planu (COMPLETED/ABANDONED -> ACTIVE). Służy do naprawy
* pomyłek (np. błędnie oznaczony plan) — dni SKIPPED nie są wskrzeszane, a plan
* bez dni zaplanowanych zostanie ponownie ukończony przez scheduler, gdy tylko
* wszystkie dni pozostaną domknięte.
* Wznowić może wyłącznie właściciel planu (trener nie ma takiej akcji).
* Zawieszony plan (SUSPENDED) wraca przez resumePlan — nie przez reopen.
*/
export async function reopenPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanOwner(prisma, planId, userId);
if (plan.status !== 'COMPLETED' && plan.status !== 'ABANDONED')
throw badRequest('Only a completed or abandoned plan can be reopened');
// Jeden aktywny plan dotyczy właściciela.
// Pre-check + częściowy indeks unikalny (TrainingPlan_userId_active_key)
// rozstrzyga równoległe wznowienia/aktywacje.
const otherActive = await prisma.trainingPlan.findFirst({
where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id } },
});
if (otherActive) throw conflict('User already has an active plan');
try {
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'ACTIVE' },
});
} catch (e) {
if (isPrismaUnique(e)) throw conflict('User already has an active plan');
throw e;
}
return { ok: true, title: plan.title };
}
/**
* The owner shares the plan with a user in an ACTIVE coaching relation
* (trainer <-> trainee, either direction). Recipients get read-only access.
* The share survives the coaching ending; the owner can unshare anytime.
*/
export async function sharePlan(
prisma: PrismaClient,
planId: string,
requesterId: string,
userId: string,
) {
const plan = await assertPlanAccess(prisma, planId, requesterId);
if (plan.userId !== requesterId) throw forbidden('Only the plan owner can share the plan');
if (userId === requesterId) throw badRequest('Cannot share a plan with yourself');
const coaching =
(await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId: plan.userId, userId } },
})) ??
(await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId: userId, userId: plan.userId } },
}));
if (!coaching || coaching.status !== 'ACTIVE')
throw badRequest('No active coaching relation with this user');
try {
const share = await prisma.planShare.create({
data: { planId, sharedById: plan.userId, sharedWithId: userId },
});
await createNotification(prisma, {
userId,
type: 'PLAN_SHARED',
title: `Plan „${plan.title}” został Ci udostępniony`,
payload: { planId, planTitle: plan.title, sharedById: plan.userId },
});
return { share };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('Plan is already shared with this user');
throw e;
}
}
/** The owner revokes a share (idempotent 404 when the share does not exist). */
export async function unsharePlan(
prisma: PrismaClient,
planId: string,
requesterId: string,
userId: string,
) {
const plan = await assertPlanAccess(prisma, planId, requesterId);
if (plan.userId !== requesterId) throw forbidden('Only the plan owner can unshare the plan');
const result = await prisma.planShare.deleteMany({
where: { planId, sharedWithId: userId },
});
if (result.count === 0) throw notFound('Plan is not shared with this user');
return { ok: true };
}
/** Plans explicitly shared with the user (read-only), with the sharer's name. */
export async function listSharedWithMe(prisma: PrismaClient, userId: string) {
const shares = await prisma.planShare.findMany({
where: { sharedWithId: userId },
include: {
sharedBy: { select: { id: true, firstName: true, lastName: true } },
plan: {
include: {
gym: { select: { id: true, name: true } },
weeks: { select: { days: { select: { status: true } } } },
},
},
},
orderBy: { createdAt: 'desc' },
});
return {
plans: shares.map((s) => {
const days = (s.plan.weeks ?? []).flatMap((w) => w.days);
const completed = days.filter((d) => d.status === 'COMPLETED').length;
const total = days.length;
const { weeks: _weeks, ...rest } = s.plan;
return {
...rest,
sharedBy: s.sharedBy,
progress: {
completed,
total,
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
},
};
}),
};
}
/** The user's trainers (ACTIVE coachings where the user is the trainee). */
export async function getMyTrainers(prisma: PrismaClient, userId: string) {
const coachings = await prisma.coaching.findMany({
where: { userId, status: 'ACTIVE' },
include: {
trainer: { select: { id: true, firstName: true, lastName: true, nickname: true } },
},
orderBy: { createdAt: 'asc' },
});
return {
trainers: coachings.map((c) => ({
id: c.trainer.id,
firstName: c.trainer.firstName,
lastName: c.trainer.lastName,
nickname: c.trainer.nickname,
})),
};
}