diff --git a/api/prisma/migrations/20261027185839_add_plan_day_skip_resolved_at/migration.sql b/api/prisma/migrations/20261027185839_add_plan_day_skip_resolved_at/migration.sql new file mode 100644 index 0000000..15c225d --- /dev/null +++ b/api/prisma/migrations/20261027185839_add_plan_day_skip_resolved_at/migration.sql @@ -0,0 +1,8 @@ +-- AlterTable +ALTER TABLE "PlanDay" ADD COLUMN "skipResolvedAt" TIMESTAMP(3); + +-- Backfill: historyczne pominięcia są uznane za decyzję — dialog dotyczy tylko +-- pominięć od wdrożenia (bez tego każdy użytkownik zobaczy dialog przy pierwszym wejściu). +UPDATE "PlanDay" + SET "skipResolvedAt" = COALESCE("skippedAt", "date", now()) + WHERE "status" = 'SKIPPED' AND "skipResolvedAt" IS NULL; diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma index 3306a20..9f073e4 100644 --- a/api/prisma/schema.prisma +++ b/api/prisma/schema.prisma @@ -741,13 +741,15 @@ model PlanWeek { } model PlanDay { - id String @id @default(cuid()) - weekId String - dayOfWeek Int - date DateTime? - status DayStatus @default(PLANNED) - completedAt DateTime? - skippedAt DateTime? + id String @id @default(cuid()) + weekId String + dayOfWeek Int + date DateTime? + status DayStatus @default(PLANNED) + completedAt DateTime? + skippedAt DateTime? + /// Decyzja użytkownika o pominiętym dniu (akceptacja); null = oczekuje decyzji. + skipResolvedAt DateTime? week PlanWeek @relation(fields: [weekId], references: [id], onDelete: Cascade) moveLog DayMove[] diff --git a/api/src/routes/plans.ts b/api/src/routes/plans.ts index 3277121..2683197 100644 --- a/api/src/routes/plans.ts +++ b/api/src/routes/plans.ts @@ -5,6 +5,7 @@ import { authenticate } from '../middleware/auth.js'; import { validate } from '../middleware/validate.js'; import { abandonPlan, + acceptSkippedDay, activatePlan, assertPlanOwner, completePlan, @@ -246,6 +247,35 @@ export function createPlanRoutes({ prisma }: AppDeps) { }), ); + /** + * @openapi + * /plans/{id}/days/{dayId}/skip/accept: + * post: + * summary: Accept a skipped training day of an active plan (owner only) — the day + * stays SKIPPED and the decision dialog stops showing it. Idempotent: accepting + * an already-resolved day returns it unchanged. + * tags: [Plans] + * responses: + * 200: { description: OK, returns { day } } + * 400: { description: The day is not skipped } + * 404: { description: Plan or day not found } + */ + router.post( + '/:id/days/:dayId/skip/accept', + asyncHandler(async (req, res) => { + await assertPlanOwner(prisma, req.params.id, req.user!.id); + const result = await acceptSkippedDay(prisma, req.params.id, req.params.dayId, req.user!.id); + await logActivity(prisma, { + actorId: req.user!.id, + action: 'plan.day.skip.accepted', + entityType: 'plan', + entityId: req.params.id, + details: { dayId: req.params.dayId }, + }); + res.json(result); + }), + ); + /** * @openapi * /plans/{id}: diff --git a/api/src/services/dashboard.ts b/api/src/services/dashboard.ts index c8c9158..7ab1d61 100644 --- a/api/src/services/dashboard.ts +++ b/api/src/services/dashboard.ts @@ -87,6 +87,14 @@ export async function getDashboard(prisma: PrismaClient, userId: string) { exercises: { name: string; nameEn: string | null; muscle: string }[]; } | null = null; let progress: { completed: number; total: number; percent: number } | null = null; + let pendingSkip: { + dayId: string; + date: string; + skippedAt: string; + exerciseCount: number; + unresolvedCount: number; + plan: { id: string; title: string; startDate: Date | null }; + } | null = null; let extra: { sets: number } | null = null; let missing: { sets: number } | null = null; let week: { planned: number; completed: number } | null = null; @@ -158,6 +166,23 @@ export async function getDashboard(prisma: PrismaClient, userId: string) { percent: total > 0 ? Math.round((done / total) * 100) : 0, }; + // Pominięcia oczekujące na decyzję użytkownika (dialog na Dashboardzie): + // dzień górą wg czasu pominięcia (fallback data dnia), najstarsze zamykane najpierw. + const unresolved = days + .filter((d) => d.status === 'SKIPPED' && !d.skipResolvedAt) + .sort((a, b) => (b.skippedAt ?? b.date!).getTime() - (a.skippedAt ?? a.date!).getTime()); + const top = unresolved[0]; + pendingSkip = top + ? { + dayId: top.id, + date: top.date!.toISOString(), + skippedAt: (top.skippedAt ?? top.date!).toISOString(), + exerciseCount: top.exercises.length, + unresolvedCount: unresolved.length, + plan: { id: activePlan.id, title: activePlan.title, startDate: activePlan.startDate }, + } + : null; + // Extra = sets performed beyond the plan (planSetId = null) in completed sessions: // sets of exercises added beyond the plan + additional sets of planned exercises. const extraSets = await prisma.sessionSet.count({ @@ -213,6 +238,7 @@ export async function getDashboard(prisma: PrismaClient, userId: string) { weeklySets, nextTraining, progress, + pendingSkip, extra, missing, activePlan: activePlan diff --git a/api/src/services/plans.ts b/api/src/services/plans.ts index 5baa705..363da31 100644 --- a/api/src/services/plans.ts +++ b/api/src/services/plans.ts @@ -782,8 +782,11 @@ export async function movePlanDay( data: { date: to, // przesunięcie w przyszłość przywraca dzień do planu (inaczej zostałby - // SKIPPED na zawsze, mimo że trening wciąż przed nami) - ...(day.status === 'SKIPPED' ? { status: 'PLANNED', skippedAt: null } : {}), + // SKIPPED na zawsze, mimo że trening wciąż przed nami); wyzerowanie + // decyzji: jeśli przesunięty dzień znowu minie, użytkownik zapyta ponownie + ...(day.status === 'SKIPPED' + ? { status: 'PLANNED', skippedAt: null, skipResolvedAt: null } + : {}), }, }); if (swapWith) { @@ -800,6 +803,29 @@ export async function movePlanDay( return { day: updated, swappedWith: swapWith?.id ?? null }; } +/** + * Akceptacja pominiętego dnia: dzień zostaje SKIPPED, a decyzja zamyka dialog + * decyzji na Dashboardzie. Idempotentne — powtórna akceptacja nie zapisuje nic + * ponownie (podwójne kliknięcie jest nieszkodliwe). + */ +export async function acceptSkippedDay( + prisma: PrismaClient, + planId: string, + dayId: string, + userId: string, +) { + await assertPlanOwner(prisma, planId, userId); + const day = await prisma.planDay.findFirst({ where: { id: dayId, week: { planId } } }); + if (!day) throw notFound('Training day not found'); + if (day.status !== 'SKIPPED') throw badRequest('Only a skipped training day can be accepted'); + if (day.skipResolvedAt) return { day }; + const updated = await prisma.planDay.update({ + where: { id: day.id }, + data: { skipResolvedAt: new Date() }, + }); + return { day: updated }; +} + export async function activatePlan( prisma: PrismaClient, planId: string, diff --git a/api/src/services/scheduler.ts b/api/src/services/scheduler.ts index a65bb86..d67dd82 100644 --- a/api/src/services/scheduler.ts +++ b/api/src/services/scheduler.ts @@ -11,7 +11,8 @@ import { expireStale } from './presence.js'; * 3. Auto-abandon sessions after 24h from start — the real hard limit for a * running session; the day they belong to is skipped too (same rule as manual * abandonment — an abandoned training is not retryable). - * 4. Auto-complete active plans when all days are completed/skipped. + * 4. Auto-complete active plans when all days are completed/skipped and no + * skipped day is awaiting the user's decision (skipResolvedAt set). * 5. Remove gym schedule exceptions whose date is in the past. * 6. Release presence slots: ACTIVE presence without activity for 30 min -> EXPIRED. */ @@ -77,9 +78,12 @@ export function startScheduler(prisma: PrismaClient): void { }); for (const plan of activePlans) { const days = plan.weeks.flatMap((w) => w.days); + // Unresolved SKIPPED wstrzymuje auto-completion — pominięcie ostatniego + // dnia nie może skasować szansy na dialog decyzji (akceptacja/przesunięcie). if ( days.length > 0 && - days.every((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED') + days.every((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED') && + !days.some((d) => d.status === 'SKIPPED' && !d.skipResolvedAt) ) { await prisma.trainingPlan.update({ where: { id: plan.id }, diff --git a/api/src/swagger.ts b/api/src/swagger.ts index 1af8c43..4c0eaf9 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -1354,6 +1354,24 @@ export const openapi: Record = { }, }, }, + '/plans/{id}/days/{dayId}/skip/accept': { + post: { + tags: ['Plans'], + summary: + 'Accept a SKIPPED training day of an ACTIVE plan (owner only) — the day stays SKIPPED and the decision dialog no longer shows it. Idempotent: an already-resolved day is returned unchanged', + description: 'Writes an ActivityLog entry: plan.day.skip.accepted.', + security: [{ bearerAuth: [] }], + parameters: [ + { name: 'id', in: 'path', required: true, schema: { type: 'string' } }, + { name: 'dayId', in: 'path', required: true, schema: { type: 'string' } }, + ], + responses: { + 200: { description: 'OK, returns { day }' }, + 400: { description: 'The day is not skipped' }, + 404: { description: 'Plan or day not found' }, + }, + }, + }, '/plans/{id}/gym': { patch: { tags: ['Plans'], @@ -1632,7 +1650,7 @@ export const openapi: Record = { get: { tags: ['Dashboard'], summary: - 'Dashboard — killstreak (+ rekord, daty skutecznych dni z 30 ostatnich), globalna historia (plany/sesje/serie, pierwsza/ostatnia sesja, serie wg tygodni), tempo tygodnia i postęp aktywnego planu', + 'Dashboard — killstreak (+ rekord, daty skutecznych dni z 30 ostatnich), globalna historia (plany/sesje/serie, pierwsza/ostatnia sesja, serie wg tygodni), tempo tygodnia i postęp aktywnego planu; pendingSkip: najnowsze nierozstrzygnięte pominięcie aktywnego planu (dialog decyzji) lub null', security: [{ bearerAuth: [] }], }, }, diff --git a/api/test/helpers.ts b/api/test/helpers.ts index 29227c4..d5627e5 100644 --- a/api/test/helpers.ts +++ b/api/test/helpers.ts @@ -84,6 +84,8 @@ export interface SeedDay { dayOfWeek: number; date?: Date | null; status?: 'PLANNED' | 'COMPLETED' | 'SKIPPED'; + skippedAt?: Date; + skipResolvedAt?: Date | null; exercises?: { exerciseId: string; order: number; @@ -120,6 +122,8 @@ export async function seedPlan(opts: { dayOfWeek: d.dayOfWeek, date: d.date ?? null, status: d.status ?? 'PLANNED', + skippedAt: d.skippedAt ?? null, + skipResolvedAt: d.skipResolvedAt ?? null, exercises: { create: (d.exercises ?? []).map((e) => ({ exerciseId: e.exerciseId, diff --git a/api/test/integration/dashboard.test.ts b/api/test/integration/dashboard.test.ts index c420a42..45a5d9f 100644 --- a/api/test/integration/dashboard.test.ts +++ b/api/test/integration/dashboard.test.ts @@ -25,6 +25,7 @@ describe('dashboard routes', () => { firstSessionAt: null, nextTraining: null, progress: null, + pendingSkip: null, extra: null, missing: null, activePlan: null, @@ -163,6 +164,8 @@ describe('dashboard routes', () => { monday.getTime(), ]); expect(res.body.week).toEqual({ planned: 2, completed: 1 }); + // pominięcia w COMPLETED planie nie startują dialogu — reguła dotyczy ACTIVE + expect(res.body.pendingSkip).toBeNull(); expect(new Date(res.body.firstSessionAt).getTime()).toBe(dBefore(60).getTime()); expect(new Date(res.body.lastSessionAt).getTime()).toBe(monday.getTime()); expect(res.body.history).toEqual({ completedPlans: 1, sessions: 5, sets: 15 }); @@ -385,6 +388,105 @@ describe('dashboard routes', () => { expect(res.body.killstreak).toBe(0); }); + it('pendingSkip: najstarsze nierozstrzygnięte pominięcie aktywnego planu, znika po akceptacji', async () => { + const app = buildApp(); + const { user } = await createUser(); + const token = (await loginViaApi(user.email, PASSWORD)).token; + const exercise = await createExercise(); + + const plan = await seedPlan({ + userId: user.id, + title: 'Skip plan', + status: 'ACTIVE', + startDate: localMidnight(-7), + weeks: [ + { + index: 0, + days: [ + { + dayOfWeek: 1, + date: localMidnight(-3), + status: 'SKIPPED', + skippedAt: localMidnight(-2), + exercises: [{ exerciseId: exercise.id, order: 0, sets: [{ index: 0, reps: 10 }] }], + }, + { + dayOfWeek: 3, + date: localMidnight(-1), + status: 'SKIPPED', + skippedAt: localMidnight(0), + }, + { dayOfWeek: 5, date: localMidnight(1), status: 'PLANNED' }, + ], + }, + ], + }); + const olderSkipId = plan.weeks[0].days[0].id; + const newerSkipId = plan.weeks[0].days[1].id; + + const res = await app.get('/api/v1/dashboard').set('Authorization', `Bearer ${token}`); + expect(res.status).toBe(200); + // górą najnowsze pominięcie (skippedAt), licznik obejmuje oba + expect(res.body.pendingSkip).toEqual({ + dayId: newerSkipId, + date: localMidnight(-1).toISOString(), + skippedAt: localMidnight(0).toISOString(), + exerciseCount: 0, + unresolvedCount: 2, + plan: { + id: plan.id, + title: 'Skip plan', + startDate: localMidnight(-7).toISOString(), + }, + }); + + const accept = await app + .post(`/api/v1/plans/${plan.id}/days/${newerSkipId}/skip/accept`) + .set('Authorization', `Bearer ${token}`); + expect(accept.status).toBe(200); + + const after = await app.get('/api/v1/dashboard').set('Authorization', `Bearer ${token}`); + expect(after.body.pendingSkip).toMatchObject({ + dayId: olderSkipId, + exerciseCount: 1, + unresolvedCount: 1, + }); + + await app + .post(`/api/v1/plans/${plan.id}/days/${olderSkipId}/skip/accept`) + .set('Authorization', `Bearer ${token}`); + const closed = await app.get('/api/v1/dashboard').set('Authorization', `Bearer ${token}`); + expect(closed.body.pendingSkip).toBeNull(); + }); + + it('pendingSkip: null gdy pominięcie ma już decyzję (skipResolvedAt)', async () => { + const app = buildApp(); + const { user } = await createUser(); + const token = (await loginViaApi(user.email, PASSWORD)).token; + await seedPlan({ + userId: user.id, + status: 'ACTIVE', + startDate: localMidnight(-7), + weeks: [ + { + index: 0, + days: [ + { + dayOfWeek: 1, + date: localMidnight(-3), + status: 'SKIPPED', + skippedAt: localMidnight(-2), + skipResolvedAt: localMidnight(-1), + }, + ], + }, + ], + }); + const res = await app.get('/api/v1/dashboard').set('Authorization', `Bearer ${token}`); + expect(res.status).toBe(200); + expect(res.body.pendingSkip).toBeNull(); + }); + it('rejects /dashboard without a token with 401', async () => { const app = buildApp(); const res = await app.get('/api/v1/dashboard'); diff --git a/api/test/integration/plans.test.ts b/api/test/integration/plans.test.ts index 464f2af..a1a07fc 100644 --- a/api/test/integration/plans.test.ts +++ b/api/test/integration/plans.test.ts @@ -1493,6 +1493,8 @@ describe('PATCH /plans/:id/days/:dayId/move — przesunięcie dnia treningowego' const day = await prisma.planDay.findUnique({ where: { id: skippedDayId } }); expect(day!.status).toBe('PLANNED'); expect(day!.skippedAt).toBeNull(); + // decyzja wyzerowana — gdy przesunięty dzień znowu minie, dialog zapyta ponownie + expect(day!.skipResolvedAt).toBeNull(); }); it('refuses to move a completed day with 400', async () => { @@ -1585,3 +1587,107 @@ describe('PATCH /plans/:id/days/:dayId/move — przesunięcie dnia treningowego' }); }); +describe('POST /plans/:id/days/:dayId/skip/accept — akceptacja pominiętego dnia', () => { + let token: string; + let planId: string; + let skippedDayId: string; + let plannedDayId: string; + + function localDay(offset: number): Date { + const d = new Date(); + d.setHours(0, 0, 0, 0); + d.setDate(d.getDate() + offset); + return d; + } + + beforeEach(async () => { + const { user, token: t } = await createUserWithToken(); + token = t; + const plan = await seedPlan({ + userId: user.id, + status: 'ACTIVE', + startDate: localDay(-7), + weeks: [ + { + index: 0, + days: [ + { dayOfWeek: 1, date: localDay(-6), status: 'SKIPPED', skippedAt: localDay(-5) }, + { dayOfWeek: 5, date: localDay(0), status: 'PLANNED' }, + ], + }, + ], + }); + planId = plan.id; + const byDow = new Map(plan.weeks[0].days.map((d) => [d.dayOfWeek, d.id] as const)); + skippedDayId = byDow.get(1)!; + plannedDayId = byDow.get(5)!; + }); + + it('accepts an unresolved skipped day: 200, skipResolvedAt in DB and an audit entry', async () => { + const app = buildApp(); + const res = await app + .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) + .set('Authorization', `Bearer ${token}`); + expect(res.status).toBe(200); + expect(res.body.day).toMatchObject({ id: skippedDayId, status: 'SKIPPED' }); + expect(res.body.day.skipResolvedAt).toEqual(expect.any(String)); + + const day = await prisma.planDay.findUnique({ where: { id: skippedDayId } }); + expect(day!.status).toBe('SKIPPED'); + expect(day!.skipResolvedAt).toBeInstanceOf(Date); + + const log = await prisma.activityLog.findFirst({ + where: { action: 'plan.day.skip.accepted', entityId: planId }, + }); + expect(log).not.toBeNull(); + expect(log!.details).toMatchObject({ dayId: skippedDayId }); + }); + + it('is idempotent: a second accept returns 200 without rewriting the decision', async () => { + const app = buildApp(); + const first = await app + .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) + .set('Authorization', `Bearer ${token}`); + expect(first.status).toBe(200); + const second = await app + .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) + .set('Authorization', `Bearer ${token}`); + expect(second.status).toBe(200); + expect(second.body.day.skipResolvedAt).toBe(first.body.day.skipResolvedAt); + const day = await prisma.planDay.findUnique({ where: { id: skippedDayId } }); + expect(day!.skipResolvedAt).toBeInstanceOf(Date); + }); + + it('refuses a planned day with 400', async () => { + const app = buildApp(); + const res = await app + .post(`/api/v1/plans/${planId}/days/${plannedDayId}/skip/accept`) + .set('Authorization', `Bearer ${token}`); + expect(res.status).toBe(400); + expect(res.body.error.message).toBe('Only a skipped training day can be accepted'); + }); + + it('returns 404 for another user and for a day outside the plan', async () => { + const app = buildApp(); + const stranger = await createUserWithToken(); + const strangerPlan = await seedPlan({ + userId: stranger.user.id, + status: 'ACTIVE', + startDate: localDay(-7), + weeks: [{ index: 0, days: [{ dayOfWeek: 2, date: localDay(-6), status: 'SKIPPED' }] }], + }); + + const intruder = await app + .post(`/api/v1/plans/${planId}/days/${skippedDayId}/skip/accept`) + .set('Authorization', `Bearer ${stranger.token}`); + expect(intruder.status).toBe(404); + expect(intruder.body.error.message).toBe('Plan not found'); + + const wrongDay = await app + .post(`/api/v1/plans/${planId}/days/${strangerPlan.weeks[0].days[0].id}/skip/accept`) + .set('Authorization', `Bearer ${token}`); + expect(wrongDay.status).toBe(404); + expect(wrongDay.body.error.message).toBe('Training day not found'); + }); +}); + diff --git a/api/test/unit/scheduler.test.ts b/api/test/unit/scheduler.test.ts index 7cdde48..18af242 100644 --- a/api/test/unit/scheduler.test.ts +++ b/api/test/unit/scheduler.test.ts @@ -105,7 +105,11 @@ describe('scheduler', () => { planFindMany.mockResolvedValue([ { id: 'plan-1', - weeks: [{ days: [{ status: 'COMPLETED' }, { status: 'SKIPPED' }] }], + weeks: [ + { + days: [{ status: 'COMPLETED' }, { status: 'SKIPPED', skipResolvedAt: new Date() }], + }, + ], }, ]); await tickOnce(); @@ -115,6 +119,17 @@ describe('scheduler', () => { }); }); + it('does not auto-complete while a skip is unresolved (decision dialog pending)', async () => { + planFindMany.mockResolvedValue([ + { + id: 'plan-1', + weeks: [{ days: [{ status: 'COMPLETED' }, { status: 'SKIPPED', skipResolvedAt: null }] }], + }, + ]); + await tickOnce(); + expect(planUpdate).not.toHaveBeenCalled(); + }); + it('keeps a plan active while days are still planned', async () => { planFindMany.mockResolvedValue([{ id: 'plan-1', weeks: [{ days: [{ status: 'PLANNED' }] }] }]); await tickOnce(); diff --git a/api/test/unit/services-plans.test.ts b/api/test/unit/services-plans.test.ts index cf39042..d6924bb 100644 --- a/api/test/unit/services-plans.test.ts +++ b/api/test/unit/services-plans.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, vi } from 'vitest'; import { abandonPlan, + acceptSkippedDay, activatePlan, assertPlanOwner, completePlan, @@ -39,7 +40,13 @@ function mockPrisma() { exercise: { findMany: vi.fn() }, coaching: { findUnique: vi.fn(), findMany: vi.fn() }, planWeek: { findMany: vi.fn() }, - planDay: { count: vi.fn(), findFirst: vi.fn(), findMany: vi.fn(), findUnique: vi.fn() }, + planDay: { + count: vi.fn(), + findFirst: vi.fn(), + findMany: vi.fn(), + findUnique: vi.fn(), + update: vi.fn(), + }, dayMove: { create: vi.fn() }, planShare: { findUnique: vi.fn(), @@ -463,7 +470,12 @@ describe('moving a training day', () => { }); expect(tx.planDay.update).toHaveBeenCalledWith({ where: { id: 'd1' }, - data: expect.objectContaining({ status: 'PLANNED', skippedAt: null }), + data: expect.objectContaining({ + status: 'PLANNED', + skippedAt: null, + // decyzja wyzerowana: jeśli przesunięty dzień znowu minie, dialog zapyta ponownie + skipResolvedAt: null, + }), }); }); @@ -482,6 +494,73 @@ describe('moving a training day', () => { }); }); +describe('accepting a skipped day', () => { + const startDate = new Date(); + startDate.setDate(startDate.getDate() - 30); + const activeRow = { id: 'p1', userId: 'u1', status: 'ACTIVE', title: 't', startDate, gymId: null }; + + function acceptMocks(dayRow: Record | null) { + const { prisma } = mockPrisma(); + prisma.trainingPlan.findUnique.mockResolvedValue(activeRow); + prisma.planDay.findFirst.mockResolvedValue(dayRow); + prisma.planDay.update.mockResolvedValue(dayRow); + return prisma; + } + + it('accepts an unresolved skipped day and stamps skipResolvedAt', async () => { + const prisma = acceptMocks({ + id: 'd1', + status: 'SKIPPED', + skippedAt: new Date(), + skipResolvedAt: null, + }); + await acceptSkippedDay(prisma, 'p1', 'd1', 'u1'); + expect(prisma.planDay.update).toHaveBeenCalledTimes(1); + expect(prisma.planDay.update).toHaveBeenCalledWith({ + where: { id: 'd1' }, + data: { skipResolvedAt: expect.any(Date) }, + }); + }); + + it('is idempotent: an already-resolved day returns without a second write', async () => { + const prisma = acceptMocks({ + id: 'd1', + status: 'SKIPPED', + skippedAt: new Date(), + skipResolvedAt: new Date(), + }); + const result = await acceptSkippedDay(prisma, 'p1', 'd1', 'u1'); + expect(prisma.planDay.update).not.toHaveBeenCalled(); + expect(result.day).toMatchObject({ id: 'd1', status: 'SKIPPED' }); + }); + + it('rejects a planned day with 400', async () => { + const prisma = acceptMocks({ id: 'd1', status: 'PLANNED', skipResolvedAt: null }); + await expect(acceptSkippedDay(prisma, 'p1', 'd1', 'u1')).rejects.toMatchObject({ + status: 400, + message: 'Only a skipped training day can be accepted', + }); + expect(prisma.planDay.update).not.toHaveBeenCalled(); + }); + + it('rejects a day from another plan with 404', async () => { + const prisma = acceptMocks(null); + await expect(acceptSkippedDay(prisma, 'p1', 'dX', 'u1')).rejects.toMatchObject({ + status: 404, + message: 'Training day not found', + }); + }); + + it('rejects a foreign plan with 404 (owner only, no existence leak)', async () => { + const prisma = acceptMocks({ id: 'd1', status: 'SKIPPED', skipResolvedAt: null }); + prisma.trainingPlan.findUnique.mockResolvedValue({ ...activeRow, userId: 'someone-else' }); + await expect(acceptSkippedDay(prisma, 'p1', 'd1', 'u1')).rejects.toMatchObject({ + status: 404, + message: 'Plan not found', + }); + }); +}); + describe('createPlan', () => { it('rejects an unknown exerciseId with 400', async () => { const { prisma } = mockPrisma(); diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index ce8fda2..2f1b552 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -707,6 +707,17 @@ export function movePlanDay( }>(`/plans/${planId}/days/${dayId}/move`, { method: 'PATCH', body }); } +/** + * Akceptacja pominiętego dnia (właściciel): dzień zostaje SKIPPED, dialog decyzji + * znika. Idempotentne po stronie API — podwójne kliknięcie jest nieszkodliwe. + */ +export function acceptSkippedDay(planId: string, dayId: string) { + return api<{ day: { id: string; status: string } }>( + `/plans/${planId}/days/${dayId}/skip/accept`, + { method: 'POST' }, + ); +} + /** * Zmiana informacyjnej siłowni planu (właściciel, dowolny status) — modal rozpoczęcia * treningu, gdy user stawił się w innej siłowni niż plan wskazuje. diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 566d168..c08c8b2 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -575,6 +575,18 @@ export interface Dashboard { exercises: { name: string; nameEn?: string | null; muscle: string }[]; } | null; progress: { completed: number; total: number; percent: number } | null; + /** + * Najnowsze nierozstrzygnięte pominięcie aktywnego planu (dialog decyzji); + * null = brak pominięć oczekujących na decyzję. + */ + pendingSkip: { + dayId: string; + date: string; + skippedAt: string; + exerciseCount: number; + unresolvedCount: number; + plan: { id: string; title: string; startDate: string | null }; + } | null; /** Serie wykonane ponad plan (planSetId = null) w ukończonych sesjach aktywnego planu. */ extra: { sets: number } | null; /** Niewykonane serie z planu (reps = null) w ukończonych sesjach aktywnego planu. */ diff --git a/app/src/components/calendar/MoveDayDialog.tsx b/app/src/components/calendar/MoveDayDialog.tsx index b4121e7..b3f7df4 100644 --- a/app/src/components/calendar/MoveDayDialog.tsx +++ b/app/src/components/calendar/MoveDayDialog.tsx @@ -8,12 +8,13 @@ import { fmtDate, todayStr } from '../../lib/format'; import { Button, ErrorText, Field, Input, Modal } from '../ui'; import { useToast } from '../toast'; import { dayKey } from './CalendarView'; -import type { CalendarDay } from '../../api/types'; /** * Przesunięcie dnia treningowego aktywnego planu z poziomu kalendarza. * 409 PLAN_DAY_TAKEN (ktoś już ma trening w terminie) nie jest ślepym błędem: * serwis zwraca details.conflictDayId, a dialog proponuje zamianę dni. + * Prop `day` celowo strukturalny — dialog używany też z poziomu Dashboardu + * (okno decyzji o pominiętym dniu), gdzie dzień nie jest obiektem CalendarDay. */ export function MoveDayDialog({ open, @@ -22,7 +23,7 @@ export function MoveDayDialog({ }: { open: boolean; onClose: () => void; - day: CalendarDay; + day: { id: string; date: string; planId: string; planStartDate: string | null }; }) { const { t } = useTranslation(); const queryClient = useQueryClient(); diff --git a/app/src/components/plans/SkippedDayDialog.tsx b/app/src/components/plans/SkippedDayDialog.tsx new file mode 100644 index 0000000..2488f04 --- /dev/null +++ b/app/src/components/plans/SkippedDayDialog.tsx @@ -0,0 +1,95 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useQueryClient } from '@tanstack/react-query'; +import type { Dashboard } from '../../api/types'; +import { acceptSkippedDay } from '../../api/queries'; +import { apiErrorMessage } from '../../lib/errors'; +import { fmtDate } from '../../lib/format'; +import { Button, ErrorText, Modal } from '../ui'; +import { useToast } from '../toast'; +import { MoveDayDialog } from '../calendar/MoveDayDialog'; + +/** + * Decyzja o pominiętym dniu treningowym (Dashboard): zostać przy pominięciu albo + * przesunąć dzień na inny termin. Przesunięcie wraca dniem do PLANNED i realnie + * naprawia killstreak; akceptacja zamyka dialog (skipResolvedAt po stronie API). + * Zamknięcie X/Esc nie jest decyzją — dialog wróci przy następnej wizycji, + * ale maksymalnie raz na sesję przeglądarki (sekwestr w sessionStorage po stronie + * Dashboardu). + */ +export function SkippedDayDialog({ + open, + onClose, + pending, +}: { + open: boolean; + onClose: () => void; + pending: NonNullable; +}) { + const { t } = useTranslation('dashboard'); + const queryClient = useQueryClient(); + const { push } = useToast(); + const [moveOpen, setMoveOpen] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + + const accept = async () => { + setError(''); + setBusy(true); + try { + await acceptSkippedDay(pending.plan.id, pending.dayId); + await queryClient.invalidateQueries({ queryKey: ['dashboard'] }); + push(t('skipPromptAcceptedToast'), 'success'); + onClose(); + } catch (e) { + setError(apiErrorMessage(e, t)); + } finally { + setBusy(false); + } + }; + + return ( + <> + {/* podczas okna przesunięcia zewnętrzne okno ustępuje miejsca (jeden modal naraz) */} + +

+ {t('skipPromptIntro', { plan: pending.plan.title, date: fmtDate(pending.date) })} +

+

{t('skipPromptStreak')}

+ {pending.unresolvedCount > 1 && ( +

+ {t('skipPromptMore', { count: pending.unresolvedCount - 1 })} +

+ )} + {error && {error}} +
+ + +
+
+ { + setMoveOpen(false); + // niezależnie od wyniku: decyzja mogła zapaść — odśwież pendingSkip + void queryClient.invalidateQueries({ queryKey: ['dashboard'] }); + }} + day={{ + id: pending.dayId, + date: pending.date, + planId: pending.plan.id, + planStartDate: pending.plan.startDate, + }} + /> + + ); +} diff --git a/app/src/i18n/locales/en/dashboard.json b/app/src/i18n/locales/en/dashboard.json index 8c48e07..02bda79 100644 --- a/app/src/i18n/locales/en/dashboard.json +++ b/app/src/i18n/locales/en/dashboard.json @@ -23,6 +23,13 @@ "moveConflict": "Another workout is already planned on that date. You can swap the two days.", "moveLimitHint": "The date cannot be in the past or before the plan start." }, + "skipPromptTitle": "Skipped training day", + "skipPromptIntro": "The training day {{date}} in plan {{plan}} was skipped.", + "skipPromptStreak": "Skipped days break your killstreak. Keep this day as skipped or move it to another date — the workout then returns to the plan.", + "skipPromptMore_one": "{{count}} more skipped day is waiting for your decision.", + "skipPromptMore_other": "{{count}} more skipped days are waiting for your decision.", + "skipPromptKeep": "Keep as skipped", + "skipPromptAcceptedToast": "The day stays skipped.", "greetingNight": "Sleep well", "greetingEvening": "Good evening", "greetingDay": "Good morning", diff --git a/app/src/i18n/locales/pl/dashboard.json b/app/src/i18n/locales/pl/dashboard.json index 80f76a0..0bb64ee 100644 --- a/app/src/i18n/locales/pl/dashboard.json +++ b/app/src/i18n/locales/pl/dashboard.json @@ -23,6 +23,15 @@ "moveConflict": "W tym terminie jest już zaplanowany inny trening. Możesz zamienić te dni.", "moveLimitHint": "Termin nie może być w przeszłości ani przed startem planu." }, + "skipPromptTitle": "Pominięty dzień treningowy", + "skipPromptIntro": "Dzień {{date}} w planie {{plan}} został pominięty.", + "skipPromptStreak": "Pominięte dni przerywają serię (killstreak). Zostaw ten dzień jako pominięty albo przesuń go na inny termin — trening wróci wtedy do planu.", + "skipPromptMore_one": "Czeka jeszcze {{count}} pominięty dzień.", + "skipPromptMore_few": "Czekają jeszcze {{count}} pominięte dni.", + "skipPromptMore_many": "Czeka jeszcze {{count}} pominiętych dni.", + "skipPromptMore_other": "Czeka jeszcze {{count}} pominiętych dni.", + "skipPromptKeep": "Zostaw pominięty", + "skipPromptAcceptedToast": "Dzień pozostał pominięty.", "greetingNight": "Dobrej nocy", "greetingEvening": "Dobry wieczór", "greetingDay": "Dzień dobry", diff --git a/app/src/pages/Dashboard.tsx b/app/src/pages/Dashboard.tsx index 796954d..a4ae493 100644 --- a/app/src/pages/Dashboard.tsx +++ b/app/src/pages/Dashboard.tsx @@ -5,6 +5,7 @@ import { CalendarPlus, Dumbbell, Megaphone, Play } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; import { useActiveSession, useDashboard, useFeed } from '../api/queries'; import { FeedItemRow } from '../components/FeedItemRow'; +import { SkippedDayDialog } from '../components/plans/SkippedDayDialog'; import { useAuth } from '../store/auth'; import { fmtDate, @@ -48,6 +49,20 @@ function planWeekNo(startDate: string | null): number | null { return Math.max(1, Math.floor((Date.now() - start) / (7 * 86_400_000)) + 1); } +/* Pominięcia zamknięte X/Esc w tej karcie przeglądarki: maksymalnie raz na + sesję — odświeżenie strony w tej samej karcie pozostaje cicho. */ +const SKIP_DISMISSED_KEY = 'fitos-skip-dismissed'; + +function readDismissedSkips(): string[] { + try { + const raw = sessionStorage.getItem(SKIP_DISMISSED_KEY); + const parsed = raw ? JSON.parse(raw) : []; + return Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === 'string') : []; + } catch { + return []; + } +} + /* Wykres słupkowy (aria-hidden): serie w 12 ostatnich tygodniach — prawdziwe dane z API. */ function WeekBars({ values }: { values: number[] }) { const max = Math.max(0, ...values); @@ -313,6 +328,7 @@ export default function Dashboard() { const { data: activeData } = useActiveSession(); const active = activeData?.session ?? null; useTick(!!active); + const [dismissedSkips, setDismissedSkips] = useState(readDismissedSkips); if (isLoading) { return ( @@ -367,6 +383,22 @@ export default function Dashboard() { const historyVisible = data.killstreak > 0 || history.completedPlans > 0 || history.sessions > 0 || history.sets > 0; + // Decyzja o pominiętym dniu: dialog tylko dla nierozstrzygniętego pominięcia + // aktywnego planu, niezamkniętego X/Esc w tej sesji karty. Brak akcji w topbarze — + // to decyzja użytkownika, nie akcja strony. + const pendingSkip = data.pendingSkip ?? null; + const skipOpen = pendingSkip != null && !dismissedSkips.includes(pendingSkip.dayId); + const dismissSkip = () => { + if (!pendingSkip) return; + const next = [...dismissedSkips, pendingSkip.dayId]; + try { + sessionStorage.setItem(SKIP_DISMISSED_KEY, JSON.stringify(next)); + } catch { + // prywatny tryb / brak sessionStorage: decyzja „odwołana" tylko do reloada + } + setDismissedSkips(next); + }; + return ( <> {/* Powitanie + data/tydzień planu */} @@ -557,6 +589,10 @@ export default function Dashboard() {
+ + {pendingSkip != null && ( + + )} ); } diff --git a/app/test/SkippedDayDialog.test.tsx b/app/test/SkippedDayDialog.test.tsx new file mode 100644 index 0000000..02db8c6 --- /dev/null +++ b/app/test/SkippedDayDialog.test.tsx @@ -0,0 +1,247 @@ +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter } from 'react-router-dom'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import App from '../src/App'; +import { useAuth } from '../src/store/auth'; +import { setAccessToken } from '../src/api/client'; +import type { User } from '../src/api/types'; + +const USER: User = { + id: 'u1', + email: 'jan@test.local', + firstName: 'Jan', + lastName: 'Kowalski', + age: 30, + heightCm: 180, + phone: '+48 600 000 000', + isAdmin: false, + availability: null, + priorities: null, + exclusions: null, + developMuscles: [], + canDoMuscles: [], + difficultMuscles: [], + avoidMuscles: [], + createdAt: '2026-08-22T10:00:00.000Z', +}; + +const DAY = 86_400_000; +const ago = (days: number) => new Date(Date.now() - days * DAY).toISOString(); +const isoIn = (days: number) => { + const d = new Date(); + d.setDate(d.getDate() + days); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String( + d.getDate(), + ).padStart(2, '0')}`; +}; + +function pendingSkip(overrides: Record = {}) { + return { + dayId: 'day-skip', + date: ago(2), + skippedAt: ago(2), + exerciseCount: 1, + unresolvedCount: 2, + plan: { id: 'plan-1', title: 'Plan testowy', startDate: ago(10) }, + ...overrides, + }; +} + +function dashBody(overrides: Record = {}) { + return { + killstreak: 0, + killstreakBest: 0, + killstreakDays: [], + history: { completedPlans: 0, sessions: 0, sets: 0 }, + week: null, + lastSessionAt: null, + firstSessionAt: null, + weeklySets: [], + nextTraining: null, + progress: { completed: 4, total: 5, percent: 80 }, + pendingSkip: null, + extra: { sets: 0 }, + missing: { sets: 0 }, + activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: ago(10) }, + ...overrides, + }; +} + +const calls: { method: string; url: string; body: unknown }[] = []; + +function jsonResponse(status: number, body: unknown) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); +} + +function mockApi(dash: unknown) { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + const method = (init?.method ?? 'GET').toUpperCase(); + calls.push({ method, url, body: init?.body ? JSON.parse(String(init.body)) : null }); + if (method === 'POST' && url.includes('/skip/accept')) + return jsonResponse(200, { day: { id: 'day-skip', status: 'SKIPPED' } }); + if (method === 'PATCH' && url.includes('/move')) + return jsonResponse(200, { + day: { id: 'day-skip', date: new Date().toISOString(), status: 'PLANNED', dayOfWeek: 1 }, + swappedWith: null, + }); + if (url.includes('/auth/login')) + return jsonResponse(200, { user: USER, accessToken: 'tok-1' }); + if (url.includes('/auth/refresh')) + return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } }); + if (url.includes('/me/active-session')) return jsonResponse(200, { session: null }); + if (url.includes('/me/feed')) return jsonResponse(200, { items: [], nextCursor: null }); + if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] }); + if (url.includes('/dashboard')) return jsonResponse(200, dash); + return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } }); + }), + ); +} + +function renderApp() { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } }, + }); + return render( + + + + + , + ); +} + +async function login(user: ReturnType) { + 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; + await user.type(email, 'jan@test.local'); + await user.type(password, 'Password123!'); + await user.click(screen.getByRole('button', { name: 'Zaloguj' })); + // dialog decyzji startuje od razu po wczytaniu -> reszta aplikacji ma aria-hidden, + // więc role-queries nie widzą h1 Topbaru; sprawdzamy DOM bezpośrednio + await waitFor(() => + expect( + Array.from(document.querySelectorAll('h1')).some((h) => h.textContent === 'Dashboard'), + ).toBe(true), + ); +} + +async function openSkipDialog(user: ReturnType) { + mockApi(dashBody({ pendingSkip: pendingSkip() })); + renderApp(); + await login(user); + return screen.findByRole('heading', { name: 'Pominięty dzień treningowy' }); +} + +beforeEach(() => { + calls.length = 0; + setAccessToken(null); + localStorage.clear(); + sessionStorage.clear(); + useAuth.setState({ user: null, ready: false }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Dashboard — dialog decyzji o pominiętym dniu', () => { + it('pendingSkip otwiera dialog z treścią i licznikiem pozostałych pominięć', async () => { + const user = userEvent.setup(); + const title = await openSkipDialog(user); + expect(title).toBeInTheDocument(); + // plan + treść o serii; licznik: unresolvedCount 2 => „jeszcze 1” (pluralika PL) + expect(screen.getByText(/został pominięty/)).toBeInTheDocument(); + expect(screen.getByText(/przerywają serię/)).toBeInTheDocument(); + expect(screen.getByText('Czeka jeszcze 1 pominięty dzień.')).toBeInTheDocument(); + // oba rozwiązania decyzji, bez akcji w topbarze + expect(screen.getByRole('button', { name: 'Zostaw pominięty' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Przesuń dzień' })).toBeInTheDocument(); + }); + + it('„Zostaw pominięty” → POST skip/accept, toast i zniknięcie dialogu', async () => { + const user = userEvent.setup(); + await openSkipDialog(user); + await user.click(screen.getByRole('button', { name: 'Zostaw pominięty' })); + expect(await screen.findByText('Dzień pozostał pominięty.')).toBeInTheDocument(); + await waitFor(() => + expect(calls).toContainEqual( + expect.objectContaining({ + method: 'POST', + url: expect.stringContaining('/plans/plan-1/days/day-skip/skip/accept'), + }), + ), + ); + await waitFor(() => + expect( + screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }), + ).not.toBeInTheDocument(), + ); + }); + + it('X/Esc to nie decyzja: brak POST, a ponowne wejście na Dashboard nie pokazuje dialogu', async () => { + const user = userEvent.setup(); + await openSkipDialog(user); + await user.keyboard('{Escape}'); + await waitFor(() => + expect( + screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }), + ).not.toBeInTheDocument(), + ); + expect(calls.some((c) => c.url.includes('/skip/accept'))).toBe(false); + expect(sessionStorage.getItem('fitos-skip-dismissed')).toContain('day-skip'); + + // powrót na Dashboard w tej samej sesji karty: ten sam dzień nie startuje dialogu ponownie + renderApp(); + await waitFor(() => + expect( + Array.from(document.querySelectorAll('h1')).some((h) => h.textContent === 'Dashboard'), + ).toBe(true), + ); + expect( + screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }), + ).not.toBeInTheDocument(); + }); + + it('„Przesuń dzień” otwiera MoveDayDialog i PATCH move z nową datą', async () => { + const user = userEvent.setup(); + await openSkipDialog(user); + await user.click(screen.getByRole('button', { name: 'Przesuń dzień' })); + + const dialog = await screen.findByRole('dialog', { name: 'Przesunięcie dnia treningowego' }); + const target = isoIn(5); + const dateInput = dialog.querySelector('input[type="date"]') as HTMLInputElement; + fireEvent.change(dateInput, { target: { value: target } }); + await user.click(within(dialog).getByRole('button', { name: 'Przesuń' })); + + await waitFor(() => + expect(calls).toContainEqual( + expect.objectContaining({ + method: 'PATCH', + url: expect.stringContaining('/plans/plan-1/days/day-skip/move'), + body: expect.objectContaining({ date: target }), + }), + ), + ); + expect(await screen.findByText(/Trening przesunięty na/)).toBeInTheDocument(); + }); + + it('brak pendingSkip w odpowiedzi (starszy kontrakt/mock): dialog się nie pokazuje', async () => { + const user = userEvent.setup(); + mockApi(dashBody()); + renderApp(); + await login(user); + expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument(); + expect( + screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }), + ).not.toBeInTheDocument(); + }); +}); diff --git a/app/test/e2e/presence.spec.ts b/app/test/e2e/presence.spec.ts index 9db6ff6..d300e5b 100644 --- a/app/test/e2e/presence.spec.ts +++ b/app/test/e2e/presence.spec.ts @@ -31,7 +31,8 @@ async function login(page: Page) { await page.locator('input[type="email"]').fill('test@fitos.pl'); await page.locator('input[type="password"]').fill('haslo123'); await page.getByRole('button', { name: 'Zaloguj' }).click(); - await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + // modal keep-alive startuje sam i chowa shell (aria-hidden) — asercja po DOM, nie po drzewie a11y + await expect(page.locator('h1', { hasText: 'Dashboard' })).toBeVisible(); } async function openGymDetail(page: Page) { diff --git a/app/test/e2e/skipped-day.spec.ts b/app/test/e2e/skipped-day.spec.ts new file mode 100644 index 0000000..1a8aadb --- /dev/null +++ b/app/test/e2e/skipped-day.spec.ts @@ -0,0 +1,116 @@ +import { test, expect } from './fixtures'; +import { mockApi, TEST_DASHBOARD } from './mock-api'; + +const DAY = 86_400_000; +const ago = (days: number) => new Date(Date.now() - days * DAY).toISOString(); +const isoIn = (days: number) => { + const d = new Date(); + d.setDate(d.getDate() + days); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String( + d.getDate(), + ).padStart(2, '0')}`; +}; + +const dashboardWithSkip = { + ...TEST_DASHBOARD, + pendingSkip: { + dayId: 'day-skip', + date: ago(2), + skippedAt: ago(2), + exerciseCount: 1, + unresolvedCount: 2, + plan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01' }, + }, +}; + +async function login(page: import('@playwright/test').Page) { + await page.goto('/login'); + await page.locator('input[type="email"]').fill('test@fitos.pl'); + await page.locator('input[type="password"]').fill('haslo123'); + await page.getByRole('button', { name: 'Zaloguj' }).click(); + // Radix chowa shell (aria-hidden), gdy dialog decyzji startuje sam — asercja po DOM, nie po drzewie a11y + await expect(page.locator('h1', { hasText: 'Dashboard' })).toBeVisible(); +} + +test('pominięty dzień: dialog decyzji startuje na Dashboardzie i akceptacja odsyła POST', async ({ + page, +}) => { + let acceptCalls = 0; + mockApi(page, { dashboard: dashboardWithSkip }); + page.route('**/api/v1/plans/plan-1/days/day-skip/skip/accept', (route) => { + acceptCalls++; + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + day: { id: 'day-skip', status: 'SKIPPED', skipResolvedAt: new Date().toISOString() }, + }), + }); + }); + + await login(page); + + const dialog = page.getByRole('dialog', { name: 'Pominięty dzień treningowy' }); + await expect(dialog).toBeVisible(); + await expect(dialog.getByText(/Plan testowy/)).toBeVisible(); + await expect(dialog.getByText(/przerywają serię/)).toBeVisible(); + await expect(dialog.getByText('Czeka jeszcze 1 pominięty dzień.')).toBeVisible(); + + // akcje wyłącznie w oknie — topbar Dashboardu pozostaje bez akcji + await expect(dialog.getByRole('button', { name: 'Zostaw pominięty' })).toBeVisible(); + await dialog.getByRole('button', { name: 'Zostaw pominięty' }).click(); + + await expect(page.getByText('Dzień pozostał pominięty.')).toBeVisible(); + await expect.poll(() => acceptCalls).toBe(1); + await expect(page.getByRole('dialog', { name: 'Pominięty dzień treningowy' })).toBeHidden(); +}); + +test('pominięty dzień: „Przesuń dzień” otwiera okno przesunięcia i PATCH move bez akceptacji', async ({ + page, +}) => { + let acceptCalls = 0; + let moveBody: Record | null = null; + mockApi(page, { dashboard: dashboardWithSkip }); + page.route('**/api/v1/plans/plan-1/days/day-skip/skip/accept', (route) => { + acceptCalls++; + return route.fulfill({ status: 200, contentType: 'application/json', body: '{}' }); + }); + page.route('**/api/v1/plans/plan-1/days/day-skip/move', (route) => { + moveBody = JSON.parse(route.request().postData() ?? '{}'); + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + day: { id: 'day-skip', date: new Date().toISOString(), status: 'PLANNED', dayOfWeek: 1 }, + swappedWith: null, + }), + }); + }); + + await login(page); + + const skip = page.getByRole('dialog', { name: 'Pominięty dzień treningowy' }); + await expect(skip).toBeVisible(); + await skip.getByRole('button', { name: 'Przesuń dzień' }).click(); + + const moveDialog = page.getByRole('dialog', { name: 'Przesunięcie dnia treningowego' }); + await expect(moveDialog).toBeVisible(); + const target = isoIn(5); + await moveDialog.locator('input[type="date"]').fill(target); + await moveDialog.getByRole('button', { name: 'Przesuń' }).click(); + + await expect(page.getByText(/Trening przesunięty na/)).toBeVisible(); + await expect + .poll(() => moveBody) + .toEqual(expect.objectContaining({ date: target, reason: null })); + expect(acceptCalls).toBe(0); +}); + +test('mockApi bez pendingSkip (stary kontrakt): dialog decyzji nie startuje', async ({ page }) => { + mockApi(page); + await login(page); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + await expect( + page.getByRole('dialog', { name: 'Pominięty dzień treningowy' }), + ).not.toBeVisible(); +});