Plany: wizard 3-etapowy tworzenia/edycji, silownia i alias tygodnia (UX + API + migracja)

This commit is contained in:
tisachi
2026-09-12 15:16:13 +02:00
parent a2d31ee46b
commit ef2fa726bb
26 changed files with 1340 additions and 361 deletions

View File

@@ -0,0 +1,11 @@
-- AlterTable
ALTER TABLE "PlanWeek" ADD COLUMN "customName" TEXT;
-- AlterTable
ALTER TABLE "TrainingPlan" ADD COLUMN "gymId" TEXT;
-- CreateIndex
CREATE INDEX "TrainingPlan_gymId_idx" ON "TrainingPlan"("gymId");
-- AddForeignKey
ALTER TABLE "TrainingPlan" ADD CONSTRAINT "TrainingPlan_gymId_fkey" FOREIGN KEY ("gymId") REFERENCES "Gym"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@@ -85,45 +85,45 @@ enum EquipmentKind {
}
model User {
id String @id @default(cuid())
email String @unique
passwordHash String
firstName String?
lastName String?
nickname String?
socialMedia Json?
age Int?
heightCm Float?
phone String? @unique
isAdmin Boolean @default(false)
tokenVersion Int @default(0)
availability Json?
priorities String?
exclusions String?
id String @id @default(cuid())
email String @unique
passwordHash String
firstName String?
lastName String?
nickname String?
socialMedia Json?
age Int?
heightCm Float?
phone String? @unique
isAdmin Boolean @default(false)
tokenVersion Int @default(0)
availability Json?
priorities String?
exclusions String?
developMuscles String[] @default([])
canDoMuscles String[] @default([])
difficultMuscles String[] @default([])
avoidMuscles String[] @default([])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships GymMembership[]
plans TrainingPlan[]
createdPlans TrainingPlan[] @relation("PlanCreator")
weightEntries BodyMeasurement[]
memberships GymMembership[]
plans TrainingPlan[]
createdPlans TrainingPlan[] @relation("PlanCreator")
weightEntries BodyMeasurement[]
circumferenceEntries CircumferenceMeasurement[]
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
gymRatings GymRating[]
gymClaims GymClaim[]
claimsDecided GymClaim[] @relation("ClaimDecider")
gymInvitations GymInvitation[]
gymInvitationsSent GymInvitation[] @relation("GymInviteSender")
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
gymRatings GymRating[]
gymClaims GymClaim[]
claimsDecided GymClaim[] @relation("ClaimDecider")
gymInvitations GymInvitation[]
gymInvitationsSent GymInvitation[] @relation("GymInviteSender")
}
/// Audit trail of user actions (app + trainer level). Best-effort writes,
@@ -147,16 +147,16 @@ model ActivityLog {
/// Trainer ↔ trainee relation. Created as PENDING (invitation), becomes ACTIVE
/// after the invited party accepts. Invitations expire after 7 days.
model Coaching {
id String @id @default(cuid())
trainerId String
userId String
gymId String?
status CoachingStatus @default(PENDING)
note String?
invitedBy String
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
id String @id @default(cuid())
trainerId String
userId String
gymId String?
status CoachingStatus @default(PENDING)
note String?
invitedBy String
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
trainer User @relation("CoachingTrainer", fields: [trainerId], references: [id], onDelete: Cascade)
user User @relation("CoachingUser", fields: [userId], references: [id], onDelete: Cascade)
@@ -216,26 +216,27 @@ model ConversationRead {
}
model Gym {
id String @id @default(cuid())
name String
location String?
id String @id @default(cuid())
name String
location String?
availability Json?
capacity Int?
capacity Int?
/// Existing rows default to REAL; VIRTUAL gyms are created by users.
kind GymKind @default(REAL)
kind GymKind @default(REAL)
/// Only meaningful for VIRTUAL gyms (hidden from the public list).
isPrivate Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isPrivate Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships GymMembership[]
memberships GymMembership[]
customExercises Exercise[]
equipment GymEquipment[]
exceptions GymException[]
ratings GymRating[]
claims GymClaim[]
invitations GymInvitation[]
photos GymPhoto[]
equipment GymEquipment[]
exceptions GymException[]
ratings GymRating[]
claims GymClaim[]
invitations GymInvitation[]
photos GymPhoto[]
plans TrainingPlan[]
}
/// Zdjęcie w galerii siłowni REAL. `order` = kolejność; okładka = najmniejsze `order` (tie → najstarsze `createdAt`).
@@ -262,7 +263,7 @@ model GymRating {
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([gymId, userId])
@@index([gymId])
@@ -271,33 +272,33 @@ model GymRating {
/// A claim: verification of an existing virtual gym (gymId set) or a request for a
/// new real gym (gymId null, gym data carried in the claim).
model GymClaim {
id String @id @default(cuid())
id String @id @default(cuid())
/// null = claim for a NEW real gym (data below); set = verification of that virtual gym.
gymId String?
userId String
gymId String?
userId String
/// Gym data — only for claims with gymId = null:
gymName String?
gymLocation String?
gymName String?
gymLocation String?
gymAvailability Json?
gymCapacity Int?
gymCapacity Int?
/// Applicant data / proof:
description String
companyName String?
nip String?
phone String?
email String?
description String
companyName String?
nip String?
phone String?
email String?
/// Verification claims only: overrides gym.location on approval.
address String?
status ClaimStatus @default(PENDING)
rejectReason String?
decidedById String?
decidedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
address String?
status ClaimStatus @default(PENDING)
rejectReason String?
decidedById String?
decidedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
decidedBy User? @relation("ClaimDecider", fields: [decidedById], references: [id], onDelete: SetNull)
gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
decidedBy User? @relation("ClaimDecider", fields: [decidedById], references: [id], onDelete: SetNull)
documents GymClaimDocument[]
@@index([gymId, status])
@@ -320,14 +321,14 @@ model GymClaimDocument {
/// Invitation to a PRIVATE virtual gym (owner invites a specific user, 7-day TTL).
model GymInvitation {
id String @id @default(cuid())
id String @id @default(cuid())
gymId String
userId String
invitedById String
status GymInvitationStatus @default(PENDING)
invitedAt DateTime @default(now())
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -342,10 +343,10 @@ model GymInvitation {
/// Gym ↔ equipment instance: how many units of a catalog item a gym has
/// (e.g. two pairs of dumbbells).
model GymEquipment {
id String @id @default(cuid())
id String @id @default(cuid())
gymId String
equipmentId String
quantity Int @default(1)
quantity Int @default(1)
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
equipment Equipment @relation(fields: [equipmentId], references: [id], onDelete: Cascade)
@@ -381,7 +382,7 @@ model FocusArea {
}
model GymMembership {
id String @id @default(cuid())
id String @id @default(cuid())
userId String
gymId String
roles GymRole[] @default([MEMBER])
@@ -431,8 +432,8 @@ model Equipment {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
exercises Exercise[]
gyms GymEquipment[]
exercises Exercise[]
gyms GymEquipment[]
}
model Exercise {
@@ -464,7 +465,7 @@ model Exercise {
gym Gym? @relation(fields: [gymId], references: [id], onDelete: SetNull)
equipment Equipment[]
planExercises PlanExercise[]
planExercises PlanExercise[]
sessionExercises SessionExercise[]
@@index([source])
@@ -478,20 +479,26 @@ model TrainingPlan {
status PlanStatus @default(DRAFT)
weeksCount Int
startDate DateTime?
/// Informacyjna — siłownia, w której realizowany jest plan (bez wpływu na scheduler).
gymId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
creator User? @relation("PlanCreator", fields: [creatorId], references: [id], onDelete: SetNull)
gym Gym? @relation(fields: [gymId], references: [id], onDelete: SetNull)
weeks PlanWeek[]
@@index([userId, status])
@@index([gymId])
}
model PlanWeek {
id String @id @default(cuid())
planId String
index Int
id String @id @default(cuid())
planId String
index Int
/// Opcjonalny alias tygodnia (np. „Deload").
customName String?
plan TrainingPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
days PlanDay[]
@@ -500,15 +507,15 @@ model PlanWeek {
}
model PlanDay {
id String @id @default(cuid())
id String @id @default(cuid())
weekId String
dayOfWeek Int
date DateTime?
status DayStatus @default(PLANNED)
status DayStatus @default(PLANNED)
completedAt DateTime?
skippedAt DateTime?
week PlanWeek @relation(fields: [weekId], references: [id], onDelete: Cascade)
week PlanWeek @relation(fields: [weekId], references: [id], onDelete: Cascade)
moveLog DayMove[]
exercises PlanExercise[]
sessions TrainingSession[]
@@ -542,19 +549,19 @@ model PlanExercise {
}
model PlanSet {
id String @id @default(cuid())
exerciseId String
index Int
reps Int?
loadKg Float?
restSec Int?
rir Int?
difficulty Int?
cardioBpm Int?
timeSec Int?
speed Float?
id String @id @default(cuid())
exerciseId String
index Int
reps Int?
loadKg Float?
restSec Int?
rir Int?
difficulty Int?
cardioBpm Int?
timeSec Int?
speed Float?
exercise PlanExercise @relation(fields: [exerciseId], references: [id], onDelete: Cascade)
exercise PlanExercise @relation(fields: [exerciseId], references: [id], onDelete: Cascade)
sessionSets SessionSet[]
@@unique([exerciseId, index])
@@ -567,9 +574,9 @@ model TrainingSession {
startedAt DateTime @default(now())
endedAt DateTime?
day PlanDay @relation(fields: [dayId], references: [id], onDelete: Cascade)
exercises SessionExercise[]
messagesAsSession Message[] @relation("MessageSession")
day PlanDay @relation(fields: [dayId], references: [id], onDelete: Cascade)
exercises SessionExercise[]
messagesAsSession Message[] @relation("MessageSession")
@@index([dayId, status])
}

View File

@@ -25,12 +25,16 @@ const planDaySchema = z.object({
const planWeekSchema = z.object({
index: z.number().int().min(0),
// Opcjonalny alias tygodnia (np. „Deload").
customName: z.string().max(40).nullable().optional(),
days: z.array(planDaySchema),
});
const planBaseSchema = z.object({
title: z.string().min(1).max(200),
weeksCount: z.number().int().min(1).max(8),
// Informacyjna — siłownia, w której realizowany jest plan (właściciel musi być jej członkiem).
gymId: z.string().nullable().optional(),
weeks: z.array(planWeekSchema),
});
@@ -51,7 +55,5 @@ export const updatePlanSchema = planBaseSchema.refine((d) => d.weeks.length ===
});
export const activateSchema = z.object({
startDate: z
.string()
.refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date'),
startDate: z.string().refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date'),
});

View File

@@ -21,7 +21,10 @@ import {
withdrawInvitation,
} from '../services/trainer.js';
import { addTraineeComment, deleteTraineeComment } from '../services/comments.js';
import { getTraineeExerciseProgress, getTraineeLatestResults } from '../services/exerciseProgress.js';
import {
getTraineeExerciseProgress,
getTraineeLatestResults,
} from '../services/exerciseProgress.js';
import {
abandonPlan,
activatePlan,
@@ -206,7 +209,12 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
asyncHandler(async (req, res) => {
const parsed = searchQuerySchema.safeParse(req.query);
if (!parsed.success) throw badRequest('firstName and lastName query parameters are required');
const result = await searchUsers(prisma, req.user!.id, parsed.data.firstName, parsed.data.lastName);
const result = await searchUsers(
prisma,
req.user!.id,
parsed.data.firstName,
parsed.data.lastName,
);
res.json(result);
}),
);
@@ -351,7 +359,12 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
asyncHandler(async (req, res) => {
const parsed = calendarQuerySchema.safeParse(req.query);
if (!parsed.success) throw badRequest('month must be in YYYY-MM format');
const result = await getTraineeCalendar(prisma, req.user!.id, req.params.userId, parsed.data.month);
const result = await getTraineeCalendar(
prisma,
req.user!.id,
req.params.userId,
parsed.data.month,
);
res.json(result);
}),
);
@@ -421,11 +434,12 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/trainees/{userId}/plans:
* post:
* summary: Create a plan for the trainee (owner = trainee, creator = trainer)
* 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)
* tags: [Trainer]
* 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 / gym not a trainee membership }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
* 409: { description: Trainee already has an active plan }
@@ -474,11 +488,11 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* patch:
* summary: Replace plan structure (draft only)
* summary: Replace plan structure (draft only). Same body as POST (gymId, weeks[].customName)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft }
* 400: { description: Not a draft / gym not a trainee membership }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/

View File

@@ -27,12 +27,16 @@ export interface PlanDayInput {
export interface PlanWeekInput {
index: number;
/** Opcjonalny alias tygodnia (np. „Deload"). */
customName?: string | null;
days: PlanDayInput[];
}
export interface CreatePlanInput {
title: string;
weeksCount: number;
/** Informacyjna — siłownia, w której realizowany jest plan (właściciel musi być jej członkiem). */
gymId?: string | null;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
@@ -63,9 +67,28 @@ async function validateExercises(prisma: PrismaClient, weeks: PlanWeekInput[]) {
if (exercises.length !== exerciseIds.size) throw badRequest('Unknown exerciseId in plan');
}
/**
* Siłownia planu jest informacyjna, ale musi istnieć i właściciel planu
* (podopieczny w trybie trenera) musi być jej członkiem.
*/
async function validateGymMembership(
prisma: PrismaClient,
gymId: string | null | undefined,
ownerId: string,
) {
if (!gymId) return;
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw badRequest('Unknown gymId in plan');
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: ownerId, gymId } },
});
if (!membership) throw badRequest('Plan owner is not a member of the gym');
}
function weekData(weeks: PlanWeekInput[]) {
return weeks.map((w) => ({
index: w.index,
customName: w.customName ?? null,
days: {
create: w.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
@@ -87,6 +110,7 @@ export async function listPlans(prisma: PrismaClient, userId: string) {
orderBy: { createdAt: 'desc' },
include: {
creator: { select: { id: true, firstName: true, lastName: true } },
gym: { select: { id: true, name: true } },
weeks: { select: { days: { select: { status: true } } } },
},
});
@@ -115,6 +139,7 @@ export async function createPlan(
creatorId?: string,
) {
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, userId);
// Data startu: walidacja (poniedziałek) przed sprawdzeniem aktywnego planu.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
if (startOfStart) await assertNoActivePlan(prisma, userId);
@@ -125,11 +150,16 @@ export async function createPlan(
creatorId: creatorId ?? userId,
status: 'DRAFT',
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
weeks: { create: weekData(data.weeks) },
},
include: { gym: { select: { id: true, name: true } } },
});
if (startOfStart) await applyStartDate(prisma, plan.id, userId, startOfStart);
const updated = await prisma.trainingPlan.findUnique({ where: { id: plan.id } });
const updated = await prisma.trainingPlan.findUnique({
where: { id: plan.id },
include: { gym: { select: { id: true, name: true } } },
});
return {
plan: {
id: updated!.id,
@@ -137,6 +167,7 @@ export async function createPlan(
status: updated!.status,
weeksCount: updated!.weeksCount,
startDate: updated!.startDate,
gym: updated!.gym,
},
};
}
@@ -146,6 +177,7 @@ export async function getPlan(prisma: PrismaClient, planId: string, userId: stri
const full = await prisma.trainingPlan.findUnique({
where: { id: planId },
include: {
gym: { select: { id: true, name: true } },
weeks: {
orderBy: { index: 'asc' },
include: {
@@ -175,11 +207,17 @@ export async function updatePlan(
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be edited');
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, plan.userId);
await prisma.$transaction(async (tx) => {
await tx.planWeek.deleteMany({ where: { planId: plan.id } });
await tx.trainingPlan.update({
where: { id: plan.id },
data: { title: data.title, weeksCount: data.weeksCount, weeks: { create: weekData(data.weeks) } },
data: {
title: data.title,
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
weeks: { create: weekData(data.weeks) },
},
});
});
return { ok: true };

View File

@@ -364,7 +364,10 @@ export const openapi: Record<string, unknown> = {
schema: {
type: 'object',
required: ['name'],
properties: { name: { type: 'string' }, description: { type: 'string', nullable: true } },
properties: {
name: { type: 'string' },
description: { type: 'string', nullable: true },
},
},
},
},
@@ -457,7 +460,7 @@ export const openapi: Record<string, unknown> = {
post: {
tags: ['Plans'],
summary:
'Create plan: weeks -> days (dayOfWeek) -> exercises -> sets. Optional startDate (a Monday) creates and activates the plan in one step',
'Create plan: weeks -> days (dayOfWeek) -> exercises -> sets. Optional startDate (a Monday) creates and activates the plan in one step. Optional gymId (informational; the plan owner must be a gym member) and per-week customName (alias, max 40)',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
@@ -469,6 +472,11 @@ export const openapi: Record<string, unknown> = {
properties: {
title: { type: 'string' },
weeksCount: { type: 'integer', minimum: 1, maximum: 52 },
gymId: {
type: 'string',
nullable: true,
description: 'Informational gym; the plan owner must be a member of it',
},
startDate: {
type: 'string',
description: 'YYYY-MM-DD, must be a Monday of the current or a future week',
@@ -480,6 +488,7 @@ export const openapi: Record<string, unknown> = {
required: ['index', 'days'],
properties: {
index: { type: 'integer', minimum: 0 },
customName: { type: 'string', nullable: true, maxLength: 40 },
days: {
type: 'array',
items: {
@@ -538,7 +547,8 @@ export const openapi: Record<string, unknown> = {
},
patch: {
tags: ['Plans'],
summary: 'Replace plan structure (draft only)',
summary:
'Replace plan structure (draft only). Same body as POST /plans (gymId and weeks[].customName included)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
@@ -559,7 +569,11 @@ export const openapi: Record<string, unknown> = {
required: true,
content: {
'application/json': {
schema: { type: 'object', required: ['startDate'], properties: { startDate: { type: 'string' } } },
schema: {
type: 'object',
required: ['startDate'],
properties: { startDate: { type: 'string' } },
},
},
},
},
@@ -607,7 +621,11 @@ export const openapi: Record<string, unknown> = {
required: true,
content: {
'application/json': {
schema: { type: 'object', required: ['exerciseId'], properties: { exerciseId: { type: 'string' } } },
schema: {
type: 'object',
required: ['exerciseId'],
properties: { exerciseId: { type: 'string' } },
},
},
},
},
@@ -673,7 +691,8 @@ export const openapi: Record<string, unknown> = {
'/sessions/{id}/abandon': {
post: {
tags: ['Sessions'],
summary: 'Abandon session (data kept, day -> skipped, the training cannot be executed again)',
summary:
'Abandon session (data kept, day -> skipped, the training cannot be executed again)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
@@ -691,7 +710,12 @@ export const openapi: Record<string, unknown> = {
summary: 'Calendar — training days of the active plan in a month',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'month', in: 'query', schema: { type: 'string' }, description: 'YYYY-MM (default: current)' },
{
name: 'month',
in: 'query',
schema: { type: 'string' },
description: 'YYYY-MM (default: current)',
},
],
},
},

View File

@@ -390,6 +390,114 @@ describe('plans routes', () => {
});
});
describe('plans: gym and week alias', () => {
let token: string;
let exerciseId: string;
let gymId: string;
let otherGymId: string;
const body = (title: string) => ({
title,
weeksCount: 1,
weeks: [
{
index: 0,
customName: 'Deload',
days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] }],
},
],
});
beforeAll(async () => {
const reg = await registerViaApi();
token = reg.token;
exerciseId = (await createExercise()).id;
const gym = await prisma.gym.create({ data: { name: `Plan Gym ${rand()}` } });
gymId = gym.id;
const other = await prisma.gym.create({ data: { name: `Other Gym ${rand()}` } });
otherGymId = other.id;
await prisma.gymMembership.create({ data: { userId: reg.user.id, gymId, roles: ['MEMBER'] as never } });
});
it('creates a plan with gymId and per-week customName', async () => {
const app = buildApp();
const res = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Z siłownią'), gymId });
expect(res.status).toBe(201);
expect(res.body.plan.gym).toMatchObject({ id: gymId });
expect(res.body.plan.gym.name).toBeTruthy();
const detail = await app.get(`/api/v1/plans/${res.body.plan.id}`).set('Authorization', `Bearer ${token}`);
expect(detail.body.plan.gym).toMatchObject({ id: gymId });
expect(detail.body.plan.weeks[0].customName).toBe('Deload');
});
it('lists plans with the gym attached', async () => {
const app = buildApp();
const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`);
const found = res.body.plans.find((p: { title: string }) => p.title === 'Z siłownią');
expect(found.gym).toMatchObject({ id: gymId });
});
it('rejects creation with a gym the user is not a member of with 400', async () => {
const app = buildApp();
const res = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Bez członkostwa'), gymId: otherGymId });
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Plan owner is not a member of the gym');
});
it('rejects creation with an unknown gymId with 400', async () => {
const app = buildApp();
const res = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Nieznana siłownia'), gymId: 'nonexistent-gym' });
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Unknown gymId in plan');
});
it('rejects a week alias longer than 40 chars with 400', async () => {
const app = buildApp();
const b = body('Długi alias');
b.weeks[0].customName = 'a'.repeat(41);
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(b);
expect(res.status).toBe(400);
});
it('updates gymId and customName via PATCH', async () => {
const app = buildApp();
const created = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body('Do zmiany'));
const id = created.body.plan.id;
const res = await app
.patch(`/api/v1/plans/${id}`)
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Do zmiany v2'), gymId, weeks: [{ index: 0, customName: null, days: [] }] });
expect(res.status).toBe(200);
const detail = await app.get(`/api/v1/plans/${id}`).set('Authorization', `Bearer ${token}`);
expect(detail.body.plan.gym).toMatchObject({ id: gymId });
expect(detail.body.plan.weeks[0].customName).toBeNull();
});
it('clears gymId to null when the gym is deleted', async () => {
const app = buildApp();
const created = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Plan z siłownią do usunięcia'), gymId });
const id = created.body.plan.id;
await prisma.gym.delete({ where: { id: gymId } });
const detail = await app.get(`/api/v1/plans/${id}`).set('Authorization', `Bearer ${token}`);
expect(detail.body.plan.gym).toBeNull();
});
});
describe('plans: direct seeding sanity', () => {
it('seedPlan creates a consistent structure in the database', async () => {
const { user } = await createUser();
@@ -498,4 +606,26 @@ describe('plans: trainer-created plan (creator + owner access)', () => {
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${plainToken}`);
expect(res.status).toBe(404);
});
it('trainer can attach a gym the trainee is a member of', async () => {
const gym = await prisma.gym.create({ data: { name: `Trainee Gym ${rand()}` } });
await prisma.gymMembership.create({ data: { userId: traineeId, gymId: gym.id, roles: ['MEMBER'] as never } });
const res = await app
.post(`/api/v1/trainer/trainees/${traineeId}/plans`)
.set('Authorization', `Bearer ${trainerToken}`)
.send({ ...body('Plan z siłownią'), gymId: gym.id });
expect(res.status).toBe(201);
expect(res.body.plan.gym).toMatchObject({ id: gym.id });
});
it('trainer cannot attach a gym the trainee is NOT a member of (400)', async () => {
const gym = await prisma.gym.create({ data: { name: `Trainer-only Gym ${rand()}` } });
await prisma.gymMembership.create({ data: { userId: trainerId, gymId: gym.id, roles: ['TRAINER'] as never } });
const res = await app
.post(`/api/v1/trainer/trainees/${traineeId}/plans`)
.set('Authorization', `Bearer ${trainerToken}`)
.send({ ...body('Plan bez członkostwa'), gymId: gym.id });
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Plan owner is not a member of the gym');
});
});

View File

@@ -231,6 +231,7 @@ describe('listPlans', () => {
orderBy: { createdAt: 'desc' },
include: {
creator: { select: { id: true, firstName: true, lastName: true } },
gym: { select: { id: true, name: true } },
weeks: { select: { days: { select: { status: true } } } },
},
});