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:
@@ -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',
|
||||
|
||||
@@ -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 }
|
||||
*/
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -57,7 +57,9 @@ describe('plans routes', () => {
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
days: [{ dayOfWeek: 2, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 12 }] }] }],
|
||||
days: [
|
||||
{ dayOfWeek: 2, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 12 }] }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -329,9 +331,7 @@ describe('plans routes', () => {
|
||||
exercises: DetailExercise[];
|
||||
}
|
||||
const app = buildApp();
|
||||
const detail = await app
|
||||
.get(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
const weeks = (detail.body.plan.weeks as { index: number; days: DetailDay[] }[]).map((w) => ({
|
||||
index: w.index,
|
||||
days: w.days.map((d) => ({
|
||||
@@ -348,12 +348,15 @@ describe('plans routes', () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ title: 'Poprawiony w trakcie', weeksCount: 2, weeks, changeNote: 'Korekta obciążeń' });
|
||||
.send({
|
||||
title: 'Poprawiony w trakcie',
|
||||
weeksCount: 2,
|
||||
weeks,
|
||||
changeNote: 'Korekta obciążeń',
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const after = await app
|
||||
.get(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
const after = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
expect(after.body.plan.status).toBe('ACTIVE');
|
||||
expect(after.body.plan.title).toBe('Poprawiony w trakcie');
|
||||
const day1 = after.body.plan.weeks
|
||||
@@ -392,9 +395,7 @@ describe('plans routes', () => {
|
||||
exercises: NoNoteExercise[];
|
||||
}
|
||||
const app = buildApp();
|
||||
const detail = await app
|
||||
.get(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
// te same wiersze z tymi samymi parametrami — jedyna realna zmiana to tytuł
|
||||
const weeks = (detail.body.plan.weeks as { index: number; days: NoNoteDay[] }[]).map((w) => ({
|
||||
index: w.index,
|
||||
@@ -414,9 +415,7 @@ describe('plans routes', () => {
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ title: 'Edit bez notatki', weeksCount: weeks.length, weeks });
|
||||
expect(res.status).toBe(200);
|
||||
const after = await app
|
||||
.get(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
const after = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
expect(after.body.plan.title).toBe('Edit bez notatki');
|
||||
// drugi wpis historii (pierwszy z notatką z poprzedniego testu) — notatka pusta
|
||||
expect(after.body.plan.edits).toHaveLength(2);
|
||||
@@ -426,7 +425,10 @@ describe('plans routes', () => {
|
||||
it('refuses to remove a day that has training history from an active plan', async () => {
|
||||
const app = buildApp();
|
||||
await prisma.planDay.update({
|
||||
where: { id: (await prisma.planDay.findFirstOrThrow({ where: { week: { planId }, dayOfWeek: 3 } })).id },
|
||||
where: {
|
||||
id: (await prisma.planDay.findFirstOrThrow({ where: { week: { planId }, dayOfWeek: 3 } }))
|
||||
.id,
|
||||
},
|
||||
data: { status: 'COMPLETED' },
|
||||
});
|
||||
const body = planBody('Bez dnia z historia');
|
||||
@@ -442,7 +444,9 @@ describe('plans routes', () => {
|
||||
|
||||
it('forceRemoveDays soft-removes a day with history — plan hides it, /me/history keeps the session', async () => {
|
||||
const app = buildApp();
|
||||
const day3 = await prisma.planDay.findFirstOrThrow({ where: { week: { planId }, dayOfWeek: 3 } });
|
||||
const day3 = await prisma.planDay.findFirstOrThrow({
|
||||
where: { week: { planId }, dayOfWeek: 3 },
|
||||
});
|
||||
const pe = await prisma.planExercise.findFirstOrThrow({
|
||||
where: { dayId: day3.id },
|
||||
include: { sets: true },
|
||||
@@ -553,7 +557,9 @@ describe('plans routes', () => {
|
||||
.post(`/api/v1/plans/${id}/complete`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('Plan has pending training days — it can only be abandoned');
|
||||
expect(res.body.error.message).toBe(
|
||||
'Plan has pending training days — it can only be abandoned',
|
||||
);
|
||||
|
||||
// w trakcie realizacji pozostaje tylko porzucenie
|
||||
const abandoned = await app
|
||||
@@ -614,7 +620,10 @@ describe('plans routes', () => {
|
||||
.post(`/api/v1/plans/${id}/activate`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ startDate: MONDAY });
|
||||
await prisma.planDay.updateMany({ where: { week: { planId: id } }, data: { status: 'COMPLETED' } });
|
||||
await prisma.planDay.updateMany({
|
||||
where: { week: { planId: id } },
|
||||
data: { status: 'COMPLETED' },
|
||||
});
|
||||
const completed = await app
|
||||
.post(`/api/v1/plans/${id}/complete`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
@@ -657,7 +666,10 @@ describe('plans routes', () => {
|
||||
.post(`/api/v1/plans/${aId}/activate`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ startDate: MONDAY });
|
||||
await prisma.planDay.updateMany({ where: { week: { planId: aId } }, data: { status: 'COMPLETED' } });
|
||||
await prisma.planDay.updateMany({
|
||||
where: { week: { planId: aId } },
|
||||
data: { status: 'COMPLETED' },
|
||||
});
|
||||
await app.post(`/api/v1/plans/${aId}/complete`).set('Authorization', `Bearer ${token}`);
|
||||
|
||||
const b = await app
|
||||
@@ -737,9 +749,7 @@ describe('plans routes', () => {
|
||||
expect(blocked.body.error.message).toBe('User already has an active plan');
|
||||
|
||||
// po zwolnieniu slotu wznowienie przechodzi (wszystkie dni przyszłe — zero przesunięć)
|
||||
await app
|
||||
.post(`/api/v1/plans/${secondId}/abandon`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
await app.post(`/api/v1/plans/${secondId}/abandon`).set('Authorization', `Bearer ${token}`);
|
||||
const resumed = await app
|
||||
.post(`/api/v1/plans/${firstId}/resume`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
@@ -849,19 +859,21 @@ describe('plans routes', () => {
|
||||
expect(res.body.error.message).toBe('Start date cannot be in the past');
|
||||
});
|
||||
|
||||
it('creates and activates a plan in one step when startDate is provided', async () => {
|
||||
it('creates a DRAFT with a planned startDate; activation is a separate step', async () => {
|
||||
const app = buildApp();
|
||||
const body = planBody('One-step plan');
|
||||
body.startDate = MONDAY;
|
||||
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body);
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.plan).toMatchObject({ title: 'One-step plan', status: 'ACTIVE' });
|
||||
expect(res.body.plan).toMatchObject({ title: 'One-step plan', status: 'DRAFT' });
|
||||
expect(res.body).not.toHaveProperty('activationSkipped');
|
||||
expect(res.body.plan.startDate).not.toBeNull();
|
||||
|
||||
// szkic z planowanym startem: dni bez dat — daty dopiero przy aktywacji
|
||||
const detail = await app
|
||||
.get(`/api/v1/plans/${res.body.plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(detail.body.plan.status).toBe('ACTIVE');
|
||||
expect(detail.body.plan.status).toBe('DRAFT');
|
||||
const localDate = (iso: string) => {
|
||||
const d = new Date(iso);
|
||||
return [d.getFullYear(), d.getMonth() + 1, d.getDate()];
|
||||
@@ -869,19 +881,34 @@ describe('plans routes', () => {
|
||||
const [sy, sm, sd] = MONDAY.split('-').map(Number);
|
||||
const week0 = detail.body.plan.weeks.find((w: { index: number }) => w.index === 0);
|
||||
const day1 = week0.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1);
|
||||
expect(localDate(day1.date)).toEqual([sy, sm, sd]);
|
||||
expect(day1.date).toBeNull();
|
||||
|
||||
// aktywacja osobną akcją — daty wyliczone od startu
|
||||
const act = await app
|
||||
.post(`/api/v1/plans/${res.body.plan.id}/activate`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ startDate: MONDAY });
|
||||
expect(act.status).toBe(200);
|
||||
const detail2 = await app
|
||||
.get(`/api/v1/plans/${res.body.plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(detail2.body.plan.status).toBe('ACTIVE');
|
||||
const week0b = detail2.body.plan.weeks.find((w: { index: number }) => w.index === 0);
|
||||
const day1b = week0b.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1);
|
||||
expect(localDate(day1b.date)).toEqual([sy, sm, sd]);
|
||||
});
|
||||
|
||||
it('creates a DRAFT with activationSkipped when startDate is set while another plan is active', async () => {
|
||||
// "One-step plan" from the previous test is ACTIVE.
|
||||
it('creates a DRAFT with startDate even while another plan is active (no auto-activation)', async () => {
|
||||
// "One-step plan" from the previous test is ACTIVE (activated explicitly).
|
||||
const app = buildApp();
|
||||
const body = planBody('Conflicting plan');
|
||||
body.startDate = mondayIso(2);
|
||||
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body);
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.activationSkipped).toBe(true);
|
||||
expect(res.body).not.toHaveProperty('activationSkipped');
|
||||
expect(res.body.plan).toMatchObject({ title: 'Conflicting plan', status: 'DRAFT' });
|
||||
expect(res.body.plan.startDate).toBeNull();
|
||||
// planowany start zostaje zapisany mimo aktywnego planu właściciela
|
||||
expect(res.body.plan.startDate).not.toBeNull();
|
||||
});
|
||||
|
||||
it('allows multiple draft plans while one plan is active', async () => {
|
||||
@@ -1388,7 +1415,7 @@ describe('plans: sharing (PlanShare)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('plans: PATCH with startDate (update + activate)', () => {
|
||||
describe('plans: PATCH with startDate (planowany start, bez autoaktywacji)', () => {
|
||||
let app: ReturnType<typeof buildApp>;
|
||||
let token: string;
|
||||
let userId: string;
|
||||
@@ -1455,7 +1482,7 @@ describe('plans: PATCH with startDate (update + activate)', () => {
|
||||
expect(res.body.error.message).toBe('Start date cannot be in the past');
|
||||
});
|
||||
|
||||
it('PATCH with startDate updates the structure and activates the plan', async () => {
|
||||
it('PATCH with startDate updates the structure and stores the planned start (still DRAFT)', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
@@ -1463,21 +1490,37 @@ describe('plans: PATCH with startDate (update + activate)', () => {
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
expect(detail.body.plan.status).toBe('ACTIVE');
|
||||
expect(detail.body.plan.status).toBe('DRAFT');
|
||||
expect(detail.body.plan.title).toBe('Aktywowany');
|
||||
expect(detail.body.plan.startDate).not.toBeNull();
|
||||
// startDate = północ lokalna — serializowana jako ISO w UTC, więc porównanie przez datę lokalną
|
||||
const localKey = (iso: string) => {
|
||||
const d = new Date(iso);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||||
};
|
||||
expect(localKey(String(detail.body.plan.startDate))).toBe(mondayIso(1));
|
||||
|
||||
// aktywacja osobną akacją domyka flow: status + daty dni
|
||||
const act = await app
|
||||
.post(`/api/v1/plans/${planId}/activate`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ startDate: mondayIso(1) });
|
||||
expect(act.status).toBe(200);
|
||||
const detail2 = await app
|
||||
.get(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(detail2.body.plan.status).toBe('ACTIVE');
|
||||
const localDate = (iso: string) => {
|
||||
const d = new Date(iso);
|
||||
return [d.getFullYear(), d.getMonth() + 1, d.getDate()];
|
||||
};
|
||||
const [sy, sm, sd] = mondayIso(1).split('-').map(Number);
|
||||
const day1 = detail.body.plan.weeks
|
||||
const day1 = detail2.body.plan.weeks
|
||||
.find((w: { index: number }) => w.index === 0)
|
||||
.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1);
|
||||
expect(localDate(day1.date)).toEqual([sy, sm, sd]);
|
||||
});
|
||||
|
||||
it('PATCH with startDate while another plan is active saves the structure as a DRAFT (activationSkipped)', async () => {
|
||||
it('PATCH with startDate saves the planned start as a DRAFT (no auto-activation)', async () => {
|
||||
const created = await app
|
||||
.post('/api/v1/plans')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
@@ -1487,13 +1530,43 @@ describe('plans: PATCH with startDate (update + activate)', () => {
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Konflikt'), startDate: mondayIso(2) });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ ok: true, activationSkipped: true });
|
||||
expect(res.body).not.toHaveProperty('activationSkipped');
|
||||
|
||||
const detail = await app
|
||||
.get(`/api/v1/plans/${created.body.plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(detail.body.plan).toMatchObject({ status: 'DRAFT' });
|
||||
expect(detail.body.plan.startDate).toBeNull();
|
||||
// planowany start zapisany — daty dni wciąż puste (aktywacja osobno);
|
||||
// porównanie przez datę lokalną (północ lokalna serializowana jako ISO UTC)
|
||||
const localKey = (iso: string) => {
|
||||
const d = new Date(iso);
|
||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
||||
};
|
||||
expect(localKey(String(detail.body.plan.startDate))).toBe(mondayIso(2));
|
||||
const day1 = detail.body.plan.weeks
|
||||
.find((w: { index: number }) => w.index === 0)
|
||||
.days.find((d: { dayOfWeek: number }) => d.dayOfWeek === 1);
|
||||
expect(day1.date).toBeNull();
|
||||
});
|
||||
|
||||
it('PATCH with startDate and a day falling before today → 400 PLAN_DAY_IN_PAST', async () => {
|
||||
const created = await app
|
||||
.post('/api/v1/plans')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send(body('Minione dni'));
|
||||
// poniedziałek bieżącego tygodnia: dni przed dzisiaj wypadałyby w przeszłości
|
||||
const dowToday = ((new Date().getDay() + 6) % 7) + 1; // 1=Pn .. 7=Nd
|
||||
if (dowToday <= 1) return; // w poniedziałek nie ma minionych dni w tym tygodniu
|
||||
const pastBody = body('Minione dni');
|
||||
pastBody.weeks[0].days = [
|
||||
{ dayOfWeek: dowToday - 1, exercises: pastBody.weeks[0].days[0].exercises },
|
||||
];
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${created.body.plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...pastBody, startDate: mondayIso(0) });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.code).toBe('PLAN_DAY_IN_PAST');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1502,7 +1575,9 @@ describe('PATCH /plans/:id/gym — zmiana siłowni planu (modal rozpoczęcia tre
|
||||
const app = buildApp();
|
||||
const { user, token } = await registerViaApi();
|
||||
const gym = await prisma.gym.create({ data: { name: `Plan Gym ${rand()}`, kind: 'REAL' } });
|
||||
await prisma.gymMembership.create({ data: { userId: user.id, gymId: gym.id, roles: ['MEMBER'] } });
|
||||
await prisma.gymMembership.create({
|
||||
data: { userId: user.id, gymId: gym.id, roles: ['MEMBER'] },
|
||||
});
|
||||
const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' });
|
||||
|
||||
const res = await app
|
||||
@@ -1525,7 +1600,9 @@ describe('PATCH /plans/:id/gym — zmiana siłowni planu (modal rozpoczęcia tre
|
||||
it('rejects a gym the owner is not a member of with 400 and an unknown gym with 400', async () => {
|
||||
const app = buildApp();
|
||||
const { user, token } = await registerViaApi();
|
||||
const foreign = await prisma.gym.create({ data: { name: `Foreign Gym ${rand()}`, kind: 'REAL' } });
|
||||
const foreign = await prisma.gym.create({
|
||||
data: { name: `Foreign Gym ${rand()}`, kind: 'REAL' },
|
||||
});
|
||||
const plan = await seedPlan({ userId: user.id, status: 'ACTIVE' });
|
||||
|
||||
const notMember = await app
|
||||
@@ -1585,18 +1662,24 @@ describe('usuwanie planów (dowolny status)', () => {
|
||||
],
|
||||
});
|
||||
|
||||
const res = await app.delete(`/api/v1/plans/${plan.id}`).set('Authorization', `Bearer ${token}`);
|
||||
const res = await app
|
||||
.delete(`/api/v1/plans/${plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(res.status).toBe(204);
|
||||
expect(await prisma.trainingPlan.findUnique({ where: { id: plan.id } })).toBeNull();
|
||||
expect(await prisma.planDay.count({ where: { week: { planId: plan.id } } })).toBe(0);
|
||||
expect(await prisma.planExercise.count({ where: { day: { week: { planId: plan.id } } } })).toBe(0);
|
||||
expect(await prisma.planExercise.count({ where: { day: { week: { planId: plan.id } } } })).toBe(
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
it('deletes a COMPLETED plan', async () => {
|
||||
const app = buildApp();
|
||||
const { user, token } = await createUserWithToken();
|
||||
const plan = await seedPlan({ userId: user.id, status: 'COMPLETED' });
|
||||
const res = await app.delete(`/api/v1/plans/${plan.id}`).set('Authorization', `Bearer ${token}`);
|
||||
const res = await app
|
||||
.delete(`/api/v1/plans/${plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
expect(res.status).toBe(204);
|
||||
expect(await prisma.trainingPlan.findUnique({ where: { id: plan.id } })).toBeNull();
|
||||
});
|
||||
@@ -1659,9 +1742,7 @@ describe('PATCH /plans/:id/days/:dayId/move — przesunięcie dnia treningowego'
|
||||
],
|
||||
});
|
||||
planId = plan.id;
|
||||
const byDow = new Map(
|
||||
plan.weeks[0].days.map((d) => [d.dayOfWeek, d.id] as const),
|
||||
);
|
||||
const byDow = new Map(plan.weeks[0].days.map((d) => [d.dayOfWeek, d.id] as const));
|
||||
skippedDayId = byDow.get(1)!;
|
||||
completedDayId = byDow.get(3)!;
|
||||
plannedDayId = byDow.get(5)!;
|
||||
@@ -1904,4 +1985,3 @@ describe('POST /plans/:id/days/:dayId/skip/accept — akceptacja pominiętego dn
|
||||
expect(wrongDay.body.error.message).toBe('Training day not found');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -517,7 +517,7 @@ describe('editing an active plan', () => {
|
||||
prisma.exercise.findMany.mockResolvedValue([{ id: 'x1' }]);
|
||||
await expect(
|
||||
updatePlan(prisma, 'p1', 'u1', { title: 't', weeksCount: 1, weeks: sameWeekPayload() }),
|
||||
).resolves.toEqual({ ok: true, activationSkipped: false, edited: true });
|
||||
).resolves.toEqual({ ok: true, edited: true });
|
||||
expect(tx.planEdit.create).not.toHaveBeenCalled();
|
||||
expect(tx.planExercise.delete).not.toHaveBeenCalled();
|
||||
expect(tx.planDay.delete).not.toHaveBeenCalled();
|
||||
@@ -1127,37 +1127,60 @@ describe('createPlan creatorId', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('createPlan (startDate przy istniejącym aktywnym planie)', () => {
|
||||
it('tworzy plan DRAFT z activationSkipped, gdy użytkownik ma już aktywny plan', async () => {
|
||||
describe('createPlan (startDate = planowany start, bez autoaktywacji)', () => {
|
||||
it('tworzy DRAFT z zapisanym startem; daty dni liczone dopiero przy aktywacji', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
prisma.trainingPlan.create.mockResolvedValue({ id: 'p1' });
|
||||
prisma.planWeek.findMany.mockResolvedValue([]);
|
||||
// W transakcji aktywacji użytkownik ma już aktywny plan → konflikt.
|
||||
tx.trainingPlan.findFirst.mockResolvedValue({ id: 'other-active' });
|
||||
const start = mondayIso(1);
|
||||
const [y, m, d] = start.split('-').map(Number);
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||||
id: 'p1',
|
||||
title: 't',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 1,
|
||||
startDate: null,
|
||||
startDate: new Date(y, m - 1, d),
|
||||
});
|
||||
const result = await createPlan(prisma, 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: mondayIso(1),
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
plan: { id: 'p1', status: 'DRAFT' },
|
||||
activationSkipped: true,
|
||||
startDate: start,
|
||||
});
|
||||
expect(result).toMatchObject({ plan: { id: 'p1', status: 'DRAFT' } });
|
||||
expect(result).not.toHaveProperty('activationSkipped');
|
||||
// planowany start zapisany w wierszu planu
|
||||
expect(prisma.trainingPlan.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ startDate: new Date(y, m - 1, d) }),
|
||||
}),
|
||||
);
|
||||
// brak ścieżki aktywacji: brak dat dni i brak sprawdzania aktywnego planu
|
||||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||||
expect(tx.trainingPlan.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('z dniem wypadającym przed dzisiaj względem startu: 400 PLAN_DAY_IN_PAST (przed zapisem)', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
// poniedziałek bieżącego tygodnia: dni przed dzisiaj wypadałyby w przeszłości
|
||||
const dowToday = ((new Date().getDay() + 6) % 7) + 1; // 1=Pn .. 7=Nd
|
||||
if (dowToday <= 1) return; // w poniedziałek ten tydzień nie ma minionych dni
|
||||
await expect(
|
||||
createPlan(prisma, 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [{ index: 0, days: [{ dayOfWeek: dowToday - 1, exercises: [] }] }],
|
||||
startDate: mondayIso(0),
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400, code: 'PLAN_DAY_IN_PAST' });
|
||||
// fail-fast: plan nie został utworzony
|
||||
expect(prisma.trainingPlan.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updatePlan (startDate = aktualizacja + aktywacja)', () => {
|
||||
it('bez startDate: aktualizuje strukturę, plan pozostaje DRAFT', async () => {
|
||||
describe('updatePlan (startDate = planowany start szkicu, bez autoaktywacji)', () => {
|
||||
it('bez startDate: aktualizuje strukturę, start wyzerowany, plan pozostaje DRAFT', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
@@ -1165,37 +1188,34 @@ describe('updatePlan (startDate = aktualizacja + aktywacja)', () => {
|
||||
await updatePlan(prisma, 'p1', 'u1', { title: 't', weeksCount: 1, weeks: [] });
|
||||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||||
where: { id: 'p1' },
|
||||
data: expect.objectContaining({ title: 't' }),
|
||||
data: expect.objectContaining({ title: 't', startDate: null }),
|
||||
});
|
||||
// bez aktywacji — brak wyliczania dat
|
||||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('z startDate: aktualizuje strukturę i aktywuje plan (daty wyliczone)', async () => {
|
||||
it('z startDate: zapisuje planowany start bez aktywacji (brak dat dni)', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
prisma.planWeek.findMany.mockResolvedValue([{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }] }]);
|
||||
tx.trainingPlan.update.mockResolvedValue({});
|
||||
tx.planDay.update.mockResolvedValue({});
|
||||
|
||||
const start = mondayIso(1);
|
||||
const [y, m, d] = start.split('-').map(Number);
|
||||
await updatePlan(prisma, 'p1', 'u1', {
|
||||
const result = await updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: start,
|
||||
});
|
||||
// aktywacja: daty dni + status ACTIVE
|
||||
expect(tx.planDay.update).toHaveBeenCalledWith({
|
||||
where: { id: 'd1' },
|
||||
data: { date: new Date(y, m - 1, d) },
|
||||
});
|
||||
expect(result).toEqual({ ok: true });
|
||||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||||
where: { id: 'p1' },
|
||||
data: { status: 'ACTIVE', startDate: new Date(y, m - 1, d) },
|
||||
data: expect.objectContaining({ title: 't', startDate: new Date(y, m - 1, d) }),
|
||||
});
|
||||
// NIGDY nie aktywujemy: brak dat dni i brak sprawdzania aktywnego planu
|
||||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||||
expect(tx.trainingPlan.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('z startDate nie-poniedziałkiem: 400 (fail-fast, przed aktualizacją)', async () => {
|
||||
@@ -1229,27 +1249,21 @@ describe('updatePlan (startDate = aktualizacja + aktywacja)', () => {
|
||||
).rejects.toMatchObject({ status: 400, message: 'Start date cannot be in the past' });
|
||||
});
|
||||
|
||||
it('z startDate gdy właściciel ma już aktywny plan: struktura zapisana, plan DRAFT (activationSkipped)', async () => {
|
||||
it('z startDate: dni przed dzisiaj względem startu → 400 PLAN_DAY_IN_PAST (przed zapisem)', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
prisma.planWeek.findMany.mockResolvedValue([{ index: 0, days: [{ id: 'd1', dayOfWeek: 1 }] }]);
|
||||
tx.trainingPlan.update.mockResolvedValue({});
|
||||
// W transakcji aktywacji właściciel ma już aktywny plan → konflikt.
|
||||
tx.trainingPlan.findFirst.mockResolvedValue({ id: 'other-active' });
|
||||
const result = await updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: mondayIso(1),
|
||||
});
|
||||
expect(result).toEqual({ ok: true, activationSkipped: true });
|
||||
// Struktura zaktualizowana, ale plan nie został aktywowany (brak dat dni).
|
||||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||||
where: { id: 'p1' },
|
||||
data: expect.objectContaining({ title: 't' }),
|
||||
});
|
||||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||||
const dowToday = ((new Date().getDay() + 6) % 7) + 1;
|
||||
if (dowToday <= 1) return;
|
||||
await expect(
|
||||
updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [{ index: 0, days: [{ dayOfWeek: dowToday - 1, exercises: [] }] }],
|
||||
startDate: mondayIso(0),
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400, code: 'PLAN_DAY_IN_PAST' });
|
||||
expect(tx.trainingPlan.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -695,7 +695,7 @@ export interface PlanBody {
|
||||
/** Informacyjna — siłownia planu; null/brak = bez siłowni. */
|
||||
gymId?: string | null;
|
||||
weeks: PlanWeekInput[];
|
||||
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
|
||||
/** Opcjonalny planowany start (poniedziałek) — szkic; aktywacja osobną akcją. */
|
||||
startDate?: string;
|
||||
/** Edycja planu ACTIVE: wymagana notatka audytowa, gdy coś faktycznie się zmienia. */
|
||||
changeNote?: string;
|
||||
@@ -708,17 +708,11 @@ export interface PlanBody {
|
||||
}
|
||||
|
||||
export function createPlan(body: PlanBody) {
|
||||
return api<{ plan: { id: string }; activationSkipped?: boolean }>('/plans', {
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
return api<{ plan: { id: string } }>('/plans', { method: 'POST', body });
|
||||
}
|
||||
|
||||
export function updatePlan(id: string, body: PlanBody) {
|
||||
return api<{ ok: boolean; activationSkipped?: boolean }>(`/plans/${id}`, {
|
||||
method: 'PATCH',
|
||||
body,
|
||||
});
|
||||
return api<{ ok: boolean }>(`/plans/${id}`, { method: 'PATCH', body });
|
||||
}
|
||||
|
||||
export function deletePlan(id: string) {
|
||||
@@ -1087,17 +1081,17 @@ export function useTraineePlan(userId: string, planId: string) {
|
||||
}
|
||||
|
||||
export function createTraineePlan(userId: string, body: PlanBody) {
|
||||
return api<{ plan: { id: string }; activationSkipped?: boolean }>(
|
||||
`/trainer/trainees/${userId}/plans`,
|
||||
{ method: 'POST', body },
|
||||
);
|
||||
return api<{ plan: { id: string } }>(`/trainer/trainees/${userId}/plans`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
export function updateTraineePlan(userId: string, planId: string, body: PlanBody) {
|
||||
return api<{ ok: boolean; activationSkipped?: boolean }>(
|
||||
`/trainer/trainees/${userId}/plans/${planId}`,
|
||||
{ method: 'PATCH', body },
|
||||
);
|
||||
return api<{ ok: boolean }>(`/trainer/trainees/${userId}/plans/${planId}`, {
|
||||
method: 'PATCH',
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteTraineePlan(userId: string, planId: string) {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CalendarDays, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { formatMonth } from '../../lib/format';
|
||||
import { fmtDate } from '../../lib/format';
|
||||
import { formatMonth, fmtDate } from '../../lib/format';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
function localDayKey(d: Date): string {
|
||||
@@ -10,7 +9,7 @@ function localDayKey(d: Date): string {
|
||||
}
|
||||
|
||||
function parseIsoLocal(iso: string): Date {
|
||||
const [y, m, d] = iso.split('-').map(Number);
|
||||
const [y, m, d] = iso.slice(0, 10).split('-').map(Number);
|
||||
return new Date(y, m - 1, d);
|
||||
}
|
||||
|
||||
@@ -49,7 +48,9 @@ const NAV_BTN =
|
||||
/* Wybór tygodnia startu: kalendarz miesiąca, w którym każdy tydzień (Pn–Nd) jest
|
||||
osobnym wierszem — kliknięcie dowolnego dnia zaznacza CAŁY tydzień (tło w akcencie),
|
||||
a data startu to poniedziałek zaznaczonego tygodnia. Minione tygodnie są zablokowane
|
||||
(start nie może być w przeszłości). Nawigacja miesiącami + skrót „Dziś”. */
|
||||
(start nie może być w przeszłości). Strzałki przesuwają kursor o tydzień i ZAZNACZAJĄ
|
||||
tygodniem docelowym; lewa znika, gdy kursor stoi na minimalnym dostępnym tygodniu
|
||||
(bieżącym). „Ten tydzień” zaznacza bieżący tydzień. */
|
||||
export function WeekPicker({
|
||||
value,
|
||||
onChange,
|
||||
@@ -62,27 +63,31 @@ export function WeekPicker({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const dows = t('weekPicker.dows', { returnObjects: true }) as string[];
|
||||
const now = new Date();
|
||||
const [view, setView] = useState<[number, number]>(() => {
|
||||
if (value) {
|
||||
const [y, m] = value.split('-').map(Number);
|
||||
return [y, m];
|
||||
}
|
||||
return [now.getFullYear(), now.getMonth() + 1];
|
||||
});
|
||||
const [y, m] = view;
|
||||
const currentKey = localDayKey(currentMonday());
|
||||
const valueKey = value ? value.slice(0, 10) : '';
|
||||
const [anchorKey, setAnchorKey] = useState<string>(() =>
|
||||
valueKey ? localDayKey(mondayOf(parseIsoLocal(valueKey))) : currentKey,
|
||||
);
|
||||
|
||||
const shift = (delta: number) => {
|
||||
const d = new Date(y, m - 1 + delta, 1);
|
||||
setView([d.getFullYear(), d.getMonth() + 1]);
|
||||
const anchor = parseIsoLocal(anchorKey);
|
||||
// Miesiąc siatki = miesiąc czwartku tygodnia-kotwicy (tygodnie przekraczające
|
||||
// granicę miesiąca mają stabilny miesiąc widoku).
|
||||
const viewDay = addDaysLocal(anchor, 3);
|
||||
const vy = viewDay.getFullYear();
|
||||
const vm = viewDay.getMonth() + 1;
|
||||
|
||||
const selectWeek = (weekKey: string) => {
|
||||
setAnchorKey(weekKey);
|
||||
onChange(weekKey);
|
||||
};
|
||||
const goToday = () => setView([now.getFullYear(), now.getMonth() + 1]);
|
||||
const moveWeek = (deltaWeeks: number) =>
|
||||
selectWeek(localDayKey(addDaysLocal(anchor, deltaWeeks * 7)));
|
||||
|
||||
// Monday-first grid: 6 pełnych wierszy tygodni (42 dni) — każdy wiersz to
|
||||
// jednostka wyboru (cały tydzień).
|
||||
const firstDay = new Date(y, m - 1, 1);
|
||||
const firstDay = new Date(vy, vm - 1, 1);
|
||||
const startOffset = (firstDay.getDay() + 6) % 7;
|
||||
const gridStart = new Date(y, m - 1, 1 - startOffset);
|
||||
const gridStart = new Date(vy, vm - 1, 1 - startOffset);
|
||||
const rows: Date[][] = [];
|
||||
for (let wi = 0; wi < 6; wi++) {
|
||||
const row: Date[] = [];
|
||||
@@ -94,8 +99,11 @@ export function WeekPicker({
|
||||
rows.push(row);
|
||||
}
|
||||
|
||||
const selMondayKey = value ? localDayKey(mondayOf(parseIsoLocal(value))) : null;
|
||||
const todayKey = localDayKey(now);
|
||||
const selMondayKey = valueKey ? localDayKey(mondayOf(parseIsoLocal(valueKey))) : null;
|
||||
const todayKey = localDayKey(new Date());
|
||||
// Klucz YYYY-MM-DD porównuje się leksykalnie — kursor można cofnąć dopiero
|
||||
// powyżej minimalnego (bieżącego) tygodnia.
|
||||
const canGoBack = anchorKey > currentKey;
|
||||
|
||||
return (
|
||||
<div className={cn('w-full', className)}>
|
||||
@@ -103,29 +111,31 @@ export function WeekPicker({
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<CalendarDays className="h-5 w-5 shrink-0 text-accent" aria-hidden="true" />
|
||||
<span className="truncate text-[1.125rem] font-bold sm:text-[1.25rem]">
|
||||
{formatMonth(`${y}-${String(m).padStart(2, '0')}`)}
|
||||
{formatMonth(`${vy}-${String(vm).padStart(2, '0')}`)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{canGoBack && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => moveWeek(-1)}
|
||||
aria-label={t('weekPicker.prevWeek')}
|
||||
className={NAV_BTN}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => shift(-1)}
|
||||
aria-label={t('topbar.prevMonth')}
|
||||
className={NAV_BTN}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={goToday}
|
||||
onClick={() => selectWeek(currentKey)}
|
||||
className={cn(NAV_BTN, 'px-3 text-[0.875rem] font-semibold')}
|
||||
>
|
||||
{t('weekPicker.today')}
|
||||
{t('weekPicker.thisWeek')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => shift(1)}
|
||||
aria-label={t('topbar.nextMonth')}
|
||||
onClick={() => moveWeek(1)}
|
||||
aria-label={t('weekPicker.nextWeek')}
|
||||
className={NAV_BTN}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
@@ -154,14 +164,14 @@ export function WeekPicker({
|
||||
)}
|
||||
>
|
||||
{row.map((d, i) => {
|
||||
const inMonth = d.getMonth() === m - 1;
|
||||
const inMonth = d.getMonth() === vm - 1;
|
||||
const isToday = localDayKey(d) === todayKey;
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
disabled={past}
|
||||
onClick={() => onChange(weekKey)}
|
||||
onClick={() => selectWeek(weekKey)}
|
||||
aria-pressed={sel}
|
||||
className={cn(
|
||||
'h-12 text-center text-[0.9rem] tabular-nums transition-colors max-md:h-11',
|
||||
@@ -183,11 +193,11 @@ export function WeekPicker({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{value && (
|
||||
{valueKey && (
|
||||
<p className="mt-2 text-dim text-[0.8rem]">
|
||||
{t('weekPicker.startWeek', {
|
||||
from: fmtDate(value),
|
||||
to: fmtDate(localDayKey(addDaysLocal(parseIsoLocal(value), 6))),
|
||||
from: fmtDate(valueKey),
|
||||
to: fmtDate(localDayKey(addDaysLocal(parseIsoLocal(valueKey), 6))),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -58,7 +58,9 @@
|
||||
"dows": ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
|
||||
"groupAria": "Start week selection",
|
||||
"startWeek": "Start: week {{from}} – {{to}}",
|
||||
"today": "Today"
|
||||
"thisWeek": "This week",
|
||||
"prevWeek": "Previous week",
|
||||
"nextWeek": "Next week"
|
||||
},
|
||||
"weekShort": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
|
||||
"fmt": {
|
||||
|
||||
@@ -71,6 +71,7 @@
|
||||
"lastSession": "Last session:",
|
||||
"dayPickerAria": "Training days",
|
||||
"dayHistoryAria": "day with training history",
|
||||
"dayPastAria": "day in the past — cannot be scheduled",
|
||||
"wheelMode": "Scroll",
|
||||
"manualMode": "Type",
|
||||
"wheelModeGroupAria": "Value input method",
|
||||
@@ -85,7 +86,6 @@
|
||||
"length": "Length (weeks)",
|
||||
"gym": "Gym",
|
||||
"noGym": "No gym",
|
||||
"activateHint": "Optionally mark the start week — the plan is activated right away (start = Monday of the marked week).",
|
||||
"startDateLockedHint": "This plan is in progress — its start date cannot change.",
|
||||
"changeNoteLabel": "Change note",
|
||||
"changeNotePlaceholder": "What you change in the in-progress plan and why",
|
||||
@@ -132,10 +132,10 @@
|
||||
"sumMirror": "mirrors week 1",
|
||||
"weeksMismatch": "The plan has {{count}} weeks — define them all",
|
||||
"emptyDayError": "Week {{week}}: {{day}} has no exercises — add exercises or remove the day",
|
||||
"draftCreatedOwn": "Plan created as a draft — you already have an active plan, activation skipped",
|
||||
"draftSavedOwn": "Plan saved as a draft — you already have an active plan, activation skipped",
|
||||
"draftCreatedTrainee": "Plan created as a draft — the trainee already has an active plan, activation skipped",
|
||||
"draftSavedTrainee": "Plan saved as a draft — the trainee already has an active plan, activation skipped",
|
||||
"pastDayError": "Week {{week}}: {{day}} falls in the past — remove this day or change the start week",
|
||||
"pastDayTitle": "That day has already passed",
|
||||
"pastDayDesc": "The plan has a start week marked, and {{day}} of week {{week}} falls before today. A training cannot be scheduled in the past — pick another day or change the start week.",
|
||||
"pastDayOk": "Got it",
|
||||
"saveError": "Save error",
|
||||
"noGymTrainee": "The trainee does not belong to any gym.",
|
||||
"noGymOwn": "You do not belong to any gym.",
|
||||
|
||||
@@ -58,7 +58,9 @@
|
||||
"dows": ["Pn", "Wt", "Śr", "Cz", "Pt", "So", "Nd"],
|
||||
"groupAria": "Wybór tygodnia startu",
|
||||
"startWeek": "Start: tydzień {{from}} – {{to}}",
|
||||
"today": "Dziś"
|
||||
"thisWeek": "Ten tydzień",
|
||||
"prevWeek": "Poprzedni tydzień",
|
||||
"nextWeek": "Następny tydzień"
|
||||
},
|
||||
"weekShort": ["Pon", "Wt", "Śr", "Czw", "Pt", "Sob", "Niedz"],
|
||||
"fmt": {
|
||||
|
||||
@@ -71,6 +71,7 @@
|
||||
"lastSession": "Ostatnia sesja:",
|
||||
"dayPickerAria": "Dni treningowe",
|
||||
"dayHistoryAria": "dzień z historią treningów",
|
||||
"dayPastAria": "dzień w przeszłości — nie można zaplanować",
|
||||
"wheelMode": "Przewijaj",
|
||||
"manualMode": "Wpisz",
|
||||
"wheelModeGroupAria": "Sposób wprowadzania wartości",
|
||||
@@ -85,7 +86,6 @@
|
||||
"length": "Długość (tygodnie)",
|
||||
"gym": "Siłownia",
|
||||
"noGym": "Bez siłowni",
|
||||
"activateHint": "Opcjonalnie zaznacz tydzień startu — plan zostanie od razu aktywowany (start = poniedziałek zaznaczonego tygodnia).",
|
||||
"startDateLockedHint": "Plan jest realizowany — data startu jest niezmienna.",
|
||||
"changeNoteLabel": "Notatka o zmianach",
|
||||
"changeNotePlaceholder": "Co i dlaczego zmieniasz w realizowanym planie",
|
||||
@@ -132,10 +132,10 @@
|
||||
"sumMirror": "odzwierciedla tyg. 1",
|
||||
"weeksMismatch": "Plan ma {{count}} tygodni — zdefiniuj je wszystkie",
|
||||
"emptyDayError": "Tydzień {{week}}: dzień {{day}} nie ma ćwiczeń — dodaj ćwiczenia lub usuń dzień",
|
||||
"draftCreatedOwn": "Plan utworzony jako szkic — masz już aktywny plan, aktywacja pominięta",
|
||||
"draftSavedOwn": "Plan zapisany jako szkic — masz już aktywny plan, aktywacja pominięta",
|
||||
"draftCreatedTrainee": "Plan utworzony jako szkic — podopieczny ma już aktywny plan, aktywacja pominięta",
|
||||
"draftSavedTrainee": "Plan zapisany jako szkic — podopieczny ma już aktywny plan, aktywacja pominięta",
|
||||
"pastDayError": "Tydzień {{week}}: dzień {{day}} wypada w przeszłości — usuń ten dzień lub zmień tydzień startu",
|
||||
"pastDayTitle": "Ten dzień już minął",
|
||||
"pastDayDesc": "Plan ma zaznaczony start, a {{day}} w tygodniu {{week}} wypada przed dzisiaj. Trening nie może być zaplanowany w przeszłości — wybierz inny dzień albo zmień tydzień startu.",
|
||||
"pastDayOk": "Rozumiem",
|
||||
"saveError": "Błąd zapisu",
|
||||
"noGymTrainee": "Podopieczny nie należy do żadnej siłowni.",
|
||||
"noGymOwn": "Nie należysz do żadnej siłowni.",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
@@ -53,6 +53,17 @@ export default function PlanDetail() {
|
||||
|
||||
const planData = data?.plan;
|
||||
const [shareOpen, setShareOpen] = useState(false);
|
||||
// Szkic zapisany z zaznaczonym tygodniem startu — picker preuzupełnia planowany
|
||||
// start (jednorazowo, żeby nie nadpisywać ręcznej zmiany użytkownika).
|
||||
const startPrefilled = useRef(false);
|
||||
useEffect(() => {
|
||||
if (startPrefilled.current) return;
|
||||
const s = planData?.status === 'DRAFT' ? planData.startDate : null;
|
||||
if (s) {
|
||||
startPrefilled.current = true;
|
||||
setStartDate(String(s).slice(0, 10));
|
||||
}
|
||||
}, [planData]);
|
||||
// Właściciel = pełne prawa; trener z ACTIVE coachingiem = zarządza (bez sharingu);
|
||||
// odbiorca share'a = read-only (canManage z detalu; fallback: właściciel).
|
||||
const isOwner = !!planData && !!meData && planData.userId === meData.user.id;
|
||||
|
||||
@@ -38,7 +38,7 @@ import { dayName, dayNameAcc, parseLoadInput } from '../../lib/format';
|
||||
import { dayCountLabel, exerciseCountLabel } from '../../lib/labels';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import { displayedDaysOf, type EditorDay, type EditorWeek } from './plan-editor/types';
|
||||
import { usePlanEditorState } from './plan-editor/usePlanEditorState';
|
||||
import { plannedDayPast, usePlanEditorState } from './plan-editor/usePlanEditorState';
|
||||
import { PlanMetaForm } from './plan-editor/PlanMetaForm';
|
||||
import { PlanSummary } from './plan-editor/PlanSummary';
|
||||
import { WeekPanel } from './plan-editor/WeekPanel';
|
||||
@@ -165,7 +165,8 @@ export default function PlanEditor() {
|
||||
|
||||
// Walidacja kroku 1 (potrzebna w akcji topbar — przed useTopbar):
|
||||
// pusty tytuł lub tydzień startu w przeszłości blokują „Dalej”. Krok 2 → 3 zawsze.
|
||||
// Tydzień startu walidowany w obu trybach (edycja = aktualizacja + aktywacja).
|
||||
// Tydzień startu walidowany w obu trybach (zapis NIGDY nie aktywuje — start to
|
||||
// plan szkicu; aktywacja osobną akcją na ekranie planu).
|
||||
const startWeekError =
|
||||
!isPlanActive && editor.startDate && isPastWeek(editor.startDate)
|
||||
? t('wizard.startWeekError')
|
||||
@@ -258,6 +259,8 @@ export default function PlanEditor() {
|
||||
const [shrinkReq, setShrinkReq] = useState<{ n: number } | null>(null);
|
||||
const [forceRemoveDays, setForceRemoveDays] = useState(false);
|
||||
const [titleTouched, setTitleTouched] = useState(false);
|
||||
// Klik w dzień, którego data (od zaznaczonego startu) już minęła — wyjaśnienie w modalu.
|
||||
const [pastDayReq, setPastDayReq] = useState<{ wi: number; dow: number } | null>(null);
|
||||
// Notatka audytowa (edycja planu ACTIVE) — opcjonalna; brak = historia bez „dlaczego”
|
||||
const [changeNote, setChangeNoteState] = useState('');
|
||||
|
||||
@@ -346,6 +349,22 @@ export default function PlanEditor() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Start zaznaczony: dzień, który wypada w przeszłości (tydzień już się rozpoczął),
|
||||
// nie może być treningiem — skocz do niego (usuń dzień lub zmień tydzień startu).
|
||||
if (!isPlanActive && editor.startDate) {
|
||||
for (let wi = 0; wi < editor.weeks.length; wi++) {
|
||||
const past = displayedDaysOf(editor.weeks, wi).find((d) =>
|
||||
plannedDayPast(editor.startDate, wi, d.dayOfWeek),
|
||||
);
|
||||
if (past) {
|
||||
push(t('wizard.pastDayError', { week: wi + 1, day: dayName(past.dayOfWeek) }), 'error');
|
||||
setStep(2);
|
||||
setActiveWeek(wi);
|
||||
setActiveDow(past.dayOfWeek);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Plan w trakcie realizacji: notatka audytowa opcjonalna (trafia do historii planu).
|
||||
// Id wierszy z bazy wysyłamy tylko dla tygodni, do których faktycznie należą
|
||||
// (lustro/kopia tygodnia 1 to nowe wiersze — bez id).
|
||||
@@ -382,8 +401,8 @@ export default function PlanEditor() {
|
||||
// Dzień z historią usunięty za potwierdzeniem „Usuń mimo historii” — backend
|
||||
// soft-remuje go (removedAt), historia sesji/serii zostaje w bazie.
|
||||
if (isPlanActive && forceRemoveDays) body.forceRemoveDays = true;
|
||||
// Data startu w obu trybach — przy tworzeniu: plan tworzony i aktywowany w jednym
|
||||
// kroku; przy edycji (DRAFT): zapis = aktualizacja struktury + aktywacja.
|
||||
// Data startu w obu trybach — plan ZAWSZE pozostaje szkicem; zaznaczony tydzień
|
||||
// to planowany start (daty dni wyliczane przy aktywacji „Aktywuj”).
|
||||
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
|
||||
// Plan ACTIVE ma start niezmienny — nie wysyłamy go wcale.
|
||||
if (!isPlanActive && editor.startDate) {
|
||||
@@ -395,37 +414,17 @@ export default function PlanEditor() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
let activationSkipped = false;
|
||||
let targetPath = `/plans/${planIdParam}`;
|
||||
if (isTraineeMode) {
|
||||
const res = isEdit
|
||||
? await updateTraineePlan(traineeUserId, planIdParam, body)
|
||||
: await createTraineePlan(traineeUserId, body);
|
||||
activationSkipped = !!res.activationSkipped;
|
||||
if (!isEdit) await createTraineePlan(traineeUserId, body);
|
||||
else await updateTraineePlan(traineeUserId, planIdParam, body);
|
||||
targetPath = backPath;
|
||||
} else if (isEdit) {
|
||||
const res = await updatePlan(planIdParam, body);
|
||||
activationSkipped = !!res.activationSkipped;
|
||||
await updatePlan(planIdParam, body);
|
||||
} else {
|
||||
const res = await createPlan(body);
|
||||
activationSkipped = !!res.activationSkipped;
|
||||
targetPath = `/plans/${res.plan.id}`;
|
||||
}
|
||||
// Zapis utworzył plan, ale aktywacja była niemożliwa (właściciel ma już aktywny plan).
|
||||
if (activationSkipped) {
|
||||
push(
|
||||
t(
|
||||
isEdit
|
||||
? isTraineeMode
|
||||
? 'wizard.draftSavedTrainee'
|
||||
: 'wizard.draftSavedOwn'
|
||||
: isTraineeMode
|
||||
? 'wizard.draftCreatedTrainee'
|
||||
: 'wizard.draftCreatedOwn',
|
||||
),
|
||||
'info',
|
||||
);
|
||||
}
|
||||
navigate(targetPath);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.code === 'PLAN_DAY_HAS_HISTORY') {
|
||||
@@ -441,6 +440,19 @@ export default function PlanEditor() {
|
||||
setStep(2);
|
||||
if (d.weekIndex != null) setActiveWeek(d.weekIndex);
|
||||
if (d.dayOfWeek != null) setActiveDow(d.dayOfWeek);
|
||||
} else if (err instanceof ApiError && err.code === 'PLAN_DAY_IN_PAST') {
|
||||
// Zapasowy guard (wyścig: tydzień „przecieka” przez minione doby): skocz do dnia.
|
||||
const d = (err.body?.error?.details ?? {}) as { weekIndex?: number; dayOfWeek?: number };
|
||||
push(
|
||||
t('wizard.pastDayError', {
|
||||
week: (d.weekIndex ?? 0) + 1,
|
||||
day: d.dayOfWeek != null ? dayName(d.dayOfWeek) : '',
|
||||
}),
|
||||
'error',
|
||||
);
|
||||
setStep(2);
|
||||
if (d.weekIndex != null) setActiveWeek(d.weekIndex);
|
||||
if (d.dayOfWeek != null) setActiveDow(d.dayOfWeek);
|
||||
} else {
|
||||
push(err instanceof Error ? err.message : t('wizard.saveError'), 'error');
|
||||
}
|
||||
@@ -491,6 +503,14 @@ export default function PlanEditor() {
|
||||
const weekSummaryActive = weekSummary(activeWi, week, weekDays);
|
||||
// Lustrzany tydzień (2+ nieodłączony): panel pokazuje podgląd + jawne odłączenie zamiast edytora
|
||||
const mirrored = activeWi > 0 && !week.detached;
|
||||
// Dni aktywnego tygodnia, które przy zaznaczonym starcie planu (szkic) wypadają
|
||||
// w przeszłości — nie da się ich dodać; klik otwiera wyjaśnienie w modalu.
|
||||
const pastDows =
|
||||
!isPlanActive && editor.startDate
|
||||
? new Set(
|
||||
[1, 2, 3, 4, 5, 6, 7].filter((dow) => plannedDayPast(editor.startDate, activeWi, dow)),
|
||||
)
|
||||
: undefined;
|
||||
// Źródła „Kopiuj z…” — każdy inny tydzień z podsumowaniem jego wyświetlanej treści
|
||||
const copySources = editor.weeks.flatMap((w, wi) => {
|
||||
if (wi === activeWi) return [];
|
||||
@@ -549,6 +569,10 @@ export default function PlanEditor() {
|
||||
// forceRemoveDays; niepusty bez historii → jawne potwierdzenie nadpisania; pusty → od razu
|
||||
const applyDayCopy = (srcWi: number, srcDow: number) => {
|
||||
if (effDow == null) return;
|
||||
if (!isPlanActive && editor.startDate && plannedDayPast(editor.startDate, activeWi, effDow)) {
|
||||
setPastDayReq({ wi: activeWi, dow: effDow });
|
||||
return;
|
||||
}
|
||||
const targetDay = weekDays.find((d) => d.dayOfWeek === effDow);
|
||||
if (isPlanActive && targetDay?.hasHistory) {
|
||||
setDayCopyReq({ targetDow: effDow, srcWi, srcDow });
|
||||
@@ -708,12 +732,14 @@ export default function PlanEditor() {
|
||||
? new Set(historyDaysOf(activeWi).map((d) => d.dayOfWeek))
|
||||
: undefined
|
||||
}
|
||||
pastDows={pastDows}
|
||||
onAddDay={(dow) => {
|
||||
editor.addDay(activeWi, dow);
|
||||
// teraz, gdy dni są podzakładkami — wyląduj na nowo dodanym dniu
|
||||
setActiveDow(dow);
|
||||
}}
|
||||
onSelectDay={(dow) => setActiveDow(dow)}
|
||||
onPastDay={(dow) => setPastDayReq({ wi: activeWi, dow })}
|
||||
/>
|
||||
|
||||
{weekDays.length === 0 && (
|
||||
@@ -1025,6 +1051,24 @@ export default function PlanEditor() {
|
||||
confirmLabel={t('wizard.shrinkWeeksLockedLabel')}
|
||||
danger
|
||||
/>
|
||||
{/* Klik w dzień, który przy zaznaczonym starcie wypada w przeszłości:
|
||||
wyjaśnienie (nie decyzja) — dzień nie zostaje dodany. */}
|
||||
<Modal
|
||||
open={pastDayReq !== null}
|
||||
onClose={() => setPastDayReq(null)}
|
||||
title={t('wizard.pastDayTitle')}
|
||||
handle
|
||||
>
|
||||
<p className="text-dim text-[0.875rem]">
|
||||
{t('wizard.pastDayDesc', {
|
||||
day: pastDayReq ? dayName(pastDayReq.dow) : '',
|
||||
week: pastDayReq ? pastDayReq.wi + 1 : 0,
|
||||
})}
|
||||
</p>
|
||||
<Button className="mt-4 w-full" onClick={() => setPastDayReq(null)}>
|
||||
{t('wizard.pastDayOk')}
|
||||
</Button>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,22 +9,31 @@ import type { EditorDay } from './types';
|
||||
wymaga świadomej zgody, historia zostaje).
|
||||
Klik w szarą komórkę = dodaj dzień; klik w pomarańczową = przenieś edytor na ten
|
||||
dzień (siatka NIGDY nie usuwa — usuwanie to kosze w nagłówku dnia w PlanEditor).
|
||||
Dzień edytowany: pierścień + aria-current, odróżnia go od zwykłego pomarańczowego. */
|
||||
Dzień edytowany: pierścień + aria-current, odróżnia go od zwykłego pomarańczowego.
|
||||
Dzień, który już minął (plan z zaznaczonym startem, w którym ten dzień wypada
|
||||
w przeszłości): nie da się go DODAĆ — klik otwiera wyjaśnienie (onPastDay);
|
||||
jeśli dzień już istnieje, zostaje klikalny, żeby dało się go edytować/usunąć. */
|
||||
export function DayPicker({
|
||||
days,
|
||||
lockedDows,
|
||||
pastDows,
|
||||
activeDow,
|
||||
onAddDay,
|
||||
onSelectDay,
|
||||
onPastDay,
|
||||
}: {
|
||||
days: EditorDay[];
|
||||
/** Dni z historią treningową — sygnalizowane kłódką. */
|
||||
lockedDows?: Set<number>;
|
||||
/** Dni, których data (od startu planu) już minęła — nie do dodania. */
|
||||
pastDows?: Set<number>;
|
||||
/** Edytowany dzień — wyróżniony pierścieniem (aria-current). */
|
||||
activeDow: number | null;
|
||||
onAddDay: (dow: number) => void;
|
||||
/** Przełącza edytor na dzień już w planie (nie usuwa go). */
|
||||
onSelectDay: (dow: number) => void;
|
||||
/** Klik w nieistniejący dzień z miniona datą — wyjaśnienie zamiast dodania. */
|
||||
onPastDay?: (dow: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation('plans');
|
||||
return (
|
||||
@@ -34,18 +43,34 @@ export function DayPicker({
|
||||
const selected = !!day;
|
||||
const active = selected && dow === activeDow;
|
||||
const locked = selected && !!lockedDows?.has(dow);
|
||||
const past = !selected && !!pastDows?.has(dow);
|
||||
return (
|
||||
<button
|
||||
key={dow}
|
||||
type="button"
|
||||
aria-pressed={selected}
|
||||
aria-current={active ? 'true' : undefined}
|
||||
aria-label={locked ? `${dayName(dow)} — ${t('editor.dayHistoryAria')}` : dayName(dow)}
|
||||
onClick={() => (selected ? onSelectDay(dow) : onAddDay(dow))}
|
||||
aria-label={
|
||||
locked
|
||||
? `${dayName(dow)} — ${t('editor.dayHistoryAria')}`
|
||||
: past
|
||||
? `${dayName(dow)} — ${t('editor.dayPastAria')}`
|
||||
: dayName(dow)
|
||||
}
|
||||
onClick={() => {
|
||||
if (past) {
|
||||
onPastDay?.(dow);
|
||||
return;
|
||||
}
|
||||
if (selected) onSelectDay(dow);
|
||||
else onAddDay(dow);
|
||||
}}
|
||||
className={`relative min-h-11 rounded-[10px] text-[0.8rem] font-semibold border transition-colors cursor-pointer ${
|
||||
selected
|
||||
? 'bg-accent text-accent-ink border-accent'
|
||||
: 'bg-input border-line text-dim hover:border-accent hover:text-accent-text'
|
||||
: past
|
||||
? 'bg-input/50 border-line text-dim/50 line-through decoration-dim/60'
|
||||
: 'bg-input border-line text-dim hover:border-accent hover:text-accent-text'
|
||||
}${active ? ' ring-2 ring-accent ring-offset-2 ring-offset-card' : ''}`}
|
||||
>
|
||||
{dayName(dow).slice(0, 3)}
|
||||
|
||||
@@ -69,7 +69,16 @@ export function PlanMetaForm({
|
||||
placeholder={t('meta.titlePlaceholder')}
|
||||
aria-invalid={titleError ? true : undefined}
|
||||
/>
|
||||
{titleError && <ErrorText>{titleError}</ErrorText>}
|
||||
{/* Rezerwa miejsca na błąd: przy autofocusie pierwszy klik poza polem
|
||||
rozmywa tytuł i wstawia komunikat — bez rezerwy treść poniżej przeskakuje
|
||||
między mousedown a mouseup i pierwszy klik „przepada”. */}
|
||||
{titleError ? (
|
||||
<ErrorText>{titleError}</ErrorText>
|
||||
) : (
|
||||
<div className="mt-2 text-[0.9rem]" aria-hidden="true">
|
||||
|
||||
</div>
|
||||
)}
|
||||
</Field>
|
||||
<Field
|
||||
label={t('meta.length')}
|
||||
@@ -145,10 +154,6 @@ export function PlanMetaForm({
|
||||
<ErrorText>{startWeekError}</ErrorText>
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-4 flex items-start gap-2 text-dim text-[0.875rem]">
|
||||
<Info className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
{t('meta.activateHint')}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
@@ -23,6 +23,23 @@ export interface PlanLike {
|
||||
weeks: Parameters<typeof weekFromApi>[0][];
|
||||
}
|
||||
|
||||
/**
|
||||
* Czy planowany dzień tygodnia `wi` (dzień tygodnia `dow`) przy zaznaczonym
|
||||
* starcie wypada PRZED dzisiaj. Pilnuje logiki przeszłości w edytorze: dni takie
|
||||
* nie mogą być treningami — bieżący tydzień startu ma minione dni, a kopia
|
||||
* przyszłego tygodnia do minionego musi je pominąć (inaczej przyszły poniedziałek
|
||||
* źródła „przeskakuje” w przeszłość celu).
|
||||
*/
|
||||
export function plannedDayPast(startDate: string, wi: number, dow: number): boolean {
|
||||
if (!startDate) return false;
|
||||
const [y, m, d] = startDate.slice(0, 10).split('-').map(Number);
|
||||
if (!y || !m || !d) return false;
|
||||
const dt = new Date(y, m - 1, d + wi * 7 + (dow - 1));
|
||||
const now = new Date();
|
||||
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
return dt < today;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cały stan edytora planu + akcje mutacji. PlanEditor zostaje cienki:
|
||||
* dane query + layout + save. Flaga `dirty` (porównanie z snapshotem
|
||||
@@ -53,7 +70,8 @@ export function usePlanEditorState() {
|
||||
/** Inicjalizacja trybu edycji po załadowaniu danych (zamiast setState during render). */
|
||||
const initFromPlan = useCallback((plan: PlanLike) => {
|
||||
const loaded = plan.weeks.map((w) => weekFromApi(w));
|
||||
const loadedStart = plan.startDate ?? '';
|
||||
// API zwraca Date (ISO) albo date-only — edytor operuje na kluczu YYYY-MM-DD.
|
||||
const loadedStart = plan.startDate ? String(plan.startDate).slice(0, 10) : '';
|
||||
setTitleState(plan.title);
|
||||
setStartDateState(loadedStart);
|
||||
setWeeksCountState(plan.weeksCount);
|
||||
@@ -288,60 +306,81 @@ export function usePlanEditorState() {
|
||||
);
|
||||
|
||||
/** Kopiowanie dni z dowolnego tygodnia (nie tylko poprzedniego): źródło lustrzane
|
||||
rozwiązuje się przez `displayedDaysOf`, cel zostaje odłączony; aliasu nie kopiujemy. */
|
||||
const copyFromWeek = useCallback((wi: number, srcWi: number) => {
|
||||
setWeeks((ws) => {
|
||||
if (wi === srcWi || !ws[wi] || !ws[srcWi]) return ws;
|
||||
const srcDays = displayedDaysOf(ws, srcWi);
|
||||
return ws.map((w, i) =>
|
||||
i === wi
|
||||
? {
|
||||
days: withoutIds(structuredClone(srcDays)),
|
||||
detached: true,
|
||||
customName: w.customName,
|
||||
}
|
||||
: w,
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
rozwiązuje się przez `displayedDaysOf`, cel zostaje odłączony; aliasu nie kopiujemy.
|
||||
Dni, które w celu wypadałyby w przeszłości (start zaznaczony), są pomijane —
|
||||
kopia tygodnia przyszłego do bieżącego nie może przenieść treningów „wstecz”. */
|
||||
const copyFromWeek = useCallback(
|
||||
(wi: number, srcWi: number) => {
|
||||
setWeeks((ws) => {
|
||||
if (wi === srcWi || !ws[wi] || !ws[srcWi]) return ws;
|
||||
const srcDays = displayedDaysOf(ws, srcWi).filter(
|
||||
(d) => !plannedDayPast(startDate, wi, d.dayOfWeek),
|
||||
);
|
||||
return ws.map((w, i) =>
|
||||
i === wi
|
||||
? {
|
||||
days: withoutIds(structuredClone(srcDays)),
|
||||
detached: true,
|
||||
customName: w.customName,
|
||||
}
|
||||
: w,
|
||||
);
|
||||
});
|
||||
},
|
||||
[startDate],
|
||||
);
|
||||
|
||||
/** Kopiowanie zawartości pojedynczego dnia (stepper „Kopiuj dzień z…”): bieżący dzień
|
||||
tygodnia `wi` przejmuje ćwiczenia i serie dnia `srcDow` z tygodnia `srcWi`
|
||||
(źródło lustrzane rozwiązane przez `displayedDaysOf`), zostając pod swoim
|
||||
`targetDow`; kopia bez id wierszy, tydzień docelowy odłączony. */
|
||||
const copyDayTo = useCallback((wi: number, targetDow: number, srcWi: number, srcDow: number) => {
|
||||
setWeeks((ws) => {
|
||||
if (!ws[wi] || !ws[srcWi]) return ws;
|
||||
if (wi === srcWi && targetDow === srcDow) return ws;
|
||||
const src = displayedDaysOf(ws, srcWi).find((d) => d.dayOfWeek === srcDow);
|
||||
if (!src) return ws;
|
||||
const clone: EditorDay = withoutIds([structuredClone(src)])[0];
|
||||
clone.dayOfWeek = targetDow;
|
||||
return ws.map((w, i) => {
|
||||
if (i !== wi) return w;
|
||||
const days: EditorDay[] = w.days.filter((d) => d.dayOfWeek !== targetDow);
|
||||
days.push(clone);
|
||||
days.sort((a, b) => a.dayOfWeek - b.dayOfWeek);
|
||||
return { days, detached: true, customName: w.customName };
|
||||
const copyDayTo = useCallback(
|
||||
(wi: number, targetDow: number, srcWi: number, srcDow: number) => {
|
||||
// Cel w przeszłości = kopia bezsensowna (dzień minął) — brak zmian; UI
|
||||
// blokuje takie kliknięcia, to zabezpieczenie dla pozostałych ścieżek.
|
||||
if (plannedDayPast(startDate, wi, targetDow)) return;
|
||||
setWeeks((ws) => {
|
||||
if (!ws[wi] || !ws[srcWi]) return ws;
|
||||
if (wi === srcWi && targetDow === srcDow) return ws;
|
||||
const src = displayedDaysOf(ws, srcWi).find((d) => d.dayOfWeek === srcDow);
|
||||
if (!src) return ws;
|
||||
const clone: EditorDay = withoutIds([structuredClone(src)])[0];
|
||||
clone.dayOfWeek = targetDow;
|
||||
return ws.map((w, i) => {
|
||||
if (i !== wi) return w;
|
||||
const days: EditorDay[] = w.days.filter((d) => d.dayOfWeek !== targetDow);
|
||||
days.push(clone);
|
||||
days.sort((a, b) => a.dayOfWeek - b.dayOfWeek);
|
||||
return { days, detached: true, customName: w.customName };
|
||||
});
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
},
|
||||
[startDate],
|
||||
);
|
||||
|
||||
/** Jawne odłączenie lustrzanego tygodnia: kopia dni z tygodnia 1 + `detached`.
|
||||
Tydzień 1 i już odłączone — bez zmian (bezpieczne nb. auto-detach w `editWeek`). */ const detachWeek =
|
||||
useCallback((wi: number) => {
|
||||
Tydzień 1 i już odłączone — bez zmian (bezpieczne nb. auto-detach w `editWeek`).
|
||||
Dni, które w odłączanym tygodniu wypadałyby w przeszłości — pomijane. */
|
||||
const detachWeek = useCallback(
|
||||
(wi: number) => {
|
||||
setWeeks((ws) =>
|
||||
ws.map((w, i) =>
|
||||
i === wi && i > 0 && !w.detached
|
||||
? {
|
||||
days: withoutIds(structuredClone(ws[0].days)),
|
||||
days: withoutIds(
|
||||
structuredClone(
|
||||
ws[0].days.filter((d) => !plannedDayPast(startDate, i, d.dayOfWeek)),
|
||||
),
|
||||
),
|
||||
detached: true,
|
||||
customName: w.customName,
|
||||
}
|
||||
: w,
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
},
|
||||
[startDate],
|
||||
);
|
||||
|
||||
const clearWeek = useCallback(
|
||||
(wi: number) =>
|
||||
|
||||
@@ -247,6 +247,33 @@ describe('PlanDetail — udostępnianie planów (WP4)', () => {
|
||||
expect(screen.getByText('Tydzień startu')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('szkic z planowanym startem: picker preuzupełnia tydzień, „Aktywuj” aktywny od razu', async () => {
|
||||
const now = new Date();
|
||||
const mon = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
mon.setDate(mon.getDate() - ((mon.getDay() + 6) % 7) + 7); // poniedziałek przyszłego tygodnia
|
||||
const key = `${mon.getFullYear()}-${String(mon.getMonth() + 1).padStart(2, '0')}-${String(
|
||||
mon.getDate(),
|
||||
).padStart(2, '0')}`;
|
||||
const draft = planDetail({ startDate: `${key}T00:00:00.000Z` });
|
||||
mockApi({}, { user: OWNER, plans: [draft], plan: draft });
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenPlans(user, OWNER.email);
|
||||
|
||||
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
|
||||
|
||||
// zapisany planowany start widoczny jako podsum tygodnia…
|
||||
const sun = new Date(mon);
|
||||
sun.setDate(mon.getDate() + 6);
|
||||
const fmt = (d: Date) =>
|
||||
`${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}.${d.getFullYear()}`;
|
||||
expect(await screen.findByText(`Start: tydzień ${fmt(mon)} – ${fmt(sun)}`)).toBeInTheDocument();
|
||||
// …i „Aktywuj” w topmenu jest aktywny bez ręcznego zaznaczania tygodnia
|
||||
const header = document.querySelector('header')!;
|
||||
expect(within(header).getByRole('button', { name: 'Aktywuj' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('odbiorca share’a: sekcja „Udostępnione mi”, plan read-only (bez akcji i bez tygodnia startu)', async () => {
|
||||
const shared = planDetail({
|
||||
canManage: false,
|
||||
|
||||
@@ -185,18 +185,16 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
|
||||
// wybór tygodnia startu jest widoczny w trybie tworzenia
|
||||
expect(screen.getByRole('group', { name: 'Wybór tygodnia startu' })).toBeInTheDocument();
|
||||
|
||||
// 20. dzień bieżącego miesiąca może być w minionym tygodniu (zablokowany) —
|
||||
// wybieramy 20. dzień następnego miesiąca (unikalny w siatce, zawsze przyszły tydzień)
|
||||
await user.click(screen.getByRole('button', { name: 'Następny miesiąc' }));
|
||||
await user.click(screen.getByRole('button', { name: '20' }));
|
||||
// strzałka w prawo przesuwa kursor o tydzień i zaznacza tygodniem docelowym
|
||||
await user.click(screen.getByRole('button', { name: 'Następny tydzień' }));
|
||||
|
||||
// oczekiwany poniedziałek tygodnia zawierającego 20. dzień następnego miesiąca
|
||||
// oczekiwany poniedziałek = poniedziałek następnego tygodnia
|
||||
const now = new Date();
|
||||
const target = new Date(now.getFullYear(), now.getMonth() + 1, 20);
|
||||
const monday = new Date(target);
|
||||
monday.setDate(target.getDate() - ((target.getDay() + 6) % 7));
|
||||
const expected = `${monday.getFullYear()}-${String(monday.getMonth() + 1).padStart(2, '0')}-${String(
|
||||
monday.getDate(),
|
||||
const cur = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
cur.setDate(cur.getDate() - ((cur.getDay() + 6) % 7));
|
||||
cur.setDate(cur.getDate() + 7);
|
||||
const expected = `${cur.getFullYear()}-${String(cur.getMonth() + 1).padStart(2, '0')}-${String(
|
||||
cur.getDate(),
|
||||
).padStart(2, '0')}`;
|
||||
|
||||
const title = screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy');
|
||||
@@ -211,7 +209,7 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('autofocus na tytule przy tworzeniu nowego planu; kalendarz tygodnia z przyciskiem „Dziś”', async () => {
|
||||
it('autofocus na tytule przy tworzeniu nowego planu; kalendarz tygodnia z przyciskiem „Ten tydzień”', async () => {
|
||||
mockApi({});
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
@@ -221,8 +219,34 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
|
||||
expect(document.activeElement).toBe(
|
||||
screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'),
|
||||
);
|
||||
// kalendarz tygodnia startu: nawigacja miesiącami + skrót do bieżącego miesiąca
|
||||
expect(screen.getByRole('button', { name: 'Dziś' })).toBeInTheDocument();
|
||||
// kalendarz tygodnia: skrót do bieżącego tygodnia; lewa strzałka znika,
|
||||
// gdy kursor stoi na minimalnym dostępnym tygodniu (bieżącym)
|
||||
expect(screen.getByRole('button', { name: 'Ten tydzień' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Poprzedni tydzień' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('strzałki przesuwają kursor o tydzień; lewa znika po powrocie do bieżącego tygodnia', async () => {
|
||||
mockApi({});
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenNewPlan(user);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Następny tydzień' }));
|
||||
// kursor/selected = następny tydzień — cofnięcie dozwolone
|
||||
expect(screen.getByRole('button', { name: 'Poprzedni tydzień' })).toBeInTheDocument();
|
||||
// zaznaczony tygodniowy podsum wyliczony od poniedziałku kursora
|
||||
const now = new Date();
|
||||
const mon = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
mon.setDate(mon.getDate() - ((mon.getDay() + 6) % 7) + 7);
|
||||
const sun = new Date(mon);
|
||||
sun.setDate(mon.getDate() + 6);
|
||||
const fmt = (d: Date) =>
|
||||
`${String(d.getDate()).padStart(2, '0')}.${String(d.getMonth() + 1).padStart(2, '0')}.${d.getFullYear()}`;
|
||||
expect(screen.getByText(`Start: tydzień ${fmt(mon)} – ${fmt(sun)}`)).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Poprzedni tydzień' }));
|
||||
// minimalny dostępny tydzień (bieżący) — lewa strzałka znika
|
||||
expect(screen.queryByRole('button', { name: 'Poprzedni tydzień' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('blokuje minione tygodnie startu', async () => {
|
||||
@@ -233,10 +257,15 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
|
||||
|
||||
// siatka = 42 komórki (6 tygodni) z dniami sąsiednich miesięcy — dla KAŻDEJ komórki
|
||||
// oczekiwany stan bierze się z poniedziałka jej tygodnia (ten sam numer dnia może
|
||||
// występować w minionym i przyszłym tygodniu, więc sprawdzamy komórkę po komórce)
|
||||
// występować w minionym i przyszłym tygodniu, więc sprawdzamy komórkę po komórce).
|
||||
// Miesiąc siatki = miesiąc czwartku bieżącego tygodnia (reguła kotwicy WeekPicker).
|
||||
const now = new Date();
|
||||
const y = now.getFullYear();
|
||||
const m = now.getMonth() + 1;
|
||||
const curMon = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
curMon.setDate(curMon.getDate() - ((curMon.getDay() + 6) % 7));
|
||||
const view = new Date(curMon);
|
||||
view.setDate(curMon.getDate() + 3);
|
||||
const y = view.getFullYear();
|
||||
const m = view.getMonth() + 1;
|
||||
const firstDay = new Date(y, m - 1, 1);
|
||||
const startOffset = (firstDay.getDay() + 6) % 7;
|
||||
const gridStart = new Date(y, m - 1, 1 - startOffset);
|
||||
@@ -250,7 +279,7 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
|
||||
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
|
||||
return x;
|
||||
};
|
||||
const curMonday = mondayOf(now);
|
||||
const curMonday = curMon;
|
||||
|
||||
const group = screen.getByRole('group', { name: 'Wybór tygodnia startu' });
|
||||
const buttons = within(group).getAllByRole('button');
|
||||
@@ -736,7 +765,7 @@ function mockEditApi(capture: Capture, plan: Record<string, unknown>) {
|
||||
);
|
||||
}
|
||||
|
||||
async function loginAndOpenEditor(user: userEvent.User) {
|
||||
async function loginAndOpenEditor(user: userEvent.User, planTitle = 'Plan w trakcie') {
|
||||
expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument();
|
||||
const email = document.querySelector('input[type="email"]') as HTMLInputElement;
|
||||
const password = document.querySelector('input[type="password"]') as HTMLInputElement;
|
||||
@@ -747,7 +776,7 @@ async function loginAndOpenEditor(user: userEvent.User) {
|
||||
await user.click(screen.getByRole('link', { name: 'Plany treningowe' }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plan w trakcie' })).toBeInTheDocument();
|
||||
expect(await screen.findByRole('heading', { name: planTitle })).toBeInTheDocument();
|
||||
// akcja „Edytuj” w topmenu (PlanDetail) prowadzi do edytora
|
||||
await user.click(
|
||||
within(document.querySelector('header')!).getByRole('button', { name: 'Edytuj' }),
|
||||
@@ -883,3 +912,114 @@ describe('PlanEditor — dzień bez ćwiczeń blokuje zapis', () => {
|
||||
expect(screen.getByRole('group', { name: 'Dni treningowe' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlanEditor — szkic ze startem w bieżącym tygodniu: dni minione zablokowane', () => {
|
||||
const DAY_NAMES = ['Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota', 'Niedziela'];
|
||||
|
||||
/** Szkic (DRAFT) z planowanym startem = poniedziałek bieżącego tygodnia. */
|
||||
function draftThisWeekPlan(withPastDay: boolean) {
|
||||
const now = new Date();
|
||||
const mon = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
mon.setDate(mon.getDate() - ((mon.getDay() + 6) % 7));
|
||||
const key = `${mon.getFullYear()}-${String(mon.getMonth() + 1).padStart(2, '0')}-${String(
|
||||
mon.getDate(),
|
||||
).padStart(2, '0')}`;
|
||||
const dowToday = ((now.getDay() + 6) % 7) + 1; // 1=Pn .. 7=Nd
|
||||
const days =
|
||||
withPastDay && dowToday > 1
|
||||
? [
|
||||
{
|
||||
id: 'td-1',
|
||||
dayOfWeek: dowToday - 1,
|
||||
date: null,
|
||||
status: 'PLANNED',
|
||||
moveLog: [],
|
||||
sessions: [],
|
||||
exercises: [
|
||||
{
|
||||
id: 'tpe-1',
|
||||
exerciseId: 'ex-1',
|
||||
order: 0,
|
||||
exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
|
||||
sets: [
|
||||
{
|
||||
id: 'tps-1',
|
||||
index: 0,
|
||||
reps: 10,
|
||||
loadKg: 60,
|
||||
restSec: 90,
|
||||
rir: 2,
|
||||
cardioBpm: null,
|
||||
timeSec: null,
|
||||
speed: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
: [];
|
||||
return {
|
||||
id: 'plan-1',
|
||||
userId: 'u1',
|
||||
title: 'Szkic ze startem',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 1,
|
||||
startDate: `${key}T00:00:00.000Z`,
|
||||
gym: null,
|
||||
creator: null,
|
||||
canManage: true,
|
||||
weeks: [{ id: 'tw-1', index: 0, customName: null, days }],
|
||||
};
|
||||
}
|
||||
|
||||
it('klik w minione pole dni otwiera wyjaśnienie w modalu; dzień dzisiejszy wciąż do dodania', async () => {
|
||||
const capture: Capture = {};
|
||||
mockEditApi(capture, draftThisWeekPlan(false));
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenEditor(user, 'Szkic ze startem');
|
||||
expect(await screen.findByRole('heading', { name: 'Edycja planu' })).toBeInTheDocument();
|
||||
|
||||
const dowToday = ((new Date().getDay() + 6) % 7) + 1;
|
||||
if (dowToday <= 1) return; // w poniedziałek bieżący tydzień nie ma minionych dni
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Dalej' }));
|
||||
const past = DAY_NAMES[dowToday - 2];
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: `${past} — dzień w przeszłości — nie można zaplanować` }),
|
||||
);
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(within(dialog).getByText('Ten dzień już minął')).toBeInTheDocument();
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Rozumiem' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
// dzień NIE został dodany
|
||||
expect(screen.queryByText(`Planujesz teraz [${past}]`)).not.toBeInTheDocument();
|
||||
|
||||
// dzień dzisiejszy nadal do dodania
|
||||
await user.click(screen.getByRole('button', { name: DAY_NAMES[dowToday - 1] }));
|
||||
expect(
|
||||
await screen.findByText(`Planujesz teraz [${DAY_NAMES[dowToday - 1]}]`),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('zapis szkicu z dniem z przeszłością: toast błędu + skok do dnia, brak PATCH', async () => {
|
||||
const capture: Capture = {};
|
||||
mockEditApi(capture, draftThisWeekPlan(true));
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenEditor(user, 'Szkic ze startem');
|
||||
await screen.findByRole('heading', { name: 'Edycja planu' });
|
||||
|
||||
const dowToday = ((new Date().getDay() + 6) % 7) + 1;
|
||||
if (dowToday <= 1) return;
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
|
||||
expect(await screen.findByText(/wypada w przeszłości/)).toBeInTheDocument();
|
||||
expect(capture.patchPlanBody).toBeUndefined();
|
||||
// edytor wskazuje problemowy dzień — można go edytować/usunąć
|
||||
expect(
|
||||
await screen.findByText(`Planujesz teraz [${DAY_NAMES[dowToday - 2]}]`),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,30 +37,64 @@ test('formularz nowego planu ma wybór tygodnia startu i przycisk „Wstecz” w
|
||||
// przycisk „Wstecz” jest też w treści podstrony (topbar ma własny, inteligentny)
|
||||
await expect(page.locator('main > div').getByRole('button', { name: 'Wstecz' })).toBeVisible();
|
||||
|
||||
// formularz zawiera wybór tygodnia startu (siatka miesiąca)
|
||||
await expect(page.getByRole('group', { name: 'Wybór tygodnia startu' })).toBeVisible();
|
||||
// kalendarz tygodnia startu: wiersze = pełne tygodnie (Pn–Nd)
|
||||
const group = page.getByRole('group', { name: 'Wybór tygodnia startu' });
|
||||
await expect(group).toBeVisible();
|
||||
|
||||
// lewa strzałka znika, gdy kursor stoi na minimalnym dostępnym tygodniu (bieżącym)
|
||||
await expect(page.getByRole('button', { name: 'Poprzedni tydzień' })).toHaveCount(0);
|
||||
|
||||
// minione tygodnie są zablokowane — sprawdzamy komórkę po komórce (ten sam numer
|
||||
// dnia może wypaść i w minionym, i w przyszłym tygodniu)
|
||||
const now = new Date();
|
||||
const curMon = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
curMon.setDate(curMon.getDate() - ((curMon.getDay() + 6) % 7));
|
||||
const view = new Date(curMon);
|
||||
view.setDate(curMon.getDate() + 3); // miesiąc siatki = miesiąc czwartku bieżącego tygodnia
|
||||
const first = new Date(view.getFullYear(), view.getMonth(), 1);
|
||||
const gridStart = new Date(
|
||||
view.getFullYear(),
|
||||
view.getMonth(),
|
||||
1 - ((first.getDay() + 6) % 7),
|
||||
);
|
||||
const mondayOf = (d: Date) => {
|
||||
const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
||||
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
|
||||
return x;
|
||||
};
|
||||
const cells = Array.from({ length: 42 }, (_, i) => {
|
||||
const d = new Date(gridStart);
|
||||
d.setDate(gridStart.getDate() + i);
|
||||
return d;
|
||||
});
|
||||
const dayButtons = group.locator('button');
|
||||
await expect(dayButtons).toHaveCount(42);
|
||||
for (let i = 0; i < 42; i++) {
|
||||
if (mondayOf(cells[i]) < curMon) await expect(dayButtons.nth(i)).toBeDisabled();
|
||||
else await expect(dayButtons.nth(i)).toBeEnabled();
|
||||
}
|
||||
|
||||
// strzałka w prawo przesuwa kursor o tydzień i zaznacza tygodniem docelowym;
|
||||
// lewa pojawia się dopiero ponad minimum (bieżącym tygodniem)
|
||||
await page.getByRole('button', { name: 'Następny tydzień' }).click();
|
||||
await expect(page.getByRole('button', { name: 'Poprzedni tydzień' })).toBeVisible();
|
||||
await expect(page.getByText(/^Start: tydzień/)).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Poprzedni tydzień' }).click();
|
||||
await expect(page.getByRole('button', { name: 'Poprzedni tydzień' })).toHaveCount(0);
|
||||
|
||||
// „Ten tydzień” zaznacza bieżący tydzień jako start planu
|
||||
await page.getByRole('button', { name: 'Ten tydzień' }).click();
|
||||
await expect(page.getByText(/^Start: tydzień/)).toBeVisible();
|
||||
|
||||
// nowy plan (DRAFT): pole „Notatka o zmianach” nie istnieje — tylko przy edycji realizacji
|
||||
await expect(page.getByText('Notatka o zmianach')).not.toBeVisible();
|
||||
|
||||
// minione tygodnie są zablokowane — ostatni dzień poprzedniego tygodnia ma disabled
|
||||
const prevWeekEnd = new Date();
|
||||
prevWeekEnd.setDate(prevWeekEnd.getDate() - ((prevWeekEnd.getDay() + 6) % 7) - 1);
|
||||
const pastLabel = String(prevWeekEnd.getDate());
|
||||
if (prevWeekEnd.getMonth() !== new Date().getMonth()) {
|
||||
await page.getByRole('button', { name: 'Poprzedni miesiąc' }).click();
|
||||
}
|
||||
await expect(page.getByRole('button', { name: pastLabel, exact: true }).first()).toBeDisabled();
|
||||
|
||||
// wypełnij tytuł, zaznacz tydzień startu (20. dzień następnego miesiąca —
|
||||
// 20. dzień bieżącego może być w minionym, zablokowanym tygodniu), utwórz plan
|
||||
// wypełnij tytuł i utwórz plan (zapisany jako szkic z planowanym startem)
|
||||
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan e2e');
|
||||
await page.getByRole('button', { name: 'Następny miesiąc' }).click();
|
||||
await page.getByRole('button', { name: '20', exact: true }).click();
|
||||
// akcja zapisu w menu kontekstowym (lg+: inline w nagłówku)
|
||||
await page.getByRole('button', { name: 'Zapisz' }).click();
|
||||
|
||||
// po utworzeniu — szczegóły planu (aktywowany z datą startu)
|
||||
// po utworzeniu — szczegóły planu (szkic z planowanym tygodniem startu)
|
||||
await expect(page.getByRole('heading', { name: 'Plan e2e' })).toBeVisible();
|
||||
});
|
||||
|
||||
|
||||
@@ -102,8 +102,8 @@ test('zakładka Plany: blokada aktywacji szkicu, gdy podopieczny ma już aktywny
|
||||
|
||||
// wybór tygodnia startu nie zdejmuję blokady
|
||||
const picker = page.getByRole('group', { name: 'Wybór tygodnia startu' });
|
||||
await page.getByRole('button', { name: 'Następny miesiąc' }).click();
|
||||
await picker.locator('button', { hasText: /^15$/ }).first().click();
|
||||
await expect(picker).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Następny tydzień' }).click();
|
||||
await expect(page.getByText(/Start: tydzień/)).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Aktywuj' })).toBeDisabled();
|
||||
});
|
||||
|
||||
@@ -313,6 +313,52 @@ describe('usePlanEditorState — akcje mutacji', () => {
|
||||
expect(result.current.weeks[0].days[0].exercises[1].id).toBeUndefined();
|
||||
});
|
||||
|
||||
it('kopia tygodnia/dnia omija dni wypadające w przeszłości (start = bieżący tydzień)', () => {
|
||||
const { result } = renderHook(() => usePlanEditorState());
|
||||
const now = new Date();
|
||||
const mon = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
mon.setDate(mon.getDate() - ((mon.getDay() + 6) % 7)); // poniedziałek bieżącego tygodnia
|
||||
const dowToday = ((now.getDay() + 6) % 7) + 1; // 1=Pn .. 7=Nd
|
||||
if (dowToday <= 1) return; // w poniedziałek bieżący tydzień nie ma minionych dni
|
||||
const start = `${mon.getFullYear()}-${String(mon.getMonth() + 1).padStart(2, '0')}-${String(
|
||||
mon.getDate(),
|
||||
).padStart(2, '0')}`;
|
||||
const plan: PlanLike = {
|
||||
title: 't',
|
||||
weeksCount: 2,
|
||||
startDate: start,
|
||||
weeks: [
|
||||
{ index: 0, days: [] },
|
||||
{
|
||||
index: 1,
|
||||
days: [1, 2, 3, 4, 5, 6, 7].map((dow) => ({
|
||||
dayOfWeek: dow,
|
||||
exercises: [{ exerciseId: `ex-${dow}`, sets: [{ reps: '10' }] }],
|
||||
})),
|
||||
},
|
||||
],
|
||||
};
|
||||
act(() => result.current.initFromPlan(plan));
|
||||
|
||||
// przyszły tydzień → tydzień startu: dni sprzed dzisiaj nie przejdą (3. tydzień
|
||||
// ma poniedziałek w przyszłości prawidłowo, ale kopia do bieżącego go omija)
|
||||
act(() => result.current.copyFromWeek(0, 1));
|
||||
const expected = Array.from({ length: 8 - dowToday }, (_, i) => dowToday + i);
|
||||
expect(result.current.weeks[0].days.map((d) => d.dayOfWeek)).toEqual(expected);
|
||||
|
||||
// copyDayTo na cel w przeszłości — bez zmian (zabezpieczenie ścieżek poza UI)
|
||||
act(() => result.current.copyDayTo(0, dowToday - 1, 1, 7));
|
||||
expect(result.current.weeks[0].days.some((d) => d.dayOfWeek === dowToday - 1)).toBe(false);
|
||||
|
||||
// ten sam dzień w TYGODNIU 2 (przyszłym) — cel poprawny, kopia przechodzi
|
||||
act(() => result.current.copyDayTo(1, dowToday - 1, 1, 7));
|
||||
expect(
|
||||
result.current.weeks[1].days
|
||||
.find((d) => d.dayOfWeek === dowToday - 1)
|
||||
?.exercises.map((e) => e.exerciseId),
|
||||
).toEqual(['ex-7']);
|
||||
});
|
||||
|
||||
it('withoutIds zrzuca id dni/ćwiczeń/serii (bezpieczeństwo lustrzanych kopii)', () => {
|
||||
const stripped = withoutIds([
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user