Plany: strzalki tygodni w kalendarzu startu i blokada minionych dni - strzalki zaznaczaja nastepny/poprzedni tydzien (lewa znika na biezacym), Ten tydzien zamiast Dzis; krok 2 blokuje dni z przeszlosci (modal + PLAN_DAY_IN_PAST w API), kopiowanie tygodni/dni pomija cele minione; wybor tygodnia nie aktywuje planu (start zapisywany w szkicu, usuniete activateHint i activationSkipped); rezerwa miejsca na blad tytulu naprawia gubienie pierwszego klikniecia po autofocusie (weekPicker.* w i18n; testy unit + integracyjne + e2e)

This commit is contained in:
tisachi
2026-11-06 00:27:39 +01:00
parent b24f11d76b
commit 92cb3b8908
22 changed files with 797 additions and 320 deletions

View File

@@ -59,14 +59,15 @@ export function createPlanRoutes({ prisma }: AppDeps) {
* @openapi
* /plans:
* post:
* summary: Create plan. Structure: weeks -> days (dayOfWeek) -> exercises -> sets.
* Optional startDate (a Monday) creates and activates the plan in one step.
* Creation is always allowed; when the user already has an active plan the new
* plan stays a DRAFT and the response carries activationSkipped: true.
* summary: Create plan (always a DRAFT). Structure: weeks -> days (dayOfWeek) ->
* exercises -> sets. Optional startDate (a Monday, current or future week) is
* stored as the planned start; activation is a separate action
* (POST /plans/{id}/activate). Days that would fall before today under the
* marked start are rejected.
* tags: [Plans]
* responses:
* 201: { description: Created }
* 400: { description: Validation error / start date not a Monday / start week in the past }
* 400: { description: Validation error / start date not a Monday / start week in the past / PLAN_DAY_IN_PAST }
*/
router.post(
'/',
@@ -126,17 +127,16 @@ export function createPlanRoutes({ prisma }: AppDeps) {
* /plans/{id}:
* patch:
* summary: Update plan structure. DRAFT = full replace (optional startDate = a Monday,
* current or future week, activates the plan in one step). ACTIVE = differential edit
* current or future week, stored as the planned start — the plan stays a DRAFT;
* activation is separate). ACTIVE = differential edit
* (days with history are kept; removing a day with history returns 400
* PLAN_DAY_HAS_HISTORY unless forceRemoveDays: true soft-removes it with history
* preserved) and records an optional
* changeNote in the plan's edit history.
* The update is always allowed; when the user already has an active plan the
* structure is saved and the response carries activationSkipped: true.
* tags: [Plans]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft/active plan / start date not a Monday / start week in the past / PLAN_DAY_HAS_HISTORY }
* 400: { description: Not a draft/active plan / start date not a Monday / start week in the past / PLAN_DAY_IN_PAST / PLAN_DAY_HAS_HISTORY }
*/
router.patch(
'/:id',

View File

@@ -436,14 +436,13 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/trainees/{userId}/plans:
* post:
* summary: Create a plan for the trainee (owner = trainee, creator = trainer).
* Optional gymId (the trainee must be a gym member) and per-week customName (alias, max 40).
* Creation is always allowed; when the trainee already has an active plan the new
* plan stays a DRAFT and the response carries activationSkipped: true.
* summary: Create a plan for the trainee (owner = trainee, creator = trainer; always
* a DRAFT — activation is separate). Optional gymId (the trainee must be a gym
* member), per-week customName (alias, max 40) and an optional planned startDate.
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Validation error / start date not a Monday / start week in the past / gym not a trainee membership }
* 400: { description: Validation error / start date not a Monday / start week in the past / PLAN_DAY_IN_PAST / gym not a trainee membership }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
@@ -491,8 +490,9 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* patch:
* summary: Update plan structure. DRAFT = full replace (optional startDate = a Monday
* activates the plan in one step); ACTIVE = differential edit with an optional
* summary: Update plan structure. DRAFT = full replace (optional startDate = a Monday,
* current or future week, stored as the planned start — the plan stays a DRAFT);
* ACTIVE = differential edit with an optional
* changeNote (recorded in the plan edit history; the trainee gets a PLAN_EDITED
* feed notification).
* Same body as POST (gymId, weeks[].customName,
@@ -500,7 +500,7 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft/active plan / change note required / gym not a trainee membership / start date not a Monday / start week in the past / PLAN_DAY_HAS_HISTORY }
* 400: { description: Not a draft/active plan / change note required / gym not a trainee membership / start date not a Monday / start week in the past / PLAN_DAY_IN_PAST / PLAN_DAY_HAS_HISTORY }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/

View File

@@ -176,8 +176,10 @@ export async function createPlan(
) {
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, userId);
// Data startu: walidacja (poniedziałek) przed utworzeniem planu.
// Data startu: walidacja (poniedziałek, tydzień bieżący lub przyszły) przed
// utworzeniem planu + dni nie mogą wypadać w przeszłości względem startu.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
if (startOfStart) assertDaysNotInPast(startOfStart, data.weeks);
const plan = await prisma.trainingPlan.create({
data: {
title: data.title,
@@ -186,13 +188,13 @@ export async function createPlan(
status: 'DRAFT',
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
// Zaznaczony start = planowany start szkicu; aktywacja to osobna akcja
// (POST /plans/:id/activate) — tworzenie NIGDY nie aktywuje planu.
startDate: startOfStart,
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, {
@@ -215,7 +217,6 @@ export async function createPlan(
startDate: updated!.startDate,
gym: updated!.gym,
},
activationSkipped,
};
}
@@ -316,8 +317,10 @@ export async function updatePlan(
// 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, plan.userId, userId, data);
// Data startu (opcjonalna): walidacja (poniedziałek) przed aktualizacją struktury.
// Data startu (opcjonalna): walidacja (poniedziałek, bieżący/przyszły tydzień)
// + dni nie mogą wypadać w przeszłości względem zaznaczonego startu.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
if (startOfStart) assertDaysNotInPast(startOfStart, data.weeks);
await prisma.$transaction(async (tx) => {
await tx.planWeek.deleteMany({ where: { planId: plan.id } });
await tx.trainingPlan.update({
@@ -326,15 +329,14 @@ export async function updatePlan(
title: data.title,
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
// Zapis szkicu zachowuje/aktualizuje planowany start; NIGDY nie aktywuje
// planu — aktywacja to osobna akcja (POST /plans/:id/activate).
startDate: startOfStart,
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 };
return { ok: true };
}
/* ---------------------------------------------------------------------------
@@ -439,6 +441,28 @@ function planDayDate(startDate: Date, weekIndex: number, dayOfWeek: number): Dat
return d;
}
/**
* Dni szkicu z zaznaczonym startem nie mogą wypadać przed dzisiaj — ten sam warunek
* co blokady dni w wizardzie (tydzień już się rozpoczął). Pilnuje ścieżek pomijających UI
* (kopia tygodni, API wprost): kopia przyszłego tygodnia do minionego nie może
* „przenieść” treningów wstecz.
*/
function assertDaysNotInPast(startOfStart: Date, weeks: CreatePlanInput['weeks']) {
const today = startOfDay(new Date());
for (const w of weeks) {
for (const d of w.days) {
if (planDayDate(startOfStart, w.index, d.dayOfWeek) < today) {
throw new AppError(
400,
'PLAN_DAY_IN_PAST',
`Week ${w.index + 1} day ${d.dayOfWeek} falls in the past — remove this day or change the start week`,
{ weekIndex: w.index, dayOfWeek: d.dayOfWeek },
);
}
}
}
}
/** Dnia z historią (ukończona/porzuciona sesja albo stan COMPLETED/SKIPPED) */
function hasTrainingHistory(day: LoadedPlanDay): boolean {
return day.status !== 'PLANNED' || day.sessions.length > 0;
@@ -744,7 +768,7 @@ async function updateActivePlan(
payload: { planId: plan.id, planTitle: data.title.trim(), note: editNote },
});
}
return { ok: true, activationSkipped: false, edited: true };
return { ok: true, edited: true };
}
export async function deletePlan(prisma: PrismaClient, planId: string, userId: string) {
@@ -933,26 +957,6 @@ async function assertNoActivePlan(prisma: PrismaClient, userId: string) {
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).

View File

@@ -1357,7 +1357,7 @@ export const openapi: Record<string, unknown> = {
post: {
tags: ['Plans'],
summary:
'Create plan: weeks -> days (dayOfWeek) -> exercises (min 1 per day) -> sets. Optional startDate (a Monday) creates and activates the plan in one step. Creation is always allowed; when the user already has an active plan the new plan stays a DRAFT and the response carries activationSkipped: true. Optional gymId (informational; the plan owner must be a gym member) and per-week customName (alias, max 40)',
'Create plan (always a DRAFT): weeks -> days (dayOfWeek) -> exercises (min 1 per day) -> sets. Optional startDate (a Monday of the current or a future week) is stored as the planned start; activation is a separate action (POST /plans/{id}/activate). Days that would fall before today under the marked start are rejected with code PLAN_DAY_IN_PAST. Optional gymId (informational; the plan owner must be a gym member) and per-week customName (alias, max 40)',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
@@ -1474,7 +1474,7 @@ export const openapi: Record<string, unknown> = {
patch: {
tags: ['Plans'],
summary:
'Update plan structure. DRAFT = full replace (same body as POST /plans; optional startDate (a Monday of the current or a future week) updates and activates the plan in one step, and an already-active plan of the user only saves the structure with activationSkipped: true). ACTIVE = differential edit: rows matched by the ids sent in the payload are updated in place, new rows are added, the plan start date is immutable, and any real change is recorded in the plan edit history (plan.edits) with an optional changeNote. Removing a day that has training history is rejected with code PLAN_DAY_HAS_HISTORY unless the payload sets forceRemoveDays: true — then the day is soft-removed (removedAt), its row and sessions stay in history while the day disappears from the plan, calendar, stats and killstreak. When an ACTIVE plan actually changes and the editor is not its owner (trainer edit), the owner gets a PLAN_EDITED notification in their feed',
'Update plan structure. DRAFT = full replace (same body as POST /plans; optional startDate (a Monday of the current or a future week) updates the planned start — the plan stays a DRAFT, activation is separate; days falling before today under the marked start are rejected with code PLAN_DAY_IN_PAST). ACTIVE = differential edit: rows matched by the ids sent in the payload are updated in place, new rows are added, the plan start date is immutable, and any real change is recorded in the plan edit history (plan.edits) with an optional changeNote. Removing a day that has training history is rejected with code PLAN_DAY_HAS_HISTORY unless the payload sets forceRemoveDays: true — then the day is soft-removed (removedAt), its row and sessions stay in history while the day disappears from the plan, calendar, stats and killstreak. When an ACTIVE plan actually changes and the editor is not its owner (trainer edit), the owner gets a PLAN_EDITED notification in their feed',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {