Plany: PATCH z startDate (aktywacja przy zapisie) i udostepnianie planow trener-podopieczny (PlanShare, sekcja Udostepnione mi, widok read-only)
This commit is contained in:
@@ -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,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user