Backend: RBAC faza 2 M1 - role gymowe z grantow zamiast kolumny roles (migracja: seed GYM_OWNER/GYM_TRAINER + backfill grantow i uzupelnienie Coaching.gymId; katalog 11 uprawnien gym z pinem gym:delegate tylko dla wlasciciela; resolver lib/gymPermissions i bramy per zasob w uslugach silowni, feedzie, obecnosciach i kontaktach; CRUD rol custom per silownia z kluczem serwerowym + PUT ról czlonka pod /admin/gyms; rekrutacja trenera wymaga wspolnej silowni (Coaching.gymId, 0 lub wiele = 400); DTO roles wyprowadzane z grantow - kolumna roles martwa do M4; wyszukiwanie admina po e-mailu wymaga pii:read; 15 unit testow resolvera, zestaw api 1009 green)

This commit is contained in:
tisachi
2026-11-26 00:37:17 +01:00
parent 61e28ff723
commit 654dbf97e0
45 changed files with 1648 additions and 426 deletions

View File

@@ -1,6 +1,7 @@
import type { PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { isPrismaNotFound } from '../lib/prisma.js';
import { ROLE_KEYS } from '../lib/permissions.js';
import { getKillstreak } from './killstreak.js';
import { getDashboard } from './dashboard.js';
import { getHistory } from './me.js';
@@ -136,10 +137,62 @@ export async function computeTraineeMetrics(
}
async function hasTrainerRole(prisma: PrismaClient, userId: string): Promise<boolean> {
const membership = await prisma.gymMembership.findFirst({
where: { userId, roles: { has: 'TRAINER' } },
const grant = await prisma.userRoleGrant.findFirst({
where: { userId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_TRAINER } },
select: { id: true },
});
return !!membership;
return !!grant;
}
/** Sygnatura trainera w konkretnej siłowni (grant GYM_TRAINER). */
async function isTrainerInGym(
prisma: PrismaClient,
userId: string,
gymId: string,
): Promise<boolean> {
const grant = await prisma.userRoleGrant.findFirst({
where: { userId, gymId, role: { key: ROLE_KEYS.GYM_TRAINER } },
select: { id: true },
});
return !!grant;
}
/**
* Gym dla nowej relacji coachingu (faza 2, per-siłownia): kandydaci = siłownie,
* w których TRAINER ma grant GYM_TRAINER, a podopieczny jest członkiem.
* Jawny `gymId` → musi spełniać oba warunki; bez → dokładnie jeden kandydat.
*/
async function resolveCoachingGym(
prisma: PrismaClient,
trainerId: string,
traineeId: string,
explicitGymId?: string | null,
): Promise<string> {
if (explicitGymId) {
if (!(await isTrainerInGym(prisma, trainerId, explicitGymId)))
throw badRequest('Trainer has no trainer role in this gym');
const member = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: traineeId, gymId: explicitGymId } },
select: { id: true },
});
if (!member) throw badRequest('Trainee is not a member of this gym');
return explicitGymId;
}
const grants = await prisma.userRoleGrant.findMany({
where: { userId: trainerId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_TRAINER } },
select: { gymId: true },
});
const gymIds = grants.map((g) => g.gymId).filter((id): id is string => !!id);
if (gymIds.length === 0) throw badRequest('Trainer role required');
const memberships = await prisma.gymMembership.findMany({
where: { userId: traineeId, gymId: { in: gymIds } },
select: { gymId: true },
});
const shared = memberships.map((m) => m.gymId);
if (shared.length === 0)
throw badRequest('Trainer and trainee share no common gym with trainer role');
if (shared.length > 1) throw badRequest('Ambiguous gym; pass gymId');
return shared[0];
}
export async function isTrainer(prisma: PrismaClient, userId: string): Promise<boolean> {
@@ -208,7 +261,12 @@ export async function searchUsers(
* - only the target is a trainer -> the target becomes the trainer (trainee invites trainer),
* - otherwise the requester is the trainer (trainer invites a trainee).
*/
export async function sendInvitation(prisma: PrismaClient, requesterId: string, targetId: string) {
export async function sendInvitation(
prisma: PrismaClient,
requesterId: string,
targetId: string,
gymId?: string | null,
) {
if (targetId === requesterId) throw badRequest('Cannot invite yourself');
const target = await prisma.user.findUnique({ where: { id: targetId } });
if (!target) throw notFound('User not found');
@@ -219,6 +277,7 @@ export async function sendInvitation(prisma: PrismaClient, requesterId: string,
if (!requesterIsTrainer && !targetIsTrainer) throw badRequest('Trainer role required');
const trainerId = targetIsTrainer && !requesterIsTrainer ? targetId : requesterId;
const userId = trainerId === requesterId ? targetId : requesterId;
const coachingGymId = await resolveCoachingGym(prisma, trainerId, userId, gymId);
const existing = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
@@ -240,10 +299,17 @@ export async function sendInvitation(prisma: PrismaClient, requesterId: string,
const coaching = existing
? await prisma.coaching.update({
where: { id: existing.id },
data: { status: 'PENDING', invitedBy: requesterId, invitedAt: now, expiresAt, note: null },
data: {
status: 'PENDING',
invitedBy: requesterId,
invitedAt: now,
expiresAt,
note: null,
gymId: coachingGymId,
},
})
: await prisma.coaching.create({
data: { trainerId, userId, invitedBy: requesterId, expiresAt },
data: { trainerId, userId, invitedBy: requesterId, expiresAt, gymId: coachingGymId },
});
return { coaching, targetEmail: target.email };
}
@@ -369,29 +435,38 @@ export async function withdrawInvitation(prisma: PrismaClient, userId: string, c
}
}
/** Active trainees of the trainer (global list, optional gym filter by trainee membership). */
/** Active trainees of the trainer (optional gym filter by trainee membership).
* Relacje per-gym (faza 2) widoczne tylko, gdy trainer nadal ma grant w danym gymie. */
export async function listTrainees(prisma: PrismaClient, trainerId: string, gymId?: string) {
const coachings = await prisma.coaching.findMany({
where: {
trainerId,
status: 'ACTIVE',
...(gymId ? { user: { memberships: { some: { gymId } } } } : {}),
},
include: {
user: {
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
memberships: { select: { gym: { select: { id: true, name: true } } } },
const [coachings, trainerGrants] = await Promise.all([
prisma.coaching.findMany({
where: {
trainerId,
status: 'ACTIVE',
...(gymId ? { user: { memberships: { some: { gymId } } } } : {}),
},
include: {
user: {
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
memberships: { select: { gym: { select: { id: true, name: true } } } },
},
},
},
},
orderBy: { createdAt: 'asc' },
});
orderBy: { createdAt: 'asc' },
}),
prisma.userRoleGrant.findMany({
where: { userId: trainerId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_TRAINER } },
select: { gymId: true },
}),
]);
const trainerGyms = new Set(trainerGrants.map((g) => g.gymId));
const visible = coachings.filter((c) => !c.gymId || trainerGyms.has(c.gymId));
const trainees = await Promise.all(
coachings.map(async (c) => {
visible.map(async (c) => {
const metrics = await computeTraineeMetrics(prisma, c.user.id);
return {
user: {
@@ -408,12 +483,15 @@ export async function listTrainees(prisma: PrismaClient, trainerId: string, gymI
return { trainees };
}
/** The trainer must have an ACTIVE coaching relation with the user. */
/** The trainer must have an ACTIVE coaching relation with the user (and, for per-gym
* relations since phase 2, the trainer role in that gym). */
export async function assertActiveTrainee(prisma: PrismaClient, trainerId: string, userId: string) {
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
});
if (!coaching || coaching.status !== 'ACTIVE') throw notFound('Trainee not found');
if (coaching.gymId && !(await isTrainerInGym(prisma, trainerId, coaching.gymId)))
throw notFound('Trainee not found');
return coaching;
}