Plany: PATCH z startDate (aktywacja przy zapisie) i udostepnianie planow trener-podopieczny (PlanShare, sekcja Udostepnione mi, widok read-only)
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "PlanShare" (
|
||||
"id" TEXT NOT NULL,
|
||||
"planId" TEXT NOT NULL,
|
||||
"sharedById" TEXT NOT NULL,
|
||||
"sharedWithId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "PlanShare_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PlanShare_sharedWithId_idx" ON "PlanShare"("sharedWithId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PlanShare_planId_sharedWithId_key" ON "PlanShare"("planId", "sharedWithId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PlanShare" ADD CONSTRAINT "PlanShare_planId_fkey" FOREIGN KEY ("planId") REFERENCES "TrainingPlan"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PlanShare" ADD CONSTRAINT "PlanShare_sharedById_fkey" FOREIGN KEY ("sharedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "PlanShare" ADD CONSTRAINT "PlanShare_sharedWithId_fkey" FOREIGN KEY ("sharedWithId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -110,6 +110,8 @@ model User {
|
||||
memberships GymMembership[]
|
||||
plans TrainingPlan[]
|
||||
createdPlans TrainingPlan[] @relation("PlanCreator")
|
||||
planSharesBy PlanShare[] @relation("PlanShareBy")
|
||||
planSharesWith PlanShare[] @relation("PlanShareWith")
|
||||
weightEntries BodyMeasurement[]
|
||||
circumferenceEntries CircumferenceMeasurement[]
|
||||
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
|
||||
@@ -484,15 +486,33 @@ model TrainingPlan {
|
||||
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)
|
||||
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[]
|
||||
shares PlanShare[]
|
||||
|
||||
@@index([userId, status])
|
||||
@@index([gymId])
|
||||
}
|
||||
|
||||
/// Explicit plan sharing (trainer <-> trainee): the owner shares a plan with a user
|
||||
/// in an ACTIVE coaching relation. Recipients get read-only access.
|
||||
model PlanShare {
|
||||
id String @id @default(cuid())
|
||||
planId String
|
||||
sharedById String
|
||||
sharedWithId String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
plan TrainingPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
|
||||
sharedBy User @relation("PlanShareBy", fields: [sharedById], references: [id], onDelete: Cascade)
|
||||
sharedWith User @relation("PlanShareWith", fields: [sharedWithId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([planId, sharedWithId])
|
||||
@@index([sharedWithId])
|
||||
}
|
||||
|
||||
model PlanWeek {
|
||||
id String @id @default(cuid())
|
||||
planId String
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
updateProfile,
|
||||
} from '../services/me.js';
|
||||
import { getFocusChain } from '../services/focusChain.js';
|
||||
import { getMyTrainers } from '../services/plans.js';
|
||||
import { getActiveSession } from '../services/sessions.js';
|
||||
import { addMyComment, deleteMyComment } from '../services/comments.js';
|
||||
import { getExerciseProgress } from '../services/exerciseProgress.js';
|
||||
@@ -107,6 +108,23 @@ export function createMeRoutes({ prisma }: AppDeps) {
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /me/trainers:
|
||||
* get:
|
||||
* summary: My trainers (ACTIVE coaching relations where I am the trainee)
|
||||
* tags: [Profile]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
router.get(
|
||||
'/trainers',
|
||||
asyncHandler(async (req, res) => {
|
||||
const result = await getMyTrainers(prisma, req.user!.id);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /me/focus-chain:
|
||||
|
||||
@@ -50,10 +50,23 @@ export const createPlanSchema = planBaseSchema
|
||||
message: 'weeks must have exactly weeksCount entries',
|
||||
});
|
||||
|
||||
export const updatePlanSchema = planBaseSchema.refine((d) => d.weeks.length === d.weeksCount, {
|
||||
message: 'weeks must have exactly weeksCount entries',
|
||||
});
|
||||
export const updatePlanSchema = planBaseSchema
|
||||
.extend({
|
||||
// Opcjonalna data startu (poniedziałek) — zapis = aktualizacja struktury + aktywacja
|
||||
// planu w jednym kroku (plan musi być DRAFT).
|
||||
startDate: z
|
||||
.string()
|
||||
.refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date')
|
||||
.optional(),
|
||||
})
|
||||
.refine((d) => d.weeks.length === d.weeksCount, {
|
||||
message: 'weeks must have exactly weeksCount entries',
|
||||
});
|
||||
|
||||
export const activateSchema = z.object({
|
||||
startDate: z.string().refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date'),
|
||||
});
|
||||
|
||||
export const sharePlanSchema = z.object({
|
||||
userId: z.string().min(1),
|
||||
});
|
||||
|
||||
@@ -6,16 +6,25 @@ import { validate } from '../middleware/validate.js';
|
||||
import {
|
||||
abandonPlan,
|
||||
activatePlan,
|
||||
assertPlanOwner,
|
||||
completePlan,
|
||||
createPlan,
|
||||
deletePlan,
|
||||
getPlan,
|
||||
listPlans,
|
||||
listSharedWithMe,
|
||||
sharePlan,
|
||||
unsharePlan,
|
||||
updatePlan,
|
||||
} from '../services/plans.js';
|
||||
import { logActivity } from '../services/audit.js';
|
||||
import { asyncHandler } from '../lib/asyncHandler.js';
|
||||
import { activateSchema, createPlanSchema, updatePlanSchema } from './plans-schemas.js';
|
||||
import {
|
||||
activateSchema,
|
||||
createPlanSchema,
|
||||
sharePlanSchema,
|
||||
updatePlanSchema,
|
||||
} from './plans-schemas.js';
|
||||
|
||||
export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
const router = Router();
|
||||
@@ -67,11 +76,29 @@ export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plans/shared-with-me:
|
||||
* get:
|
||||
* summary: Plans explicitly shared with the user (read-only)
|
||||
* tags: [Plans]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
router.get(
|
||||
'/shared-with-me',
|
||||
asyncHandler(async (req, res) => {
|
||||
const result = await listSharedWithMe(prisma, req.user!.id);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plans/{id}:
|
||||
* get:
|
||||
* summary: Plan details (weeks -> days -> exercises -> sets)
|
||||
* summary: Plan details (weeks -> days -> exercises -> sets). Access: owner,
|
||||
* trainer with an ACTIVE coaching relation, or a share recipient (read-only).
|
||||
* tags: [Plans]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
@@ -89,15 +116,21 @@ export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /plans/{id}:
|
||||
* patch:
|
||||
* summary: Replace plan structure (draft only)
|
||||
* summary: Replace plan structure (draft only). Optional startDate (a Monday,
|
||||
* current or future week) updates and activates the plan in one step.
|
||||
* tags: [Plans]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 400: { description: Not a draft / start date not a Monday / start week in the past }
|
||||
* 409: { description: User already has an active plan }
|
||||
*/
|
||||
router.patch(
|
||||
'/:id',
|
||||
validate(updatePlanSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
// mutacje trasy właściciela = tylko właściciel (trener ma trasy /trainer/...,
|
||||
// odbiorca share'a jest read-only)
|
||||
await assertPlanOwner(prisma, req.params.id, req.user!.id);
|
||||
const data = req.body as z.infer<typeof updatePlanSchema>;
|
||||
const result = await updatePlan(prisma, req.params.id, req.user!.id, data);
|
||||
await logActivity(prisma, {
|
||||
@@ -123,6 +156,7 @@ export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
router.delete(
|
||||
'/:id',
|
||||
asyncHandler(async (req, res) => {
|
||||
await assertPlanOwner(prisma, req.params.id, req.user!.id);
|
||||
const result = await deletePlan(prisma, req.params.id, req.user!.id);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
@@ -150,6 +184,7 @@ export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
'/:id/activate',
|
||||
validate(activateSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
await assertPlanOwner(prisma, req.params.id, req.user!.id);
|
||||
const { startDate } = req.body as z.infer<typeof activateSchema>;
|
||||
const result = await activatePlan(prisma, req.params.id, req.user!.id, startDate);
|
||||
await logActivity(prisma, {
|
||||
@@ -175,6 +210,7 @@ export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
router.post(
|
||||
'/:id/abandon',
|
||||
asyncHandler(async (req, res) => {
|
||||
await assertPlanOwner(prisma, req.params.id, req.user!.id);
|
||||
const result = await abandonPlan(prisma, req.params.id, req.user!.id);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
@@ -199,6 +235,7 @@ export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
router.post(
|
||||
'/:id/complete',
|
||||
asyncHandler(async (req, res) => {
|
||||
await assertPlanOwner(prisma, req.params.id, req.user!.id);
|
||||
const result = await completePlan(prisma, req.params.id, req.user!.id);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
@@ -211,5 +248,62 @@ export function createPlanRoutes({ prisma }: AppDeps) {
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plans/{id}/share:
|
||||
* post:
|
||||
* summary: Share the plan with a user in an ACTIVE coaching relation
|
||||
* (trainer <-> trainee). Owner only; recipients get read-only access.
|
||||
* tags: [Plans]
|
||||
* responses:
|
||||
* 201: { description: Shared }
|
||||
* 400: { description: Self-share / no active coaching relation }
|
||||
* 403: { description: Not the plan owner }
|
||||
* 404: { description: Plan not found }
|
||||
* 409: { description: Already shared with this user }
|
||||
*/
|
||||
router.post(
|
||||
'/:id/share',
|
||||
validate(sharePlanSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { userId } = req.body as z.infer<typeof sharePlanSchema>;
|
||||
const result = await sharePlan(prisma, req.params.id, req.user!.id, userId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'plan.shared',
|
||||
entityType: 'plan',
|
||||
entityId: req.params.id,
|
||||
details: { userId },
|
||||
});
|
||||
res.status(201).json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plans/{id}/share/{userId}:
|
||||
* delete:
|
||||
* summary: Revoke a plan share. Owner only.
|
||||
* tags: [Plans]
|
||||
* responses:
|
||||
* 204: { description: Unshared }
|
||||
* 403: { description: Not the plan owner }
|
||||
* 404: { description: Plan not found / not shared with this user }
|
||||
*/
|
||||
router.delete(
|
||||
'/:id/share/:userId',
|
||||
asyncHandler(async (req, res) => {
|
||||
await unsharePlan(prisma, req.params.id, req.user!.id, req.params.userId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'plan.unshared',
|
||||
entityType: 'plan',
|
||||
entityId: req.params.id,
|
||||
details: { userId: req.params.userId },
|
||||
});
|
||||
res.status(204).end();
|
||||
}),
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
@@ -488,13 +488,15 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /trainer/trainees/{userId}/plans/{planId}:
|
||||
* patch:
|
||||
* summary: Replace plan structure (draft only). Same body as POST (gymId, weeks[].customName)
|
||||
* summary: Replace plan structure (draft only). Same body as POST (gymId, weeks[].customName).
|
||||
* Optional startDate (a Monday, current or future week) updates and activates the plan in one step.
|
||||
* tags: [Trainer]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 400: { description: Not a draft / gym not a trainee membership }
|
||||
* 400: { description: Not a draft / gym not a trainee membership / start date not a Monday / start week in the past }
|
||||
* 403: { description: Trainer role required }
|
||||
* 404: { description: Trainee or plan not found }
|
||||
* 409: { description: Trainee already has an active plan }
|
||||
*/
|
||||
router.patch(
|
||||
'/trainees/:userId/plans/:planId',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { badRequest, conflict, notFound } from '../lib/errors.js';
|
||||
import { badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
|
||||
import { isPrismaUnique } from '../lib/prisma.js';
|
||||
|
||||
export interface PlanSetInput {
|
||||
@@ -43,9 +43,10 @@ export interface CreatePlanInput {
|
||||
}
|
||||
|
||||
/**
|
||||
* The requester may access the plan when they are its owner (the trainee) or a
|
||||
* trainer with an ACTIVE coaching relation to the owner. Anything else — and a
|
||||
* missing plan — is a 404 (no existence leak, matches assertActiveTrainee).
|
||||
* The requester may access the plan when they are its owner (the trainee), a
|
||||
* trainer with an ACTIVE coaching relation to the owner, or a recipient of an
|
||||
* explicit plan share (read-only). Anything else — and a missing plan — is a
|
||||
* 404 (no existence leak, matches assertActiveTrainee).
|
||||
*/
|
||||
async function assertPlanAccess(prisma: PrismaClient, planId: string, requesterId: string) {
|
||||
const plan = await prisma.trainingPlan.findUnique({ where: { id: planId } });
|
||||
@@ -54,7 +55,24 @@ async function assertPlanAccess(prisma: PrismaClient, planId: string, requesterI
|
||||
const coaching = await prisma.coaching.findUnique({
|
||||
where: { trainerId_userId: { trainerId: requesterId, userId: plan.userId } },
|
||||
});
|
||||
if (!coaching || coaching.status !== 'ACTIVE') throw notFound('Plan not found');
|
||||
if (coaching && coaching.status === 'ACTIVE') return plan;
|
||||
const share = await prisma.planShare.findUnique({
|
||||
where: { planId_sharedWithId: { planId, sharedWithId: requesterId } },
|
||||
});
|
||||
if (!share) throw notFound('Plan not found');
|
||||
return plan;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owner-only access for the owner-scoped mutation routes (PATCH/DELETE
|
||||
* /plans/:id, activate/complete/abandon). A trainer keeps mutation rights via
|
||||
* the /trainer/... routes (same services, no owner check there), and a share
|
||||
* recipient is read-only — so the check lives on the route, not the service.
|
||||
*/
|
||||
export async function assertPlanOwner(prisma: PrismaClient, planId: string, userId: string) {
|
||||
const plan = await prisma.trainingPlan.findUnique({ where: { id: planId } });
|
||||
if (!plan) throw notFound('Plan not found');
|
||||
if (plan.userId !== userId) throw notFound('Plan not found');
|
||||
return plan;
|
||||
}
|
||||
|
||||
@@ -173,11 +191,26 @@ export async function createPlan(
|
||||
}
|
||||
|
||||
export async function getPlan(prisma: PrismaClient, planId: string, userId: string) {
|
||||
await assertPlanAccess(prisma, planId, userId);
|
||||
const plan = await assertPlanAccess(prisma, planId, userId);
|
||||
// `shares` eksponowane tylko dla właściciela (lista odbiorców do dialogu
|
||||
// „Udostępnij”); trener i odbiorca share'a dostają ten sam widok bez tej sekcji.
|
||||
const isOwner = plan.userId === userId;
|
||||
// canManage: właściciel lub trener z AKTYWNYM coachingiem; odbiorca share'a = read-only.
|
||||
let canManage = isOwner;
|
||||
if (!isOwner) {
|
||||
const coaching = await prisma.coaching.findUnique({
|
||||
where: { trainerId_userId: { trainerId: userId, userId: plan.userId } },
|
||||
});
|
||||
canManage = coaching?.status === 'ACTIVE';
|
||||
}
|
||||
const full = await prisma.trainingPlan.findUnique({
|
||||
where: { id: planId },
|
||||
include: {
|
||||
gym: { select: { id: true, name: true } },
|
||||
shares: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
include: { sharedWith: { select: { id: true, firstName: true, lastName: true } } },
|
||||
},
|
||||
weeks: {
|
||||
orderBy: { index: 'asc' },
|
||||
include: {
|
||||
@@ -195,7 +228,17 @@ export async function getPlan(prisma: PrismaClient, planId: string, userId: stri
|
||||
},
|
||||
},
|
||||
});
|
||||
return { plan: full };
|
||||
if (!full) throw notFound('Plan not found');
|
||||
return {
|
||||
plan: {
|
||||
...full,
|
||||
canManage,
|
||||
// frontend shape: { userId, user: { id, firstName, lastName } }
|
||||
shares: isOwner
|
||||
? full.shares.map((s) => ({ userId: s.sharedWithId, user: s.sharedWith }))
|
||||
: undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function updatePlan(
|
||||
@@ -208,6 +251,9 @@ export async function updatePlan(
|
||||
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be edited');
|
||||
await validateExercises(prisma, data.weeks);
|
||||
await validateGymMembership(prisma, data.gymId, plan.userId);
|
||||
// Data startu (opcjonalna): walidacja (poniedziałek) przed aktualizacją struktury.
|
||||
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
|
||||
if (startOfStart) await assertNoActivePlan(prisma, plan.userId);
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.planWeek.deleteMany({ where: { planId: plan.id } });
|
||||
await tx.trainingPlan.update({
|
||||
@@ -220,6 +266,9 @@ export async function updatePlan(
|
||||
},
|
||||
});
|
||||
});
|
||||
// Zapis = aktualizacja + aktywacja w jednym kroku: applyStartDate musi działać PO
|
||||
// rekolekcji tygodni (wylicza daty dla nowych ID dni).
|
||||
if (startOfStart) await applyStartDate(prisma, plan.id, plan.userId, startOfStart);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
@@ -336,3 +385,106 @@ export async function completePlan(prisma: PrismaClient, planId: string, userId:
|
||||
});
|
||||
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.
|
||||
* The share survives the coaching ending; the owner can unshare anytime.
|
||||
*/
|
||||
export async function sharePlan(
|
||||
prisma: PrismaClient,
|
||||
planId: string,
|
||||
requesterId: string,
|
||||
userId: string,
|
||||
) {
|
||||
const plan = await assertPlanAccess(prisma, planId, requesterId);
|
||||
if (plan.userId !== requesterId) throw forbidden('Only the plan owner can share the plan');
|
||||
if (userId === requesterId) throw badRequest('Cannot share a plan with yourself');
|
||||
const coaching =
|
||||
(await prisma.coaching.findUnique({
|
||||
where: { trainerId_userId: { trainerId: plan.userId, userId } },
|
||||
})) ??
|
||||
(await prisma.coaching.findUnique({
|
||||
where: { trainerId_userId: { trainerId: userId, userId: plan.userId } },
|
||||
}));
|
||||
if (!coaching || coaching.status !== 'ACTIVE')
|
||||
throw badRequest('No active coaching relation with this user');
|
||||
try {
|
||||
const share = await prisma.planShare.create({
|
||||
data: { planId, sharedById: plan.userId, sharedWithId: userId },
|
||||
});
|
||||
return { share };
|
||||
} catch (e) {
|
||||
if (isPrismaUnique(e)) throw conflict('Plan is already shared with this user');
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** The owner revokes a share (idempotent 404 when the share does not exist). */
|
||||
export async function unsharePlan(
|
||||
prisma: PrismaClient,
|
||||
planId: string,
|
||||
requesterId: string,
|
||||
userId: string,
|
||||
) {
|
||||
const plan = await assertPlanAccess(prisma, planId, requesterId);
|
||||
if (plan.userId !== requesterId) throw forbidden('Only the plan owner can unshare the plan');
|
||||
const result = await prisma.planShare.deleteMany({
|
||||
where: { planId, sharedWithId: userId },
|
||||
});
|
||||
if (result.count === 0) throw notFound('Plan is not shared with this user');
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** Plans explicitly shared with the user (read-only), with the sharer's name. */
|
||||
export async function listSharedWithMe(prisma: PrismaClient, userId: string) {
|
||||
const shares = await prisma.planShare.findMany({
|
||||
where: { sharedWithId: userId },
|
||||
include: {
|
||||
sharedBy: { select: { id: true, firstName: true, lastName: true } },
|
||||
plan: {
|
||||
include: {
|
||||
gym: { select: { id: true, name: true } },
|
||||
weeks: { select: { days: { select: { status: true } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
return {
|
||||
plans: shares.map((s) => {
|
||||
const days = (s.plan.weeks ?? []).flatMap((w) => w.days);
|
||||
const completed = days.filter((d) => d.status === 'COMPLETED').length;
|
||||
const total = days.length;
|
||||
const { weeks: _weeks, ...rest } = s.plan;
|
||||
return {
|
||||
...rest,
|
||||
sharedBy: s.sharedBy,
|
||||
progress: {
|
||||
completed,
|
||||
total,
|
||||
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The user's trainers (ACTIVE coachings where the user is the trainee). */
|
||||
export async function getMyTrainers(prisma: PrismaClient, userId: string) {
|
||||
const coachings = await prisma.coaching.findMany({
|
||||
where: { userId, status: 'ACTIVE' },
|
||||
include: {
|
||||
trainer: { select: { id: true, firstName: true, lastName: true, nickname: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return {
|
||||
trainers: coachings.map((c) => ({
|
||||
id: c.trainer.id,
|
||||
firstName: c.trainer.firstName,
|
||||
lastName: c.trainer.lastName,
|
||||
nickname: c.trainer.nickname,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -127,6 +127,13 @@ export const openapi: Record<string, unknown> = {
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
'/me/trainers': {
|
||||
get: {
|
||||
tags: ['Profile'],
|
||||
summary: 'My trainers (ACTIVE coaching relations where I am the trainee)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
'/me/body-parameters': {
|
||||
get: {
|
||||
tags: ['Profile'],
|
||||
@@ -538,19 +545,42 @@ export const openapi: Record<string, unknown> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/plans/shared-with-me': {
|
||||
get: {
|
||||
tags: ['Plans'],
|
||||
summary: 'Plans explicitly shared with the user (read-only)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
},
|
||||
},
|
||||
'/plans/{id}': {
|
||||
get: {
|
||||
tags: ['Plans'],
|
||||
summary: 'Plan details',
|
||||
summary:
|
||||
'Plan details. Access: owner, trainer with an ACTIVE coaching relation, or a share recipient (read-only)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
},
|
||||
patch: {
|
||||
tags: ['Plans'],
|
||||
summary:
|
||||
'Replace plan structure (draft only). Same body as POST /plans (gymId and weeks[].customName included)',
|
||||
'Replace plan structure (draft only). Same body as POST /plans (gymId and weeks[].customName included). Optional startDate (a Monday of the current or a future week) updates and activates the plan in one step',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
$ref: '#/paths/~1plans/post/requestBody/content/application~1json/schema',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
200: { description: 'OK' },
|
||||
400: { description: 'Not a draft / start date not a Monday / start week in the past' },
|
||||
409: { description: 'User already has an active plan' },
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
tags: ['Plans'],
|
||||
@@ -595,6 +625,50 @@ export const openapi: Record<string, unknown> = {
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
},
|
||||
},
|
||||
'/plans/{id}/share': {
|
||||
post: {
|
||||
tags: ['Plans'],
|
||||
summary:
|
||||
'Share the plan with a user in an ACTIVE coaching relation (trainer <-> trainee). Owner only; recipients get read-only access',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['userId'],
|
||||
properties: { userId: { type: 'string' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
201: { description: 'Shared' },
|
||||
400: { description: 'Self-share / no active coaching relation' },
|
||||
403: { description: 'Not the plan owner' },
|
||||
404: { description: 'Plan not found' },
|
||||
409: { description: 'Already shared with this user' },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/plans/{id}/share/{userId}': {
|
||||
delete: {
|
||||
tags: ['Plans'],
|
||||
summary: 'Revoke a plan share (owner only)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'userId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
responses: {
|
||||
204: { description: 'Unshared' },
|
||||
403: { description: 'Not the plan owner' },
|
||||
404: { description: 'Plan not found / not shared with this user' },
|
||||
},
|
||||
},
|
||||
},
|
||||
'/days/{dayId}/sessions': {
|
||||
post: {
|
||||
tags: ['Sessions'],
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { describe, it, expect, beforeAll } from 'vitest';
|
||||
import { prisma } from '../../src/lib/prisma.js';
|
||||
import { buildApp, createUser, createExercise, loginViaApi, rand, registerViaApi, seedPlan, PASSWORD } from '../helpers.js';
|
||||
import {
|
||||
buildApp,
|
||||
createUser,
|
||||
createUserWithToken,
|
||||
createExercise,
|
||||
loginViaApi,
|
||||
rand,
|
||||
registerViaApi,
|
||||
seedPlan,
|
||||
PASSWORD,
|
||||
} from '../helpers.js';
|
||||
|
||||
// Daty dynamiczne: tydzień startu musi być bieżący lub przyszły (nie miniony).
|
||||
function mondayIso(offsetWeeks: number): string {
|
||||
@@ -629,3 +639,260 @@ describe('plans: trainer-created plan (creator + owner access)', () => {
|
||||
expect(res.body.error.message).toBe('Plan owner is not a member of the gym');
|
||||
});
|
||||
});
|
||||
|
||||
describe('plans: sharing (PlanShare)', () => {
|
||||
let app: ReturnType<typeof buildApp>;
|
||||
let trainer: { user: { id: string }; token: string };
|
||||
let trainee: { user: { id: string }; token: string };
|
||||
let stranger: { user: { id: string }; token: string };
|
||||
let exerciseId: string;
|
||||
let planId: string;
|
||||
|
||||
const body = (title: string) => ({
|
||||
title,
|
||||
weeksCount: 1,
|
||||
weeks: [
|
||||
{
|
||||
index: 0,
|
||||
days: [
|
||||
{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
app = buildApp();
|
||||
trainer = await createUserWithToken({ firstName: 'ShareTrainer' });
|
||||
trainee = await createUserWithToken({ firstName: 'ShareTrainee' });
|
||||
stranger = await createUserWithToken({ firstName: 'ShareStranger' });
|
||||
// ACTIVE coaching: trainer -> trainee
|
||||
await prisma.coaching.create({
|
||||
data: {
|
||||
trainerId: trainer.user.id,
|
||||
userId: trainee.user.id,
|
||||
invitedBy: trainer.user.id,
|
||||
status: 'ACTIVE',
|
||||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
const ex = await createExercise();
|
||||
exerciseId = ex.id;
|
||||
// plan należy do podopiecznego (właściciel = podopieczny)
|
||||
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${trainee.token}`).send(body('Plan do udostępnienia'));
|
||||
expect(res.status).toBe(201);
|
||||
planId = res.body.plan.id;
|
||||
});
|
||||
|
||||
it('non-owner (trainer) cannot share the plan (403)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainer.token}`)
|
||||
.send({ userId: trainee.user.id });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error.message).toBe('Only the plan owner can share the plan');
|
||||
});
|
||||
|
||||
it('owner cannot share the plan with themselves (400)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: trainee.user.id });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('Cannot share a plan with yourself');
|
||||
});
|
||||
|
||||
it('owner cannot share with a user without an active coaching relation (400)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: stranger.user.id });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('No active coaching relation with this user');
|
||||
});
|
||||
|
||||
it('owner shares the plan with the trainer (201)', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: trainer.user.id });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.share).toMatchObject({ id: expect.any(String) });
|
||||
});
|
||||
|
||||
it('duplicate share is rejected with 409', async () => {
|
||||
const res = await app
|
||||
.post(`/api/v1/plans/${planId}/share`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`)
|
||||
.send({ userId: trainer.user.id });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error.message).toBe('Plan is already shared with this user');
|
||||
});
|
||||
|
||||
it('the owner sees the recipients in the plan detail', async () => {
|
||||
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.plan.shares).toEqual([
|
||||
{ userId: trainer.user.id, user: { id: trainer.user.id, firstName: 'ShareTrainer', lastName: null } },
|
||||
]);
|
||||
expect(res.body.plan.canManage).toBe(true);
|
||||
});
|
||||
|
||||
it('the recipient sees the plan in /plans/shared-with-me', async () => {
|
||||
const res = await app.get('/api/v1/plans/shared-with-me').set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
const found = res.body.plans.find((p: { id: string }) => p.id === planId);
|
||||
expect(found).toBeTruthy();
|
||||
expect(found.sharedBy).toMatchObject({ id: trainee.user.id, firstName: 'ShareTrainee' });
|
||||
expect(found.progress).toEqual({ completed: 0, total: 1, percent: 0 });
|
||||
});
|
||||
|
||||
it('the trainee sees the trainer in /me/trainers', async () => {
|
||||
const res = await app.get('/api/v1/me/trainers').set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.trainers).toEqual([
|
||||
{ id: trainer.user.id, firstName: 'ShareTrainer', lastName: null, nickname: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('the trainer (ACTIVE coaching) still manages the plan via the owner route? NO — owner route is owner-only (404)', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${trainer.token}`)
|
||||
.send(body('Trener edytuje'));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('the share survives the coaching ending: recipient keeps read-only access', async () => {
|
||||
await prisma.coaching.updateMany({
|
||||
where: { trainerId: trainer.user.id, userId: trainee.user.id },
|
||||
data: { status: 'ARCHIVED' },
|
||||
});
|
||||
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.plan.canManage).toBe(false);
|
||||
expect(res.body.plan.shares).toBeUndefined();
|
||||
});
|
||||
|
||||
it('a stranger gets 404 for the shared plan', async () => {
|
||||
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${stranger.token}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('the owner revokes the share (204) and the recipient loses access', async () => {
|
||||
const res = await app
|
||||
.delete(`/api/v1/plans/${planId}/share/${trainer.user.id}`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(204);
|
||||
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(detail.status).toBe(404);
|
||||
|
||||
const list = await app.get('/api/v1/plans/shared-with-me').set('Authorization', `Bearer ${trainer.token}`);
|
||||
expect(list.body.plans.find((p: { id: string }) => p.id === planId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('revoking a missing share is 404', async () => {
|
||||
const res = await app
|
||||
.delete(`/api/v1/plans/${planId}/share/${trainer.user.id}`)
|
||||
.set('Authorization', `Bearer ${trainee.token}`);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('plans: PATCH with startDate (update + activate)', () => {
|
||||
let app: ReturnType<typeof buildApp>;
|
||||
let token: string;
|
||||
let userId: string;
|
||||
let exerciseId: string;
|
||||
let planId: string;
|
||||
|
||||
const body = (title: string, weeksCount = 1) => ({
|
||||
title,
|
||||
weeksCount,
|
||||
weeks: [
|
||||
{
|
||||
index: 0,
|
||||
days: [
|
||||
{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
app = buildApp();
|
||||
const reg = await createUserWithToken();
|
||||
token = reg.token;
|
||||
userId = reg.user.id;
|
||||
const ex = await createExercise();
|
||||
exerciseId = ex.id;
|
||||
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body('Draft do aktywacji'));
|
||||
expect(res.status).toBe(201);
|
||||
planId = res.body.plan.id;
|
||||
});
|
||||
|
||||
it('PATCH without startDate keeps the plan DRAFT', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send(body('Draft v2'));
|
||||
expect(res.status).toBe(200);
|
||||
const detail = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${token}`);
|
||||
expect(detail.body.plan.status).toBe('DRAFT');
|
||||
expect(detail.body.plan.startDate).toBeNull();
|
||||
});
|
||||
|
||||
it('PATCH with a non-Monday startDate is rejected with 400', async () => {
|
||||
const [y, m, d] = mondayIso(1).split('-').map(Number);
|
||||
const tuesday = new Date(y, m - 1, d + 1);
|
||||
const tuesdayIso = `${tuesday.getFullYear()}-${String(tuesday.getMonth() + 1).padStart(2, '0')}-${String(tuesday.getDate()).padStart(2, '0')}`;
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Wtorek'), startDate: tuesdayIso });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error.message).toBe('Start date must be a Monday');
|
||||
});
|
||||
|
||||
it('PATCH with a past-week startDate is rejected with 400', async () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Miniony'), startDate: mondayIso(-1) });
|
||||
expect(res.status).toBe(400);
|
||||
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 () => {
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${planId}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Aktywowany'), startDate: mondayIso(1) });
|
||||
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.title).toBe('Aktywowany');
|
||||
expect(detail.body.plan.startDate).not.toBeNull();
|
||||
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.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 is rejected with 409', async () => {
|
||||
const created = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body('Konflikt'));
|
||||
const res = await app
|
||||
.patch(`/api/v1/plans/${created.body.plan.id}`)
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ ...body('Konflikt'), startDate: mondayIso(2) });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.error.message).toBe('User already has an active plan');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,11 +2,16 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
abandonPlan,
|
||||
activatePlan,
|
||||
assertPlanOwner,
|
||||
completePlan,
|
||||
createPlan,
|
||||
deletePlan,
|
||||
getMyTrainers,
|
||||
getPlan,
|
||||
listPlans,
|
||||
listSharedWithMe,
|
||||
sharePlan,
|
||||
unsharePlan,
|
||||
updatePlan,
|
||||
} from '../../src/services/plans.js';
|
||||
|
||||
@@ -26,8 +31,14 @@ function mockPrisma() {
|
||||
delete: vi.fn(),
|
||||
},
|
||||
exercise: { findMany: vi.fn() },
|
||||
coaching: { findUnique: vi.fn() },
|
||||
coaching: { findUnique: vi.fn(), findMany: vi.fn() },
|
||||
planWeek: { findMany: vi.fn() },
|
||||
planShare: {
|
||||
findUnique: vi.fn(),
|
||||
create: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(async (cb: (tx: typeof tx) => Promise<void>) => cb(tx)),
|
||||
};
|
||||
return { prisma, tx };
|
||||
@@ -244,15 +255,24 @@ describe('listPlans', () => {
|
||||
describe('assertPlanAccess (via getPlan)', () => {
|
||||
it('allows the owner (trainee) to read the plan', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||||
await expect(getPlan(prisma, 'p1', 'u1')).resolves.toMatchObject({ plan: { id: 'p1' } });
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1', shares: [] });
|
||||
await expect(getPlan(prisma, 'p1', 'u1')).resolves.toMatchObject({
|
||||
plan: { id: 'p1', canManage: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('allows a trainer with an ACTIVE coaching relation to read the plan', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||||
...draftPlan,
|
||||
userId: 'trainee-1',
|
||||
shares: [],
|
||||
});
|
||||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||||
await expect(getPlan(prisma, 'p1', 'trainer-1')).resolves.toMatchObject({ plan: { id: 'p1' } });
|
||||
const result = await getPlan(prisma, 'p1', 'trainer-1');
|
||||
expect(result.plan).toMatchObject({ id: 'p1', canManage: true });
|
||||
// trener nie dostaje listy odbiorców share'u
|
||||
expect(result.plan.shares).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects a trainer with a PENDING relation with 404', async () => {
|
||||
@@ -272,10 +292,25 @@ describe('assertPlanAccess (via getPlan)', () => {
|
||||
await expect(getPlan(prisma, 'p1', 'trainer-1')).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it('rejects an unrelated user (no coaching relation) with 404', async () => {
|
||||
it('allows a share recipient to read the plan (read-only)', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({
|
||||
...draftPlan,
|
||||
userId: 'trainee-1',
|
||||
shares: [],
|
||||
});
|
||||
prisma.coaching.findUnique.mockResolvedValue(null);
|
||||
prisma.planShare.findUnique.mockResolvedValue({ id: 'share-1' });
|
||||
const result = await getPlan(prisma, 'p1', 'recipient-1');
|
||||
expect(result.plan).toMatchObject({ id: 'p1', canManage: false });
|
||||
expect(result.plan.shares).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects an unrelated user (no coaching relation, no share) with 404', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||||
prisma.coaching.findUnique.mockResolvedValue(null);
|
||||
prisma.planShare.findUnique.mockResolvedValue(null);
|
||||
await expect(getPlan(prisma, 'p1', 'stranger')).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
@@ -286,6 +321,29 @@ describe('assertPlanAccess (via getPlan)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertPlanOwner', () => {
|
||||
it('allows the owner', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||||
await expect(assertPlanOwner(prisma, 'p1', 'u1')).resolves.toMatchObject({ id: 'p1' });
|
||||
});
|
||||
|
||||
it('rejects a non-owner (even a trainer) with 404', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||||
await expect(assertPlanOwner(prisma, 'p1', 'trainer-1')).rejects.toMatchObject({
|
||||
status: 404,
|
||||
message: 'Plan not found',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a missing plan with 404', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(null);
|
||||
await expect(assertPlanOwner(prisma, 'p1', 'u1')).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('createPlan creatorId', () => {
|
||||
it('sets creatorId to the given creator (trainer) when provided', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
@@ -325,3 +383,264 @@ describe('createPlan creatorId', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updatePlan (startDate = aktualizacja + aktywacja)', () => {
|
||||
it('bez startDate: aktualizuje strukturę, plan pozostaje DRAFT', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
tx.trainingPlan.update.mockResolvedValue({});
|
||||
await updatePlan(prisma, 'p1', 'u1', { title: 't', weeksCount: 1, weeks: [] });
|
||||
expect(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||||
where: { id: 'p1' },
|
||||
data: expect.objectContaining({ title: 't' }),
|
||||
});
|
||||
// bez aktywacji — brak wyliczania dat
|
||||
expect(tx.planDay.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('z startDate: aktualizuje strukturę i aktywuje plan (daty wyliczone)', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
prisma.trainingPlan.findFirst.mockResolvedValue(null);
|
||||
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', {
|
||||
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(tx.trainingPlan.update).toHaveBeenCalledWith({
|
||||
where: { id: 'p1' },
|
||||
data: { status: 'ACTIVE', startDate: new Date(y, m - 1, d) },
|
||||
});
|
||||
});
|
||||
|
||||
it('z startDate nie-poniedziałkiem: 400 (fail-fast, przed aktualizacją)', async () => {
|
||||
const { prisma, tx } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
// 2026-08-25 to wtorek
|
||||
await expect(
|
||||
updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: '2026-08-25',
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400, message: 'Start date must be a Monday' });
|
||||
// struktura nie została dotknięta
|
||||
expect(tx.trainingPlan.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('z startDate w minionym tygodniu: 400', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
await expect(
|
||||
updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: mondayIso(-1),
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400, message: 'Start date cannot be in the past' });
|
||||
});
|
||||
|
||||
it('z startDate gdy właściciel ma już aktywny plan: 409', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(draftPlan);
|
||||
prisma.exercise.findMany.mockResolvedValue([]);
|
||||
prisma.trainingPlan.findFirst.mockResolvedValue({ id: 'other-active' });
|
||||
await expect(
|
||||
updatePlan(prisma, 'p1', 'u1', {
|
||||
title: 't',
|
||||
weeksCount: 1,
|
||||
weeks: [],
|
||||
startDate: mondayIso(1),
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 409, message: 'User already has an active plan' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('sharePlan', () => {
|
||||
const ownerPlan = { ...draftPlan, userId: 'u1' };
|
||||
|
||||
it('właściciel udostępnia plan podopiecznemu (ACTIVE coaching)', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||||
// u1 = trener, trainee-1 = podopieczny (właściciel → assertPlanAccess bez coachingu)
|
||||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||||
prisma.planShare.create.mockResolvedValue({ id: 'share-1' });
|
||||
const result = await sharePlan(prisma, 'p1', 'u1', 'trainee-1');
|
||||
expect(prisma.planShare.create).toHaveBeenCalledWith({
|
||||
data: { planId: 'p1', sharedById: 'u1', sharedWithId: 'trainee-1' },
|
||||
});
|
||||
expect(result).toEqual({ share: { id: 'share-1' } });
|
||||
});
|
||||
|
||||
it('właściciel udostępnia plan swojemu trenerowi (odwrotny kierunek coachingu)', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||||
prisma.coaching.findUnique
|
||||
.mockResolvedValueOnce(null) // u1 jako trener? nie…
|
||||
.mockResolvedValueOnce({ status: 'ACTIVE' }); // …ale trainer-1 jest trenerem u1
|
||||
prisma.planShare.create.mockResolvedValue({ id: 'share-2' });
|
||||
await sharePlan(prisma, 'p1', 'u1', 'trainer-1');
|
||||
expect(prisma.planShare.create).toHaveBeenCalledWith({
|
||||
data: { planId: 'p1', sharedById: 'u1', sharedWithId: 'trainer-1' },
|
||||
});
|
||||
});
|
||||
|
||||
it('nie-właściciel (trener): 403', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||||
await expect(sharePlan(prisma, 'p1', 'trainer-1', 'u1')).rejects.toMatchObject({
|
||||
status: 403,
|
||||
message: 'Only the plan owner can share the plan',
|
||||
});
|
||||
});
|
||||
|
||||
it('udostępnienie samemu sobie: 400', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||||
await expect(sharePlan(prisma, 'p1', 'u1', 'u1')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: 'Cannot share a plan with yourself',
|
||||
});
|
||||
});
|
||||
|
||||
it('brak aktywnego coachingu: 400', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||||
prisma.coaching.findUnique.mockResolvedValue(null);
|
||||
await expect(sharePlan(prisma, 'p1', 'u1', 'stranger')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: 'No active coaching relation with this user',
|
||||
});
|
||||
});
|
||||
|
||||
it('PENDING coaching: 400', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||||
prisma.coaching.findUnique.mockResolvedValue({ status: 'PENDING' });
|
||||
await expect(sharePlan(prisma, 'p1', 'u1', 'trainee-1')).rejects.toMatchObject({
|
||||
status: 400,
|
||||
message: 'No active coaching relation with this user',
|
||||
});
|
||||
});
|
||||
|
||||
it('duplikat: 409', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue(ownerPlan);
|
||||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||||
prisma.planShare.create.mockRejectedValue(
|
||||
Object.assign(new Error('Unique constraint failed'), { code: 'P2002' }),
|
||||
);
|
||||
await expect(sharePlan(prisma, 'p1', 'u1', 'trainee-1')).rejects.toMatchObject({
|
||||
status: 409,
|
||||
message: 'Plan is already shared with this user',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('unsharePlan', () => {
|
||||
it('właściciel cofa udostępnienie', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||||
prisma.planShare.deleteMany.mockResolvedValue({ count: 1 });
|
||||
const result = await unsharePlan(prisma, 'p1', 'u1', 'trainee-1');
|
||||
expect(prisma.planShare.deleteMany).toHaveBeenCalledWith({
|
||||
where: { planId: 'p1', sharedWithId: 'trainee-1' },
|
||||
});
|
||||
expect(result).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('nie-właściciel: 403', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'trainee-1' });
|
||||
prisma.coaching.findUnique.mockResolvedValue({ status: 'ACTIVE' });
|
||||
await expect(unsharePlan(prisma, 'p1', 'trainer-1', 'u1')).rejects.toMatchObject({
|
||||
status: 403,
|
||||
});
|
||||
});
|
||||
|
||||
it('brak share\'a: 404', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.trainingPlan.findUnique.mockResolvedValue({ ...draftPlan, userId: 'u1' });
|
||||
prisma.planShare.deleteMany.mockResolvedValue({ count: 0 });
|
||||
await expect(unsharePlan(prisma, 'p1', 'u1', 'trainee-1')).rejects.toMatchObject({
|
||||
status: 404,
|
||||
message: 'Plan is not shared with this user',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('listSharedWithMe', () => {
|
||||
it('zwraca udostępnione plany z imieniem udostępniającego i postępem', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.planShare.findMany.mockResolvedValue([
|
||||
{
|
||||
sharedBy: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener' },
|
||||
plan: {
|
||||
id: 'p1',
|
||||
title: 'Plan trenera',
|
||||
status: 'ACTIVE',
|
||||
weeksCount: 4,
|
||||
startDate: null,
|
||||
gym: null,
|
||||
weeks: [{ days: [{ status: 'COMPLETED' }, { status: 'PLANNED' }] }],
|
||||
},
|
||||
},
|
||||
]);
|
||||
const result = await listSharedWithMe(prisma, 'u1');
|
||||
expect(result).toEqual({
|
||||
plans: [
|
||||
{
|
||||
id: 'p1',
|
||||
title: 'Plan trenera',
|
||||
status: 'ACTIVE',
|
||||
weeksCount: 4,
|
||||
startDate: null,
|
||||
gym: null,
|
||||
sharedBy: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener' },
|
||||
progress: { completed: 1, total: 2, percent: 50 },
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMyTrainers', () => {
|
||||
it('zwraca trenerów z AKTYWNYM coachingiem (ja = podopieczny)', async () => {
|
||||
const { prisma } = mockPrisma();
|
||||
prisma.coaching.findMany.mockResolvedValue([
|
||||
{ trainer: { id: 'trainer-1', firstName: 'Marek', lastName: 'Trener', nickname: null } },
|
||||
]);
|
||||
const result = await getMyTrainers(prisma, 'u1');
|
||||
expect(prisma.coaching.findMany).toHaveBeenCalledWith({
|
||||
where: { userId: 'u1', status: 'ACTIVE' },
|
||||
include: {
|
||||
trainer: { select: { id: true, firstName: true, lastName: true, nickname: true } },
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
expect(result).toEqual({
|
||||
trainers: [{ id: 'trainer-1', firstName: 'Marek', lastName: 'Trener', nickname: null }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user