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 }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -274,6 +274,8 @@ export interface PlanWeek {
|
||||
|
||||
export interface Plan {
|
||||
id: string;
|
||||
/** Właściciel planu (podopieczny, gdy plan utworzył trener). */
|
||||
userId: string;
|
||||
title: string;
|
||||
status: 'DRAFT' | 'ACTIVE' | 'COMPLETED' | 'ABANDONED';
|
||||
weeksCount: number;
|
||||
@@ -282,6 +284,15 @@ export interface Plan {
|
||||
gym: { id: string; name: string } | null;
|
||||
/** Kto utworzył plan (trener, gdy plan należy do podopiecznego); null = podopieczny sam. */
|
||||
creator: { id: string; firstName: string | null; lastName: string | null } | null;
|
||||
/** Kto udostępnił plan (sekcja „Udostępnione mi”); brak = plan własny. */
|
||||
sharedBy?: { id: string; firstName: string | null; lastName: string | null };
|
||||
/** Odbiorcy share'u (tylko detal, dla właściciela); brak = nieudostępniony lub nie-właściciel. */
|
||||
shares?: {
|
||||
userId: string;
|
||||
user: { id: string; firstName: string | null; lastName: string | null };
|
||||
}[];
|
||||
/** Detal: czy zalogowany może zarządzać planem (właściciel lub trener z ACTIVE coachingiem). */
|
||||
canManage?: boolean;
|
||||
/** Podsumowanie postępu (lista planów); brak = dane niedostępne. */
|
||||
progress?: { completed: number; total: number; percent: number };
|
||||
weeks: PlanWeek[];
|
||||
|
||||
@@ -13,7 +13,16 @@ const EDGE: Record<Plan['status'], string> = {
|
||||
};
|
||||
|
||||
/** Karta planu: tytuł + meta (tygodnie/dni/start/twórca), pasek postępu dla aktywnego, „Otwórz ›”. */
|
||||
export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: string | null }) {
|
||||
export function PlanCard({
|
||||
plan,
|
||||
creatorLabel,
|
||||
creatorPrefix = 'utworzył',
|
||||
}: {
|
||||
plan: Plan;
|
||||
creatorLabel: string | null;
|
||||
/** Przedrostek etykiety twórcy (np. „udostępnił” w sekcji „Udostępnione mi”). */
|
||||
creatorPrefix?: string;
|
||||
}) {
|
||||
// Postęp z API (lista); fallback na tygodnie, gdy dostępne (np. mocki bez `progress`).
|
||||
const fromWeeks = (plan.weeks ?? []).flatMap((w) => w.days);
|
||||
const progress =
|
||||
@@ -36,13 +45,20 @@ export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: str
|
||||
to={`/plans/${plan.id}`}
|
||||
className="group relative flex flex-col gap-3 overflow-hidden rounded-xl border border-line bg-(image:--card-grad) p-4 pl-5 shadow-card transition-all duration-150 hover:border-accent/55 sm:flex-row sm:items-center sm:gap-4"
|
||||
>
|
||||
<span aria-hidden="true" className={`absolute inset-y-0 left-0 w-[3px] ${EDGE[plan.status]}`} />
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`absolute inset-y-0 left-0 w-[3px] ${EDGE[plan.status]}`}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
|
||||
<span className="min-w-0 truncate font-semibold transition-colors group-hover:text-accent-text">
|
||||
{plan.title}
|
||||
</span>
|
||||
{creatorLabel && <span className="text-dim text-[0.8125rem]">utworzył: {creatorLabel}</span>}
|
||||
{creatorLabel && (
|
||||
<span className="text-dim text-[0.8125rem]">
|
||||
{creatorPrefix}: {creatorLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-dim text-[0.8125rem]">
|
||||
<MetaItem icon={CalendarDays}>{plan.weeksCount} tyg.</MetaItem>
|
||||
@@ -51,7 +67,9 @@ export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: str
|
||||
{completed}/{total} dni
|
||||
</span>
|
||||
)}
|
||||
{plan.startDate && <MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>}
|
||||
{plan.startDate && (
|
||||
<MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>
|
||||
)}
|
||||
</div>
|
||||
{isActive && total > 0 && (
|
||||
<div className="mt-2.5 flex items-center gap-2.5">
|
||||
@@ -61,7 +79,9 @@ export function PlanCard({ plan, creatorLabel }: { plan: Plan; creatorLabel: str
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">{percent}%</span>
|
||||
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">
|
||||
{percent}%
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
133
app/src/components/plans/SharePlanDialog.tsx
Normal file
133
app/src/components/plans/SharePlanDialog.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import { useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
sharePlan,
|
||||
unsharePlan,
|
||||
useIsTrainer,
|
||||
useMyTrainers,
|
||||
useTrainees,
|
||||
} from '../../api/queries';
|
||||
import { useToast } from '../toast';
|
||||
import { Button, ErrorText, Modal } from '../ui';
|
||||
import type { Plan } from '../../api/types';
|
||||
|
||||
/** Imię i nazwisko (fallback: pseudonim, potem „użytkownik”). */
|
||||
function userName(u: {
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
nickname?: string | null;
|
||||
}): string {
|
||||
return [u.firstName, u.lastName].filter(Boolean).join(' ') || u.nickname || 'użytkownik';
|
||||
}
|
||||
|
||||
/**
|
||||
* Udostępnianie planu (właściciel): lista odbiorców z AKTYWNYM coachingiem —
|
||||
* podopieczni (gdy rola TRAINER) i trenerzy. Checkbox = share/unshare natychmiast.
|
||||
* Odbiorca dostaje plan w trybie read-only.
|
||||
*/
|
||||
export function SharePlanDialog({
|
||||
open,
|
||||
onClose,
|
||||
plan,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
plan: Plan;
|
||||
}) {
|
||||
const queryClient = useQueryClient();
|
||||
const { push } = useToast();
|
||||
const isTrainer = useIsTrainer();
|
||||
const { data: traineesData } = useTrainees();
|
||||
const { data: trainersData } = useMyTrainers();
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const sharedIds = new Set((plan.shares ?? []).map((s) => s.userId));
|
||||
const trainees = (traineesData?.trainees ?? []).map((t) => t.user);
|
||||
const trainers = trainersData?.trainers ?? [];
|
||||
const hasSections = isTrainer || trainers.length > 0;
|
||||
|
||||
const toggle = async (userId: string, name: string) => {
|
||||
setBusyId(userId);
|
||||
setError('');
|
||||
try {
|
||||
if (sharedIds.has(userId)) {
|
||||
await unsharePlan(plan.id, userId);
|
||||
push(`Cofnięto udostępnienie: ${name}`, 'success');
|
||||
} else {
|
||||
await sharePlan(plan.id, userId);
|
||||
push(`Udostępniono: ${name}`, 'success');
|
||||
}
|
||||
await queryClient.invalidateQueries({ queryKey: ['plans', plan.id] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['plans', 'shared-with-me'] });
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Błąd');
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const section = (
|
||||
title: string,
|
||||
users: {
|
||||
id: string;
|
||||
firstName: string | null;
|
||||
lastName: string | null;
|
||||
nickname?: string | null;
|
||||
}[],
|
||||
) => (
|
||||
<div>
|
||||
<p className="mb-2 text-[0.875rem] font-semibold">{title}</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{users.map((u) => {
|
||||
const checked = sharedIds.has(u.id);
|
||||
return (
|
||||
<label
|
||||
key={u.id}
|
||||
className="flex cursor-pointer items-center gap-2.5 rounded-[10px] border border-line bg-input px-3 py-2.5 transition-colors hover:border-accent/55"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={busyId === u.id}
|
||||
onChange={() => void toggle(u.id, userName(u))}
|
||||
className="h-4 w-4 accent-accent cursor-pointer disabled:opacity-50"
|
||||
/>
|
||||
<span className="text-[0.9rem]">{userName(u)}</span>
|
||||
{busyId === u.id && <span className="ml-auto text-dim text-[0.8rem]">…</span>}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="Udostępnij plan">
|
||||
<p className="mb-4 text-dim text-[0.9rem]">
|
||||
Udostępnij plan osobom, z którymi masz aktywną relację coaching — odbiorca widzi plan w
|
||||
trybie tylko do odczytu.
|
||||
</p>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
{!hasSections ? (
|
||||
<p className="text-dim text-[0.9rem]">
|
||||
Nie masz aktywnych relacji coaching (ani podopiecznych, ani trenerów) — nie ma komu
|
||||
udostępnić planu.
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{isTrainer && trainees.length > 0 && section('Moje podopieczne', trainees)}
|
||||
{trainers.length > 0 && section('Moje trenerki/trenerzy', trainers)}
|
||||
{isTrainer && trainees.length === 0 && trainers.length === 0 && (
|
||||
<p className="text-dim text-[0.9rem]">Brak aktywnych relacji coaching.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-5 flex justify-end">
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
Zamknij
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { CalendarDays, MapPin, Pencil, Play, Trash2 } from 'lucide-react';
|
||||
import { CalendarDays, MapPin, Pencil, Play, Share2, Trash2 } from 'lucide-react';
|
||||
import {
|
||||
abandonPlan,
|
||||
activatePlan,
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { fmtDate } from '../../lib/format';
|
||||
import { PLAN_STATUS } from '../../lib/labels';
|
||||
import { PlanWeeks } from '../../components/plans/PlanWeeks';
|
||||
import { SharePlanDialog } from '../../components/plans/SharePlanDialog';
|
||||
import { useToast } from '../../components/toast';
|
||||
import { useTopbar } from '../../topbar';
|
||||
import {
|
||||
@@ -43,6 +44,11 @@ export default function PlanDetail() {
|
||||
const [confirm, setConfirm] = useState<null | 'delete' | 'abandon'>(null);
|
||||
|
||||
const planData = data?.plan;
|
||||
const [shareOpen, setShareOpen] = useState(false);
|
||||
// Właściciel = pełne prawa; trener z ACTIVE coachingiem = zarządza (bez sharingu);
|
||||
// odbiorca share'a = read-only (canManage z detalu; fallback: właściciel).
|
||||
const isOwner = !!planData && !!meData && planData.userId === meData.user.id;
|
||||
const canManage = planData ? (planData.canManage ?? isOwner) : false;
|
||||
// Blokada aktywacji: tylko jeden plan może być aktywny w danej chwili.
|
||||
const hasOtherActivePlan = (plansData?.plans ?? []).some(
|
||||
(p) => p.status === 'ACTIVE' && p.id !== planData?.id,
|
||||
@@ -63,50 +69,65 @@ export default function PlanDetail() {
|
||||
};
|
||||
|
||||
// operacje stronicowe w menu kontekstowym (standard topmenu); WeekPicker + hint zostają w karcie
|
||||
// read-only (odbiorca share'a): bez akcji statusowych i bez „Udostępnij”
|
||||
useTopbar({
|
||||
title: 'Plany',
|
||||
back: '/plans',
|
||||
actions: planData
|
||||
? planData.status === 'DRAFT'
|
||||
actions:
|
||||
planData && canManage
|
||||
? [
|
||||
{
|
||||
label: 'Aktywuj',
|
||||
icon: Play,
|
||||
disabled: !startDate || busy || hasOtherActivePlan,
|
||||
onClick: () =>
|
||||
void act(() => activatePlan(planData.id, startDate), 'Plan aktywowany'),
|
||||
},
|
||||
{
|
||||
label: 'Edytuj',
|
||||
to: `/plans/${planData.id}/edit`,
|
||||
variant: 'secondary',
|
||||
icon: Pencil,
|
||||
},
|
||||
{
|
||||
label: 'Usuń',
|
||||
icon: Trash2,
|
||||
variant: 'danger',
|
||||
disabled: busy,
|
||||
onClick: () => setConfirm('delete'),
|
||||
},
|
||||
...(planData.status === 'DRAFT'
|
||||
? [
|
||||
{
|
||||
label: 'Aktywuj',
|
||||
icon: Play,
|
||||
disabled: !startDate || busy || hasOtherActivePlan,
|
||||
onClick: () =>
|
||||
void act(() => activatePlan(planData.id, startDate), 'Plan aktywowany'),
|
||||
},
|
||||
{
|
||||
label: 'Edytuj',
|
||||
to: `/plans/${planData.id}/edit`,
|
||||
variant: 'secondary' as const,
|
||||
icon: Pencil,
|
||||
},
|
||||
{
|
||||
label: 'Usuń',
|
||||
icon: Trash2,
|
||||
variant: 'danger' as const,
|
||||
disabled: busy,
|
||||
onClick: () => setConfirm('delete'),
|
||||
},
|
||||
]
|
||||
: planData.status === 'ACTIVE'
|
||||
? [
|
||||
{
|
||||
label: 'Oznacz jako ukończony',
|
||||
variant: 'secondary' as const,
|
||||
disabled: busy,
|
||||
onClick: () => void act(() => completePlan(planData.id), 'Plan ukończony'),
|
||||
},
|
||||
{
|
||||
label: 'Porzuć',
|
||||
variant: 'danger' as const,
|
||||
disabled: busy,
|
||||
onClick: () => setConfirm('abandon'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// udostępnianie = tylko właściciel planu
|
||||
...(isOwner
|
||||
? [
|
||||
{
|
||||
label: 'Udostępnij',
|
||||
icon: Share2,
|
||||
variant: 'secondary' as const,
|
||||
onClick: () => setShareOpen(true),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]
|
||||
: planData.status === 'ACTIVE'
|
||||
? [
|
||||
{
|
||||
label: 'Oznacz jako ukończony',
|
||||
variant: 'secondary',
|
||||
disabled: busy,
|
||||
onClick: () => void act(() => completePlan(planData.id), 'Plan ukończony'),
|
||||
},
|
||||
{
|
||||
label: 'Porzuć',
|
||||
variant: 'danger',
|
||||
disabled: busy,
|
||||
onClick: () => setConfirm('abandon'),
|
||||
},
|
||||
]
|
||||
: undefined
|
||||
: undefined,
|
||||
: undefined,
|
||||
defaultOpenGroup: 'actions',
|
||||
});
|
||||
|
||||
@@ -133,6 +154,12 @@ export default function PlanDetail() {
|
||||
? [plan.creator.firstName, plan.creator.lastName].filter(Boolean).join(' ')
|
||||
: '';
|
||||
|
||||
// Imiona odbiorców share'u (właściciel, gdy plan jest udostępniony).
|
||||
const sharedNames = (plan.shares ?? [])
|
||||
.map((s) => [s.user.firstName, s.user.lastName].filter(Boolean).join(' '))
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
@@ -153,6 +180,7 @@ export default function PlanDetail() {
|
||||
<MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>
|
||||
)}
|
||||
{creatorName && <Muted className="text-[0.875rem]">utworzył: {creatorName}</Muted>}
|
||||
{sharedNames && <Muted className="text-[0.875rem]">udostępnione: {sharedNames}</Muted>}
|
||||
</div>
|
||||
{allDays.length > 0 && (
|
||||
<div className="mt-3 flex items-center gap-2.5">
|
||||
@@ -167,7 +195,7 @@ export default function PlanDetail() {
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{plan.status === 'DRAFT' && (
|
||||
{plan.status === 'DRAFT' && canManage && (
|
||||
<div className="mt-4">
|
||||
<p className="mb-2 text-[0.875rem] text-dim">Tydzień startu</p>
|
||||
<WeekPicker value={startDate} onChange={setStartDate} />
|
||||
@@ -188,6 +216,7 @@ export default function PlanDetail() {
|
||||
|
||||
<PlanWeeks weeks={plan.weeks} showDate canExecute={plan.status === 'ACTIVE'} />
|
||||
|
||||
<SharePlanDialog open={shareOpen} onClose={() => setShareOpen(false)} plan={plan} />
|
||||
<ConfirmDialog
|
||||
open={confirm === 'delete'}
|
||||
onClose={() => setConfirm(null)}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { CalendarPlus, Dumbbell, Plus } from 'lucide-react';
|
||||
import { useMe, usePlans } from '../../api/queries';
|
||||
import { useMe, usePlans, useSharedWithMe } from '../../api/queries';
|
||||
import { PLAN_STATUS } from '../../lib/labels';
|
||||
import { PlanCard } from '../../components/plans/PlanCard';
|
||||
import { Badge, Button, Card, EmptyState, ErrorText, H3, Skeleton } from '../../components/ui';
|
||||
@@ -19,6 +19,7 @@ export default function Plans() {
|
||||
actions: [{ label: 'Nowy plan', to: '/plans/new', icon: Plus }],
|
||||
});
|
||||
const { data, isLoading, error } = usePlans();
|
||||
const { data: sharedData } = useSharedWithMe();
|
||||
const { data: meData } = useMe();
|
||||
const query = useListSearch((s) => s.queries.plans);
|
||||
const setQuery = useListSearch((s) => s.setQuery);
|
||||
@@ -30,6 +31,10 @@ export default function Plans() {
|
||||
return [p.creator.firstName, p.creator.lastName].filter(Boolean).join(' ') || 'trener';
|
||||
};
|
||||
|
||||
/** Imię i nazwisko osoby, która udostępniła plan (sekcja „Udostępnione mi”). */
|
||||
const sharedByLabel = (p: Plan): string =>
|
||||
[p.sharedBy?.firstName, p.sharedBy?.lastName].filter(Boolean).join(' ') || 'trener';
|
||||
|
||||
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
|
||||
useEffect(() => () => setQuery('plans', ''), [setQuery]);
|
||||
|
||||
@@ -44,6 +49,12 @@ export default function Plans() {
|
||||
plans: filtered.filter((p) => p.status === status),
|
||||
})).filter((g) => g.plans.length > 0);
|
||||
|
||||
// plany jawno udostępnione (read-only) — osobna sekcja pod kategoriami statusu
|
||||
const sharedPlans = sharedData?.plans ?? [];
|
||||
const filteredShared = query
|
||||
? sharedPlans.filter((p) => p.title.toLowerCase().includes(query.toLowerCase()))
|
||||
: sharedPlans;
|
||||
|
||||
return (
|
||||
<>
|
||||
{isLoading && (
|
||||
@@ -55,7 +66,7 @@ export default function Plans() {
|
||||
)}
|
||||
{error && <ErrorText>Błąd: {(error as Error).message}</ErrorText>}
|
||||
|
||||
{data && data.plans.length === 0 && (
|
||||
{data && plans.length === 0 && (
|
||||
<Card>
|
||||
<EmptyState
|
||||
icon={Dumbbell}
|
||||
@@ -73,7 +84,7 @@ export default function Plans() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{data && data.plans.length > 0 && filtered.length === 0 && (
|
||||
{data && plans.length > 0 && filtered.length === 0 && (
|
||||
<Card>
|
||||
<p className="text-dim">Brak wyników dla podanego zapytania.</p>
|
||||
</Card>
|
||||
@@ -96,6 +107,25 @@ export default function Plans() {
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
|
||||
{filteredShared.length > 0 && (
|
||||
<section className="mb-5">
|
||||
<div className="mb-2.5 flex items-center gap-2.5">
|
||||
<H3 className="mb-0">Udostępnione mi</H3>
|
||||
<Badge color="blue">{filteredShared.length}</Badge>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
{filteredShared.map((p) => (
|
||||
<PlanCard
|
||||
key={p.id}
|
||||
plan={p}
|
||||
creatorLabel={sharedByLabel(p)}
|
||||
creatorPrefix="udostępnił"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
321
app/test/PlanDetail.test.tsx
Normal file
321
app/test/PlanDetail.test.tsx
Normal file
@@ -0,0 +1,321 @@
|
||||
import { render, screen, waitFor, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import App from '../src/App';
|
||||
import { useAuth } from '../src/store/auth';
|
||||
import { setAccessToken } from '../src/api/client';
|
||||
import type { User } from '../src/api/types';
|
||||
|
||||
const OWNER: User = {
|
||||
id: 'u1',
|
||||
email: 'jan@test.local',
|
||||
firstName: 'Jan',
|
||||
lastName: 'Kowalski',
|
||||
age: 30,
|
||||
heightCm: 180,
|
||||
phone: null,
|
||||
isAdmin: false,
|
||||
availability: null,
|
||||
priorities: 'chest',
|
||||
exclusions: 'knee',
|
||||
developMuscles: [],
|
||||
canDoMuscles: [],
|
||||
difficultMuscles: [],
|
||||
avoidMuscles: [],
|
||||
createdAt: '2026-08-22T10:00:00.000Z',
|
||||
};
|
||||
|
||||
const RECIPIENT: User = {
|
||||
...OWNER,
|
||||
id: 'u2',
|
||||
email: 'anna@test.local',
|
||||
firstName: 'Anna',
|
||||
lastName: 'Nowak',
|
||||
};
|
||||
|
||||
const TRAINEE = {
|
||||
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
|
||||
gyms: [{ id: 'gym-1', name: 'Żelazna Świątynia' }],
|
||||
activePlan: null,
|
||||
killstreak: 0,
|
||||
lastSessionAt: null,
|
||||
flags: [],
|
||||
};
|
||||
|
||||
/** Detal planu (właściciel = u1); warianty: canManage / shares / sharedBy. */
|
||||
function planDetail(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'plan-1',
|
||||
userId: 'u1',
|
||||
title: 'Plan masowy',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 1,
|
||||
startDate: null,
|
||||
gym: null,
|
||||
creator: null,
|
||||
canManage: true,
|
||||
shares: [],
|
||||
weeks: [
|
||||
{
|
||||
id: 'tw-1',
|
||||
index: 0,
|
||||
customName: null,
|
||||
days: [
|
||||
{
|
||||
id: 'td-1',
|
||||
dayOfWeek: 1,
|
||||
date: null,
|
||||
status: 'PLANNED',
|
||||
moveLog: [],
|
||||
sessions: [],
|
||||
exercises: [
|
||||
{
|
||||
id: 'tpe-1',
|
||||
exerciseId: 'ex-1',
|
||||
order: 0,
|
||||
exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
|
||||
sets: [
|
||||
{
|
||||
id: 'tps-1',
|
||||
index: 0,
|
||||
reps: 10,
|
||||
loadKg: 60,
|
||||
restSec: 90,
|
||||
rir: 2,
|
||||
difficulty: 3,
|
||||
cardioBpm: null,
|
||||
timeSec: null,
|
||||
speed: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
interface MockOpts {
|
||||
user: User;
|
||||
memberships?: { gymId: string; roles: string[] }[];
|
||||
plans?: Record<string, unknown>[];
|
||||
sharedWithMe?: Record<string, unknown>[];
|
||||
plan?: Record<string, unknown>;
|
||||
trainees?: unknown[];
|
||||
trainers?: unknown[];
|
||||
}
|
||||
|
||||
interface Capture {
|
||||
shareBody?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function mockApi(capture: Capture, opts: MockOpts) {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input);
|
||||
const method = init?.method || 'GET';
|
||||
if (url.includes('/auth/login'))
|
||||
return jsonResponse(200, { user: opts.user, accessToken: 'tok-1' });
|
||||
if (url.includes('/auth/refresh'))
|
||||
return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } });
|
||||
if (url.includes('/me/active-session')) return jsonResponse(200, { session: null });
|
||||
if (url.endsWith('/me'))
|
||||
return jsonResponse(200, { user: opts.user, memberships: opts.memberships ?? [] });
|
||||
if (url.includes('/me/trainers'))
|
||||
return jsonResponse(200, { trainers: opts.trainers ?? [] });
|
||||
if (url.includes('/trainer/trainees'))
|
||||
return jsonResponse(200, { trainees: opts.trainees ?? [] });
|
||||
if (url.includes('/dashboard'))
|
||||
return jsonResponse(200, {
|
||||
killstreak: 0,
|
||||
activePlan: null,
|
||||
nextTraining: null,
|
||||
progress: null,
|
||||
extra: null,
|
||||
missing: null,
|
||||
});
|
||||
if (url.includes('/exercises'))
|
||||
return jsonResponse(200, { exercises: [] });
|
||||
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
|
||||
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
|
||||
if (url.includes('/plans/shared-with-me'))
|
||||
return jsonResponse(200, { plans: opts.sharedWithMe ?? [] });
|
||||
if (url.includes('/plans/plan-1/share')) {
|
||||
if (method === 'POST') {
|
||||
capture.shareBody = JSON.parse(String(init?.body));
|
||||
return jsonResponse(201, { ok: true });
|
||||
}
|
||||
if (method === 'DELETE') return jsonResponse(200, { ok: true });
|
||||
}
|
||||
if (url.endsWith('/plans')) return jsonResponse(200, { plans: opts.plans ?? [] });
|
||||
if (url.includes('/plans/plan-1'))
|
||||
return jsonResponse(200, { plan: opts.plan ?? planDetail() });
|
||||
return jsonResponse(200, {});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function renderApp() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
||||
});
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<App />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
async function loginAndOpenPlans(user: userEvent.User, email: string) {
|
||||
expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument();
|
||||
const emailInput = document.querySelector('input[type="email"]') as HTMLInputElement;
|
||||
const password = document.querySelector('input[type="password"]') as HTMLInputElement;
|
||||
await user.type(emailInput, email);
|
||||
await user.type(password, 'Password123!');
|
||||
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
|
||||
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('link', { name: 'Plany' }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plany' })).toBeInTheDocument();
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
setAccessToken(null);
|
||||
localStorage.clear();
|
||||
useAuth.setState({ user: null, ready: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('PlanDetail — udostępnianie planów (WP4)', () => {
|
||||
it('właściciel: akcje w topmenu (Aktywuj/Edytuj/Usuń/Udostępnij) i wybór tygodnia startu', async () => {
|
||||
mockApi(
|
||||
{},
|
||||
{
|
||||
user: OWNER,
|
||||
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
|
||||
plans: [planDetail()],
|
||||
},
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenPlans(user, OWNER.email);
|
||||
|
||||
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
|
||||
|
||||
const header = document.querySelector('header')!;
|
||||
expect(within(header).getByRole('button', { name: 'Aktywuj' })).toBeInTheDocument();
|
||||
expect(within(header).getByRole('button', { name: 'Edytuj' })).toBeInTheDocument();
|
||||
expect(within(header).getByRole('button', { name: 'Usuń' })).toBeInTheDocument();
|
||||
expect(within(header).getByRole('button', { name: 'Udostępnij' })).toBeInTheDocument();
|
||||
// DRAFT + canManage — wybór tygodnia startu w karcie
|
||||
expect(screen.getByText('Tydzień startu')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('odbiorca share’a: sekcja „Udostępnione mi”, plan read-only (bez akcji i bez tygodnia startu)', async () => {
|
||||
const shared = planDetail({
|
||||
canManage: false,
|
||||
shares: undefined,
|
||||
sharedBy: { id: 'u1', firstName: 'Jan', lastName: 'Kowalski' },
|
||||
});
|
||||
mockApi(
|
||||
{},
|
||||
{
|
||||
user: RECIPIENT,
|
||||
plans: [],
|
||||
sharedWithMe: [shared],
|
||||
plan: shared,
|
||||
},
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenPlans(user, RECIPIENT.email);
|
||||
|
||||
// sekcja „Udostępnione mi” z etykietą twórcy
|
||||
expect(screen.getByRole('heading', { name: 'Udostępnione mi' })).toBeInTheDocument();
|
||||
expect(screen.getByText('udostępnił: Jan Kowalski')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
|
||||
|
||||
// read-only: brak akcji statusowych, „Udostępnij” i wyboru tygodnia startu
|
||||
expect(screen.queryByRole('button', { name: 'Aktywuj' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Edytuj' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Usuń' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Udostępnij' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Tydzień startu')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('dialog „Udostępnij plan”: podopieczni z checkboxem, share = POST /plans/:id/share', async () => {
|
||||
const capture: Capture = {};
|
||||
mockApi(
|
||||
capture,
|
||||
{
|
||||
user: OWNER,
|
||||
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
|
||||
plans: [planDetail()],
|
||||
trainees: [TRAINEE],
|
||||
},
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenPlans(user, OWNER.email);
|
||||
|
||||
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Udostępnij' }));
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Udostępnij plan' });
|
||||
expect(within(dialog).getByText('Moje podopieczne')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Anna Nowak')).toBeInTheDocument();
|
||||
|
||||
const checkbox = within(dialog).getByRole('checkbox') as HTMLInputElement;
|
||||
await user.click(checkbox);
|
||||
await waitFor(() =>
|
||||
expect(capture.shareBody).toMatchObject({ userId: 'trainee-1' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('właściciel z udostępnionym planem: etykieta „udostępnione: …” w meta', async () => {
|
||||
mockApi(
|
||||
{},
|
||||
{
|
||||
user: OWNER,
|
||||
plans: [planDetail()],
|
||||
plan: planDetail({
|
||||
shares: [
|
||||
{
|
||||
userId: 'trainee-1',
|
||||
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' },
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderApp();
|
||||
await loginAndOpenPlans(user, OWNER.email);
|
||||
|
||||
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
|
||||
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
|
||||
expect(screen.getByText('udostępnione: Anna Nowak')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -30,6 +30,7 @@ const USER: User = {
|
||||
const PLANS: Plan[] = [
|
||||
{
|
||||
id: 'plan-1',
|
||||
userId: 'u1',
|
||||
title: 'Plan masowy',
|
||||
status: 'ACTIVE',
|
||||
weeksCount: 8,
|
||||
@@ -38,6 +39,7 @@ const PLANS: Plan[] = [
|
||||
},
|
||||
{
|
||||
id: 'plan-2',
|
||||
userId: 'u1',
|
||||
title: 'Szkic siłowy',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 4,
|
||||
@@ -46,6 +48,7 @@ const PLANS: Plan[] = [
|
||||
},
|
||||
{
|
||||
id: 'plan-3',
|
||||
userId: 'u1',
|
||||
title: 'Plan definicyjny',
|
||||
status: 'COMPLETED',
|
||||
weeksCount: 6,
|
||||
@@ -71,6 +74,7 @@ function mockApi(plans: Plan[] = PLANS) {
|
||||
if (url.includes('/dashboard'))
|
||||
return jsonResponse(200, { killstreak: 0, activePlan: null, nextTraining: null, progress: null });
|
||||
if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] });
|
||||
if (url.includes('/plans/shared-with-me')) return jsonResponse(200, { plans: [] });
|
||||
if (url.includes('/plans')) return jsonResponse(200, { plans });
|
||||
if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] });
|
||||
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
||||
|
||||
@@ -401,6 +401,7 @@ export const TEST_MY_EXERCISE_PROGRESS = TEST_TRAINEE_EXERCISE_PROGRESS;
|
||||
export const TEST_TRAINEE_PLANS = [
|
||||
{
|
||||
id: 'tp-1',
|
||||
userId: 'trainee-1',
|
||||
title: 'Plan masowy',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 1,
|
||||
@@ -411,6 +412,7 @@ export const TEST_TRAINEE_PLANS = [
|
||||
},
|
||||
{
|
||||
id: 'tp-2',
|
||||
userId: 'trainee-1',
|
||||
title: 'Plan aktywny',
|
||||
status: 'ACTIVE',
|
||||
weeksCount: 4,
|
||||
@@ -423,6 +425,8 @@ export const TEST_TRAINEE_PLANS = [
|
||||
|
||||
export const TEST_TRAINEE_PLAN_DETAIL = {
|
||||
id: 'tp-1',
|
||||
userId: 'trainee-1',
|
||||
canManage: true,
|
||||
title: 'Plan masowy',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 1,
|
||||
@@ -459,8 +463,25 @@ export const TEST_TRAINEE_PLAN_DETAIL = {
|
||||
],
|
||||
};
|
||||
|
||||
/** Plan udostępniony zalogowanemu użytkownikowi (read-only; właściciel = trener). */
|
||||
export const TEST_SHARED_PLAN = {
|
||||
id: 'shared-1',
|
||||
userId: 'trainer-2',
|
||||
canManage: false,
|
||||
title: 'Plan udostępniony',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 2,
|
||||
startDate: null,
|
||||
gym: null,
|
||||
creator: null,
|
||||
sharedBy: { id: 'trainer-2', firstName: 'Jan', lastName: 'Kowalski' },
|
||||
weeks: [],
|
||||
};
|
||||
|
||||
export const TEST_TRAINEE_PLAN_DETAIL_ACTIVE = {
|
||||
id: 'tp-2',
|
||||
userId: 'trainee-1',
|
||||
canManage: true,
|
||||
title: 'Plan aktywny',
|
||||
status: 'ACTIVE',
|
||||
weeksCount: 4,
|
||||
@@ -688,6 +709,10 @@ export interface MockApiOptions {
|
||||
gymInvitations?: unknown;
|
||||
/** Ciało odpowiedzi GET /gyms (własne siłownie z rolami; domyślnie: TEST_GYM_OWNED). */
|
||||
myGyms?: unknown;
|
||||
/** Ciało odpowiedzi GET /plans/shared-with-me (domyślnie: brak udostępnionych planów). */
|
||||
sharedWithMe?: unknown;
|
||||
/** Ciało odpowiedzi GET /me/trainers (domyślnie: brak trenerów). */
|
||||
myTrainers?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -710,6 +735,8 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
messageThread = TEST_MESSAGE_THREAD,
|
||||
gymInvitations = { invitations: [] },
|
||||
myGyms,
|
||||
sharedWithMe,
|
||||
myTrainers,
|
||||
} = opts;
|
||||
|
||||
// Stateful: equipment added via POST /gyms/:id/equipment persists on refetch.
|
||||
@@ -793,6 +820,21 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(activeSession) }),
|
||||
);
|
||||
|
||||
// ---------- udostępnianie planów (PlanShare) ----------
|
||||
page.route('**/api/v1/plans/shared-with-me', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(sharedWithMe ?? { plans: [] }) }),
|
||||
);
|
||||
page.route('**/api/v1/me/trainers', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(myTrainers ?? { trainers: [] }) }),
|
||||
);
|
||||
page.route('**/api/v1/plans/*/share', (route) =>
|
||||
route.fulfill({
|
||||
status: route.request().method() === 'POST' ? 201 : 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ ok: true }),
|
||||
}),
|
||||
);
|
||||
|
||||
page.route('**/api/v1/focus-areas', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
@@ -1382,11 +1424,14 @@ export function mockPlans(page: Page) {
|
||||
body: JSON.stringify({
|
||||
plan: {
|
||||
id: 'plan-new',
|
||||
userId: 'user-test',
|
||||
canManage: true,
|
||||
title: 'Plan e2e',
|
||||
status: 'ACTIVE',
|
||||
weeksCount: 4,
|
||||
startDate: '2026-08-24',
|
||||
gym: null,
|
||||
creator: null,
|
||||
weeks: [],
|
||||
},
|
||||
}),
|
||||
|
||||
138
app/test/e2e/plans-sharing.spec.ts
Normal file
138
app/test/e2e/plans-sharing.spec.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { test, expect, type Page } from './fixtures';
|
||||
import { mockApi, TEST_SHARED_PLAN, TEST_USER } from './mock-api';
|
||||
|
||||
/* Udostępnianie planów (PlanShare): sekcja „Udostępnione mi” (read-only)
|
||||
i dialog „Udostępnij plan” (właściciel → podopieczni/trenerzy). */
|
||||
|
||||
/** Detal planu właściciela (DRAFT, canManage, bez share'ów). */
|
||||
const OWNER_PLAN = {
|
||||
id: 'plan-1',
|
||||
userId: 'user-test',
|
||||
canManage: true,
|
||||
title: 'Plan masowy',
|
||||
status: 'DRAFT',
|
||||
weeksCount: 1,
|
||||
startDate: null,
|
||||
gym: null,
|
||||
creator: null,
|
||||
shares: [],
|
||||
weeks: [],
|
||||
};
|
||||
|
||||
/** Właściciel = trener z podopiecznymi (dialog sharingu ma kogo pokazać). */
|
||||
function mockOwnerPlans(page: Page) {
|
||||
mockApi(page, {
|
||||
me: { user: TEST_USER, memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }] },
|
||||
});
|
||||
// Stateful: udostępnienia widoczne w detalu po POST (jak w realnym API).
|
||||
const shares: { userId: string; user: { id: string; firstName: string; lastName: string } }[] = [];
|
||||
page.route('**/api/v1/plans/plan-1/share', (route) => {
|
||||
const req = route.request();
|
||||
if (req.method() === 'POST') {
|
||||
const body = req.postDataJSON() as { userId: string };
|
||||
if (!shares.some((s) => s.userId === body.userId)) {
|
||||
shares.push({
|
||||
userId: body.userId,
|
||||
user: { id: body.userId, firstName: 'Anna', lastName: 'Nowak' },
|
||||
});
|
||||
}
|
||||
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
|
||||
}
|
||||
if (req.method() === 'DELETE') {
|
||||
const userId = req.url().split('/').slice(-2, -1)[0];
|
||||
const i = shares.findIndex((s) => s.userId === userId);
|
||||
if (i >= 0) shares.splice(i, 1);
|
||||
}
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) });
|
||||
});
|
||||
page.route('**/api/v1/plans/plan-1', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ plan: { ...OWNER_PLAN, shares: [...shares] } }),
|
||||
}),
|
||||
);
|
||||
page.route('**/api/v1/plans', (route) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
return route.fulfill({
|
||||
status: 201,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ plan: { id: 'plan-1' } }),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ plans: [OWNER_PLAN] }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Odbiorca share'a: plan w sekcji „Udostępnione mi”, detal read-only. */
|
||||
function mockRecipientPlans(page: Page) {
|
||||
mockApi(page, { sharedWithMe: { plans: [TEST_SHARED_PLAN] } });
|
||||
page.route('**/api/v1/plans/shared-1', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ plan: TEST_SHARED_PLAN }),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function login(page: Page) {
|
||||
await page.goto('/login');
|
||||
await page.locator('input[type="email"]').fill('test@fitos.pl');
|
||||
await page.locator('input[type="password"]').fill('haslo123');
|
||||
await page.getByRole('button', { name: 'Zaloguj' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
|
||||
}
|
||||
|
||||
test('„Udostępnione mi”: plan read-only — bez akcji statusowych, „Udostępnij” i tygodnia startu', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockRecipientPlans(page);
|
||||
await login(page);
|
||||
|
||||
await page.getByRole('link', { name: 'Plany' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Udostępnione mi' })).toBeVisible();
|
||||
await expect(page.getByText('udostępnił: Jan Kowalski')).toBeVisible();
|
||||
|
||||
await page.getByRole('link', { name: /Plan udostępniony/ }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Plan udostępniony' })).toBeVisible();
|
||||
|
||||
// read-only: brak akcji w topbarze i wyboru tygodnia startu w karcie
|
||||
await expect(page.getByRole('button', { name: 'Aktywuj' })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Edytuj' })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Usuń' })).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: 'Udostępnij' })).toHaveCount(0);
|
||||
await expect(page.getByText('Tydzień startu')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('właściciel: „Udostępnij” — dialog z podopiecznymi, share = POST /plans/:id/share', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockOwnerPlans(page);
|
||||
await login(page);
|
||||
|
||||
await page.getByRole('link', { name: 'Plany' }).click();
|
||||
await page.getByRole('link', { name: /Plan masowy/ }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Plan masowy' })).toBeVisible();
|
||||
|
||||
// DRAFT + canManage: wybór tygodnia startu + akcje w topbarze
|
||||
await expect(page.getByText('Tydzień startu', { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Aktywuj' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Udostępnij' })).toBeVisible();
|
||||
|
||||
await page.getByRole('button', { name: 'Udostępnij' }).click();
|
||||
await expect(page.getByRole('dialog', { name: 'Udostępnij plan' })).toBeVisible();
|
||||
await expect(page.getByText('Moje podopieczne')).toBeVisible();
|
||||
|
||||
// checkbox = natychmiastowy share (POST /plans/:id/share);
|
||||
// stan checkboxa i meta wracają z refetchu detalu (asynchronicznie)
|
||||
const checkbox = page.getByRole('checkbox');
|
||||
await checkbox.click();
|
||||
await expect(checkbox).toBeChecked();
|
||||
// efekt share'a wycięty z detalu: odbiorca w meta planu (trwały, bez wyścigu z toastem)
|
||||
await expect(page.getByText('udostępnione: Anna Nowak')).toBeVisible();
|
||||
});
|
||||
Reference in New Issue
Block a user