Plany: decyzja o pominietych dniach — dialog na Dashboardzie (Zostaw pominiety / Przesun) z API skip/accept, skipResolvedAt + pendingSkip w dashboardzie, blokada autoukonczen planow w schedulerze (api 852, app unit 255, e2e 119 przechodza)

This commit is contained in:
Tisachi
2026-10-27 20:11:53 +01:00
committed by tisachi
parent 7ee221e8b5
commit dd9645bf88
22 changed files with 973 additions and 18 deletions

View File

@@ -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}:

View File

@@ -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

View File

@@ -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,

View File

@@ -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 },

View File

@@ -1354,6 +1354,24 @@ export const openapi: Record<string, unknown> = {
},
},
},
'/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<string, unknown> = {
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: [] }],
},
},