Plany: wznowienie ukonczonego/porzuconego planu (poprawki bez tworzenia nowego, blokada przy innym aktywnym)

This commit is contained in:
Tilumca
2026-10-15 01:42:26 +02:00
parent 8044b0a4bd
commit 27a1507e50
16 changed files with 649 additions and 31 deletions

View File

@@ -13,6 +13,7 @@ import {
getPlan,
listPlans,
listSharedWithMe,
reopenPlan,
sharePlan,
unsharePlan,
updatePlan,
@@ -250,6 +251,33 @@ export function createPlanRoutes({ prisma }: AppDeps) {
}),
);
/**
* @openapi
* /plans/{id}/reopen:
* post:
* summary: Reopen a completed or abandoned plan (back to ACTIVE)
* tags: [Plans]
* responses:
* 200: { description: OK }
* 400: { description: Only a completed or abandoned plan can be reopened }
* 409: { description: User already has an active plan }
*/
router.post(
'/:id/reopen',
asyncHandler(async (req, res) => {
await assertPlanOwner(prisma, req.params.id, req.user!.id);
const result = await reopenPlan(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.reopened',
entityType: 'plan',
entityId: req.params.id,
details: { title: result.title },
});
res.json(result);
}),
);
/**
* @openapi
* /plans/{id}/share:

View File

@@ -33,6 +33,7 @@ import {
deletePlan,
getPlan,
listPlans,
reopenPlan,
updatePlan,
} from '../services/plans.js';
import { activateSchema, createPlanSchema, updatePlanSchema } from './plans-schemas.js';
@@ -639,6 +640,36 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/reopen:
* post:
* summary: Reopen the trainee's completed/abandoned plan (back to ACTIVE)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Only a completed or abandoned plan can be reopened }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
* 409: { description: Trainee already has an active plan }
*/
router.post(
'/trainees/:userId/plans/:planId/reopen',
trainerOnly,
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await reopenPlan(prisma, req.params.planId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.reopened',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, traineeId: req.params.userId },
});
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/comments:

View File

@@ -414,6 +414,35 @@ export async function completePlan(prisma: PrismaClient, planId: string, userId:
return { ok: true, title: plan.title };
}
/**
* Cofnięcie zamknięcia planu (COMPLETED/ABANDONED -> ACTIVE). Służy do naprawy
* pomyłek (np. błędnie oznaczony plan) — dni SKIPPED nie są wskrzeszane, a plan
* bez dni zaplanowanych zostanie ponownie ukończony przez scheduler, gdy tylko
* wszystkie dni pozostaną domknięte.
*/
export async function reopenPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'COMPLETED' && plan.status !== 'ABANDONED')
throw badRequest('Only a completed or abandoned plan can be reopened');
// Jeden aktywny plan dotyczy właściciela (inicjatorem może być trener).
// Pre-check + częściowy indeks unikalny (TrainingPlan_userId_active_key)
// rozstrzyga równoległe wznowienia/aktywacje.
const otherActive = await prisma.trainingPlan.findFirst({
where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id } },
});
if (otherActive) throw conflict('User already has an active plan');
try {
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'ACTIVE' },
});
} catch (e) {
if (isPrismaUnique(e)) throw conflict('User already has an active plan');
throw e;
}
return { ok: true, title: plan.title };
}
/**
* The owner shares the plan with a user in an ACTIVE coaching relation
* (trainer <-> trainee, either direction). Recipients get read-only access.

View File

@@ -204,7 +204,8 @@ export const openapi: Record<string, unknown> = {
},
post: {
tags: ['Gyms'],
summary: 'Create a gym (creator becomes OWNER; admins only for REAL, REAL requires address)',
summary:
'Create a gym (creator becomes OWNER; admins only for REAL, REAL requires address)',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
@@ -716,16 +717,34 @@ export const openapi: Record<string, unknown> = {
'/plans/{id}/complete': {
post: {
tags: ['Plans'],
summary: 'Manually archive plan (only from ACTIVE status and only when no training day is still planned; an in-progress plan can only be abandoned)',
summary:
'Manually archive plan (only from ACTIVE status and only when no training day is still planned; an in-progress plan can only be abandoned)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
200: { description: 'OK' },
400: { description: 'Only an active plan can be completed / plan has pending training days' },
400: {
description: 'Only an active plan can be completed / plan has pending training days',
},
404: { description: 'Plan not found' },
},
},
},
'/plans/{id}/reopen': {
post: {
tags: ['Plans'],
summary:
'Reopen a completed or abandoned plan (back to ACTIVE; skipped days are not revived)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
200: { description: 'OK' },
400: { description: 'Only a completed or abandoned plan can be reopened' },
404: { description: 'Plan not found' },
409: { description: 'User already has an active plan' },
},
},
},
'/plans/{id}/share': {
post: {
tags: ['Plans'],
@@ -936,14 +955,22 @@ export const openapi: Record<string, unknown> = {
properties: {
name: { type: 'string' },
ownerId: { type: 'string', description: 'User mianowany właścicielem (OWNER)' },
addressLine1: { type: 'string', description: 'Ulica i numer, np. Mokotowska 12A' },
addressLine2: { type: 'string', nullable: true, description: 'Lokal/piętro itp.' },
addressLine1: {
type: 'string',
description: 'Ulica i numer, np. Mokotowska 12A',
},
addressLine2: {
type: 'string',
nullable: true,
description: 'Lokal/piętro itp.',
},
postalCode: { type: 'string', description: 'Kod pocztowy 00-001' },
city: { type: 'string' },
countryCode: { type: 'string', default: 'PL', description: 'ISO 3166-1 alpha-2' },
location: {
type: 'string',
description: 'Pole derivowane z adresu (ulica, kod miasto[, kraj]) — nie do zapisu',
description:
'Pole derivowane z adresu (ulica, kod miasto[, kraj]) — nie do zapisu',
},
availability: {
type: 'array',
@@ -1007,10 +1034,22 @@ export const openapi: Record<string, unknown> = {
name: { type: 'string' },
addressLine1: { type: 'string', nullable: true },
addressLine2: { type: 'string', nullable: true },
postalCode: { type: 'string', nullable: true, description: 'Kod pocztowy 00-001' },
postalCode: {
type: 'string',
nullable: true,
description: 'Kod pocztowy 00-001',
},
city: { type: 'string', nullable: true },
countryCode: { type: 'string', nullable: true, description: 'ISO 3166-1 alpha-2' },
availability: { type: 'array', nullable: true, items: { type: 'object', nullable: true } },
countryCode: {
type: 'string',
nullable: true,
description: 'ISO 3166-1 alpha-2',
},
availability: {
type: 'array',
nullable: true,
items: { type: 'object', nullable: true },
},
capacity: { type: 'integer', nullable: true },
},
},