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

3
.gitattributes vendored Normal file
View File

@@ -0,0 +1,3 @@
# Migracje Prisma: checksumy liczone od bajtow pliku — wymuszenie LF (autocrlf na Windows
# inaczej zmienia zawartosc po checkout i `migrate deploy` uwaza zastosowana migracje za zmodyfikowana).
api/prisma/migrations/** text eol=lf

View File

@@ -0,0 +1,78 @@
-- AlterTable
ALTER TABLE "Role" ADD COLUMN "gymId" TEXT,
ADD COLUMN "name" TEXT;
-- CreateIndex
CREATE INDEX "Role_gymId_idx" ON "Role"("gymId");
-- AddForeignKey
ALTER TABLE "Role" ADD CONSTRAINT "Role_gymId_fkey" FOREIGN KEY ("gymId") REFERENCES "Gym"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- SeedSystemRoles (gym): katalog zgodny z api/src/lib/permissions.ts.
-- GYM_OWNER = pelna kontrola siłowni (z gym:delete i przypietym gym:delegate),
-- GYM_TRAINER = dostep do domeny /trainer w danej siłowni.
INSERT INTO "Role" ("id", "key", "permissions", "isSystem", "createdAt", "updatedAt")
VALUES
(
'role_gym_owner',
'GYM_OWNER',
ARRAY[
'gym:edit',
'gym:delete',
'gym:members',
'gym:delegate',
'gym:equipment',
'gym:gallery',
'gym:announcements',
'gym:exceptions',
'gym:stats',
'gym:contact'
],
true,
now(),
now()
),
(
'role_gym_trainer',
'GYM_TRAINER',
ARRAY['trainer:clients'],
true,
now(),
now()
)
ON CONFLICT ("key") DO NOTHING;
-- Backfill grantow z GymMembership.roles (kolumna roles pozostaje martwa do cleanupu).
INSERT INTO "UserRoleGrant" ("id", "userId", "roleId", "gymId")
SELECT gen_random_uuid()::text, m."userId", r."id", m."gymId"
FROM "GymMembership" m
JOIN "Role" r ON r."key" = 'GYM_OWNER'
WHERE 'OWNER' = ANY(m."roles")
ON CONFLICT DO NOTHING;
INSERT INTO "UserRoleGrant" ("id", "userId", "roleId", "gymId")
SELECT gen_random_uuid()::text, m."userId", r."id", m."gymId"
FROM "GymMembership" m
JOIN "Role" r ON r."key" = 'GYM_TRAINER'
WHERE 'TRAINER' = ANY(m."roles")
ON CONFLICT DO NOTHING;
-- Backfill Coaching.gymId: tylko gdy para trener-podopieczny ma dokladnie jedna
-- wspolna siłownie; wiecej/nic = zostaje NULL (legacy, obslugiwane przy /trainer).
WITH shared AS (
SELECT c."id" AS "coachingId", m1."gymId"
FROM "Coaching" c
JOIN "GymMembership" m1 ON m1."userId" = c."trainerId"
JOIN "GymMembership" m2 ON m2."userId" = c."userId" AND m2."gymId" = m1."gymId"
WHERE c."gymId" IS NULL
),
onegym AS (
SELECT "coachingId", MIN("gymId") AS "gymId"
FROM shared
GROUP BY "coachingId"
HAVING COUNT(DISTINCT "gymId") = 1
)
UPDATE "Coaching" c
SET "gymId" = o."gymId"
FROM onegym o
WHERE c."id" = o."coachingId";

View File

@@ -177,16 +177,23 @@ model User {
}
/// Rola RBAC: klucz + zestaw uprawnień (katalog w kodzie: lib/permissions.ts).
/// `isSystem` = rola seedowana (ADMIN/MODERATOR): niedeletowalna, bez zmiany klucza.
/// `isSystem` = rola seedowana (ADMIN/MODERATOR/GYM_OWNER/GYM_TRAINER): niedeletowalna,
/// bez zmiany klucza. `gymId = null` = rola platformowa; z `gymId` = rola custom
/// jednej siłowni (faza 2). `name` — nazwa wyświetlana (custom role bez wpisu w locales).
model Role {
id String @id @default(cuid())
key String @unique
permissions String[]
isSystem Boolean @default(false)
gymId String?
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
grants UserRoleGrant[]
gym Gym? @relation("RoleGym", fields: [gymId], references: [id], onDelete: Cascade)
@@index([gymId])
}
/// Grant roli użytkownikowi. `gymId = null` = rola platformowa (faza 1 — jedyna
@@ -418,6 +425,7 @@ model Gym {
presences GymPresence[]
conversations GymConversation[]
roleGrants UserRoleGrant[]
gymRoles Role[] @relation("RoleGym")
}
/// Zdjęcie w galerii siłowni REAL. `order` = kolejność; okładka = najmniejsze `order` (tie → najstarsze `createdAt`).

View File

@@ -0,0 +1,161 @@
import type { GymRole, PrismaClient } from '@prisma/client';
import { forbidden } from './errors.js';
import {
GYM_PERMISSIONS,
knownGymPermissions,
ROLE_KEYS,
type GymPermissionKey,
} from './permissions.js';
/**
* Uprawnienia gymowe (faza 2 RBAC). Rozstrzygane per siłownia z grantów
* `UserRoleGrant(gymId = <siłownia>)`; rola musi należeć do tej siłowni
* (`Role.gymId = gymId`) — ról platformowych nie da się przydzielić gymowo.
* Kolumna `GymMembership.roles` jest martwa: MEMBER = sam wiersz członkostwa,
* OWNER/TRAINER w DTO wyprowadzamy z grantów (`deriveMembershipRoles`).
*/
export interface GymGrantRow {
role: { key: string; permissions: string[] };
}
export function gymPermissionsFromGrants(grants: readonly GymGrantRow[]): GymPermissionKey[] {
return [...new Set(knownGymPermissions(grants.flatMap((g) => g.role.permissions)))];
}
export function gymRoleKeys(grants: readonly GymGrantRow[]): string[] {
return grants.map((g) => g.role.key);
}
export function canGym(permissions: readonly string[], key: GymPermissionKey): boolean {
return permissions.includes(key);
}
/**
* Granty gymowe użytkownika dla danej siłowni. Grant nosi `gymId`; rola może być
* customową rolą tej siłowni (`Role.gymId = gymId`) albo globalną rolą systemową
* gymową (`Role.gymId IS NULL`, np. GYM_OWNER/GYM_TRAINER) — scoping customek
* egzekwowany jest przy przydzielaniu (`setUserGymRoles`), nie tutaj.
*/
export async function loadGymGrants(
prisma: PrismaClient,
userId: string,
gymId: string,
): Promise<GymGrantRow[]> {
return prisma.userRoleGrant.findMany({
where: { userId, gymId },
include: { role: { select: { key: true, permissions: true } } },
});
}
export async function resolveGymPermissions(
prisma: PrismaClient,
userId: string,
gymId: string,
): Promise<GymPermissionKey[]> {
return gymPermissionsFromGrants(await loadGymGrants(prisma, userId, gymId));
}
export function hasGymRoleKey(grants: readonly GymGrantRow[], key: string): boolean {
return gymRoleKeys(grants).includes(key);
}
/**
* Kompat DTO: array ról w kształcie starego `GymMembership.roles`.
* Legacy: OWNER bez MEMBER-a, reszta z MEMBER-em — odtwarzamy ten kształt:
* OWNER (±TRAINER), a gdy nie ma OWNER-a to (TRAINER?) + MEMBER.
*/
export function deriveMembershipRoles(roleKeys: readonly string[], isMember: boolean): GymRole[] {
if (!isMember && roleKeys.length === 0) return [];
const out: GymRole[] = [];
const owner = roleKeys.includes(ROLE_KEYS.GYM_OWNER);
if (owner) out.push('OWNER');
if (roleKeys.includes(ROLE_KEYS.GYM_TRAINER)) out.push('TRAINER');
if (!owner) out.push('MEMBER');
return out;
}
/** Właściciel siłowni (grant GYM_OWNER). Nadzór admina rozstrzyga caller przez `gyms:manage`. */
export async function isGymOwner(
prisma: PrismaClient,
userId: string,
gymId: string,
): Promise<boolean> {
const grants = await loadGymGrants(prisma, userId, gymId);
return hasGymRoleKey(grants, ROLE_KEYS.GYM_OWNER);
}
/**
* Strażnik uprawnienia gymowego; `adminOverride` = caller ma platformowe
* `gyms:manage` (nadzór). Brak członkostwa/uprawnienia → 403 jak dawniej
* `assertGymOwner`.
*/
export async function assertGymPermission(
prisma: PrismaClient,
userId: string,
gymId: string,
key: GymPermissionKey,
adminOverride = false,
): Promise<void> {
if (adminOverride) return;
const perms = await resolveGymPermissions(prisma, userId, gymId);
if (!canGym(perms, key)) throw forbidden('You do not manage this gym');
}
/**
* Czy użytkownik może wejść DO zasobu siłowni (nadzorca ma zawsze). Zwraca flagę,
* nie rzuca — dla endpointów read z różnymi progami widoczności.
*/
export async function canInGym(
prisma: PrismaClient,
userId: string,
gymId: string,
key: GymPermissionKey,
adminOverride = false,
): Promise<boolean> {
if (adminOverride) return true;
const perms = await resolveGymPermissions(prisma, userId, gymId);
return canGym(perms, key);
}
/** Weryfikacja, że rola nadaje się do przydzielenia gymowego (scoping + pinned `gym:delegate`). */
export function assertGymAssignableRole(role: {
id: string;
key: string;
gymId: string | null;
isSystem: boolean;
permissions: string[];
}): void {
if (!role.gymId) {
throw forbidden('Platform roles cannot be assigned to a gym');
}
if (role.key === ROLE_KEYS.GYM_OWNER) {
throw forbidden('Gym owner role can only be managed by platform admins');
}
}
/** Zestaw uprawnień dozwolony w roli custom danej siłowni: klucze gym bez `gym:delegate`. */
export function filterAssignableGymPermissions(values: readonly string[]): GymPermissionKey[] {
return knownGymPermissions(values).filter((k) => k !== GYM_PERMISSIONS.GYM_DELEGATE);
}
/** Nazwa roli do wyświetlenia (custom → `name`; systemowa → klucz). */
export function gymRoleLabel(role: { key: string; name?: string | null }): string {
return role.name || role.key;
}
/** Slug klucza roli custom: G<slugGymu>_<slugNazwy> — globalnie unikalny, czytelny w logach. */
export function gymRoleKeyFor(gymName: string, gymId: string, name: string): string {
const slug = (s: string) =>
s
.replace(/ł/g, 'l')
.replace(/Ł/g, 'L')
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toUpperCase()
.replace(/[^A-Z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.slice(0, 20) || 'X';
const base = `G_${slug(gymName)}_${gymId.slice(-4)}_${slug(name)}`;
return base.slice(0, 40);
}

View File

@@ -1,9 +1,10 @@
import type { PrismaClient } from '@prisma/client';
/**
* Katalog uprawnień platformy (faza 1 RBAC). Źródło prawdy dla kluczy —
* role w bazie przechowują wyłącznie klucze stąd; nieznany klucz jest
* inertny (filtrowany przez `knownPermissions`).
* Katalog uprawnień platformy (faza 1 RBAC) + katalog uprawnień gymowych (faza 2).
* Źródło prawdy dla kluczy — role w bazie przechowują wyłącznie klucze stąd;
* nieznany klucz jest inertny (filtrowany przez `knownPermissions`/`knownGymPermissions`).
* Rola platformowa (Role.gymId = null) nie może zawierać kluczy gym; rola gymowa — platformowych.
*/
export const PERMISSIONS = {
USERS_READ: 'users:read',
@@ -17,6 +18,37 @@ export const PERMISSIONS = {
LOGS_VIEW: 'logs:view',
} as const;
/**
* Katalog uprawnień gymowych (faza 2, granty z `gymId`). Każdy klucz rozstrzygany
* jest względem JEDNEJ siłowni. `gym:delegate` (zarządzanie grantami gymowymi)
* jest przypięty do roli GYM_OWNER i nigdy nie wchodzi do ról custom.
*/
export const GYM_PERMISSIONS = {
GYM_EDIT: 'gym:edit',
GYM_DELETE: 'gym:delete',
GYM_MEMBERS: 'gym:members',
GYM_DELEGATE: 'gym:delegate',
GYM_EQUIPMENT: 'gym:equipment',
GYM_GALLERY: 'gym:gallery',
GYM_ANNOUNCEMENTS: 'gym:announcements',
GYM_EXCEPTIONS: 'gym:exceptions',
GYM_STATS: 'gym:stats',
GYM_CONTACT: 'gym:contact',
TRAINER_CLIENTS: 'trainer:clients',
} as const;
export type GymPermissionKey = (typeof GYM_PERMISSIONS)[keyof typeof GYM_PERMISSIONS];
export const GYM_PERMISSION_KEYS = Object.values(GYM_PERMISSIONS) as GymPermissionKey[];
export function isGymPermissionKey(value: string): value is GymPermissionKey {
return (GYM_PERMISSION_KEYS as string[]).includes(value);
}
export function knownGymPermissions(values: readonly string[]): GymPermissionKey[] {
return values.filter(isGymPermissionKey);
}
export type PermissionKey = (typeof PERMISSIONS)[keyof typeof PERMISSIONS];
export const PERMISSION_KEYS = Object.values(PERMISSIONS) as PermissionKey[];
@@ -29,14 +61,14 @@ export function isPermissionKey(value: string): value is PermissionKey {
export function knownPermissions(values: readonly string[]): PermissionKey[] {
return values.filter(isPermissionKey);
}
/** Role seedowane w migracji + seedzie (ADMIN ⊇ MODERATOR przez pakiety kluczy). */
/** Role seedowane w migracjach + seedzie (ADMIN ⊇ MODERATOR przez pakiety kluczy). */
export const DEFAULT_ROLES: ReadonlyArray<{
key: string;
permissions: PermissionKey[];
permissions: string[];
isSystem: true;
scope: 'platform' | 'gym';
}> = [
{ key: 'ADMIN', permissions: [...PERMISSION_KEYS], isSystem: true },
{ key: 'ADMIN', permissions: [...PERMISSION_KEYS], isSystem: true, scope: 'platform' },
{
key: 'MODERATOR',
permissions: [
@@ -46,12 +78,27 @@ export const DEFAULT_ROLES: ReadonlyArray<{
PERMISSIONS.LOGS_VIEW,
],
isSystem: true,
scope: 'platform',
},
{
key: 'GYM_OWNER',
permissions: GYM_PERMISSION_KEYS.filter((k) => k !== GYM_PERMISSIONS.TRAINER_CLIENTS),
isSystem: true,
scope: 'gym',
},
{
key: 'GYM_TRAINER',
permissions: [GYM_PERMISSIONS.TRAINER_CLIENTS],
isSystem: true,
scope: 'gym',
},
];
export const ROLE_KEYS = {
ADMIN: 'ADMIN',
MODERATOR: 'MODERATOR',
GYM_OWNER: 'GYM_OWNER',
GYM_TRAINER: 'GYM_TRAINER',
} as const;
/** Include grantów platformowych (gymId IS NULL) — wspólny kształt dla zapytań. */

View File

@@ -76,14 +76,15 @@ export function callerHas(req: Request, key: PermissionKey): boolean {
return !!req.user?.platformPermissions.includes(key);
}
/** The user must hold the TRAINER role in at least one gym. */
/** The user must hold the gym trainer role (grant GYM_TRAINER) in at least one gym. */
export function requireTrainer(prisma: PrismaClient) {
return async (req: Request, _res: Response, next: NextFunction) => {
try {
const membership = await prisma.gymMembership.findFirst({
where: { userId: req.user!.id, roles: { has: 'TRAINER' } },
const grant = await prisma.userRoleGrant.findFirst({
where: { userId: req.user!.id, gymId: { not: null }, role: { key: 'GYM_TRAINER' } },
select: { id: true },
});
if (!membership) return next(forbidden('Trainer role required'));
if (!grant) return next(forbidden('Trainer role required'));
next();
} catch (e) {
next(e);

View File

@@ -75,11 +75,16 @@ import { asyncHandler } from '../lib/asyncHandler.js';
import { PERMISSIONS, PERMISSION_KEYS } from '../lib/permissions.js';
import {
assertNotStaffTarget,
createGymRole,
createRole,
deleteGymRole,
deleteRole,
getUserPlatformRoles,
listGymRoles,
listRoles,
setUserGymRoles,
setUserPlatformRoles,
updateGymRole,
updateRole,
} from '../services/roles.js';
@@ -1519,6 +1524,157 @@ export function createAdminRoutes({ prisma }: AppDeps) {
}),
);
const gymRoleSchema = z.object({
name: z.string().min(1).max(60),
permissions: z.array(z.string().min(1)).min(1).max(20),
});
/**
* @openapi
* /admin/gyms/{gymId}/roles:
* get:
* summary: Role catalog for one gym (gyms:manage) — system gym roles + custom roles of that gym.
* tags: [Admin]
* responses:
* 200: { description: OK, returns { roles: [{ id, key, name, permissions, isSystem, grantCount }] } }
*/
router.get(
'/gyms/:gymId/roles',
can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
const result = await listGymRoles(prisma, req.params.gymId);
res.json(result);
}),
);
/**
* @openapi
* /admin/gyms/{gymId}/roles:
* post:
* summary: Create a custom role for one gym (gyms:manage). Klucz generowany serwerowo;
* klucze spoza katalogu gym i `gym:delegate` odrzucane.
* tags: [Admin]
* responses:
* 201: { description: Created }
* 400: { description: Invalid name/permissions }
* 404: { description: Gym not found }
*/
router.post(
'/gyms/:gymId/roles',
can(PERMISSIONS.GYMS_MANAGE),
validate(gymRoleSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer<typeof gymRoleSchema>;
const result = await createGymRole(prisma, req.params.gymId, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'role.created',
entityType: 'role',
entityId: result.role.id,
details: {
key: result.role.key,
gymId: req.params.gymId,
permissions: result.role.permissions,
},
});
res.status(201).json(result);
}),
);
/**
* @openapi
* /admin/gyms/{gymId}/roles/{roleId}:
* patch:
* summary: Edit a custom gym role (gyms:manage). System roles: read-only.
* tags: [Admin]
* responses:
* 200: { description: OK }
* 400: { description: Invalid name/permissions }
* 403: { description: System role }
* 404: { description: Role not found in this gym }
*/
router.patch(
'/gyms/:gymId/roles/:roleId',
can(PERMISSIONS.GYMS_MANAGE),
validate(gymRoleSchema.partial()),
asyncHandler(async (req, res) => {
const data = req.body as Partial<z.infer<typeof gymRoleSchema>>;
const result = await updateGymRole(prisma, req.params.gymId, req.params.roleId, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'role.updated',
entityType: 'role',
entityId: req.params.roleId,
details: { key: result.role.key, gymId: req.params.gymId },
});
res.json(result);
}),
);
/**
* @openapi
* /admin/gyms/{gymId}/roles/{roleId}:
* delete:
* summary: Delete a custom gym role (gyms:manage). System roles nieusuwalne; rola z grantami → 409.
* tags: [Admin]
* responses:
* 204: { description: Deleted }
* 403: { description: Cannot delete a system role }
* 404: { description: Role not found in this gym }
* 409: { description: Role is still assigned to users }
*/
router.delete(
'/gyms/:gymId/roles/:roleId',
can(PERMISSIONS.GYMS_MANAGE),
asyncHandler(async (req, res) => {
const result = await deleteGymRole(prisma, req.params.gymId, req.params.roleId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'role.deleted',
entityType: 'role',
entityId: req.params.roleId,
details: { key: result.role.key, gymId: req.params.gymId },
});
res.status(204).end();
}),
);
const memberGymRolesSchema = z.object({ roleKeys: z.array(z.string().min(1)).max(10) });
/**
* @openapi
* /admin/gyms/{gymId}/members/{userId}/roles:
* put:
* summary: Replace the gym role grants of a member (gyms:manage). GYM_OWNER tylko z panelu admina;
* zmiana podbija tokenVersion.
* tags: [Admin]
* responses:
* 200: { description: OK, returns { roles: string[] } }
* 400: { description: Unknown role key }
* 403: { description: Platform role assigned to a gym / owner change by non-admin }
* 404: { description: Gym, member or membership not found }
*/
router.put(
'/gyms/:gymId/members/:userId/roles',
can(PERMISSIONS.GYMS_MANAGE),
validate(memberGymRolesSchema),
asyncHandler(async (req, res) => {
const { roleKeys } = req.body as z.infer<typeof memberGymRolesSchema>;
const result = await setUserGymRoles(prisma, req.params.gymId, req.params.userId, roleKeys, {
id: req.user!.id,
permissions: req.user!.platformPermissions,
});
await logActivity(prisma, {
actorId: req.user!.id,
action: 'user.gymRoles.changed',
entityType: 'user',
entityId: req.params.userId,
details: { gymId: req.params.gymId, roles: roleKeys },
});
res.json(result);
}),
);
const focusAreaSchema = z
.object({
name: z.string().min(1).max(100),

View File

@@ -13,7 +13,7 @@ import {
import { badRequest, forbidden, notFound } from '../../lib/errors.js';
import { asyncHandler } from '../../lib/asyncHandler.js';
import { callerHas } from '../../middleware/auth.js';
import { PERMISSIONS } from '../../lib/permissions.js';
import { GYM_PERMISSIONS, PERMISSIONS } from '../../lib/permissions.js';
type Params = { gymId: string; equipmentInstanceId: string };
@@ -142,7 +142,13 @@ export function createEquipmentPhotoRoutes({ prisma }: AppDeps) {
if (!gym) throw notFound('Gym not found');
if (
gym.kind !== 'REAL' &&
!(await canManageGym(prisma, gymId, req.user!.id, callerHas(req, PERMISSIONS.GYMS_MANAGE)))
!(await canManageGym(
prisma,
gymId,
req.user!.id,
callerHas(req, PERMISSIONS.GYMS_MANAGE),
GYM_PERMISSIONS.GYM_EQUIPMENT,
))
)
throw forbidden('You do not have access to this gym');
const filePath = path.join(equipmentPhotoDir(gymId, equipmentInstanceId), photo.storedName);

View File

@@ -43,6 +43,7 @@ import { asyncHandler } from '../lib/asyncHandler.js';
const invitationSchema = z.object({
userId: z.string().min(1),
gymId: z.string().min(1).optional(),
});
const commentSchema = z.object({
@@ -89,11 +90,12 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/invitations:
* post:
* summary: Send a coaching invitation (at least one party must be a trainer)
* summary: Send a coaching invitation (at least one party must be a trainer). Optional gymId;
* bez niego wymagany dokładnie jeden wspólny gym, w którym trainer ma rolę GYM_TRAINER.
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Self-invite or no trainer role }
* 400: { description: Self-invite, no trainer role, or ambiguous/missing shared gym }
* 404: { description: User not found }
* 409: { description: Invitation exists or pending limit reached }
*/
@@ -101,8 +103,8 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
'/invitations',
validate(invitationSchema),
asyncHandler(async (req, res) => {
const { userId } = req.body as z.infer<typeof invitationSchema>;
const result = await sendInvitation(prisma, req.user!.id, userId);
const { userId, gymId } = req.body as z.infer<typeof invitationSchema>;
const result = await sendInvitation(prisma, req.user!.id, userId, gymId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.invited',

View File

@@ -1,8 +1,10 @@
import bcrypt from 'bcryptjs';
import { Prisma, type GymRole, type PrismaClient } from '@prisma/client';
import { Prisma, type PrismaClient } from '@prisma/client';
import { validateEquipmentSpec } from '../lib/equipmentSpec.js';
import { isPrismaNotFound } from '../lib/prisma.js';
import { publicUser } from '../lib/publicUser.js';
import { ROLE_KEYS } from '../lib/permissions.js';
import { deriveMembershipRoles } from '../lib/gymPermissions.js';
import {
PLATFORM_GRANTS_INCLUDE,
PERMISSIONS,
@@ -11,7 +13,7 @@ import {
redactUserRef,
} from '../lib/permissions.js';
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { assertNotStaffTarget, assertTargetNotLastRolesManager } from './roles.js';
import { assertNotStaffTarget, assertTargetNotLastRolesManager, grantGymOwner } from './roles.js';
import {
removeEquipmentPhotoFiles,
removeGymClaimFiles,
@@ -104,6 +106,30 @@ export async function listGyms(
permissions: readonly string[] = [],
) {
const term = query.q?.trim();
const ownerUserSelect = { id: true, firstName: true, lastName: true, email: true } as const;
const ownerWhere: Prisma.UserWhereInput = {
OR: [
{ firstName: { contains: term ?? '', mode: 'insensitive' } },
{ lastName: { contains: term ?? '', mode: 'insensitive' } },
{ email: { contains: term ?? '', mode: 'insensitive' } },
],
};
// Właściciele z grantów (kolumna `roles` martwa): najpierw gymy pasujące
// przez nazwisko/e-mail właściciela, potem wyciągamy właścicieli hurtowo.
const ownerGymIdsWhere = term
? (
await prisma.userRoleGrant.findMany({
where: {
gymId: { not: null },
role: { key: ROLE_KEYS.GYM_OWNER },
user: ownerWhere,
},
select: { gymId: true },
})
)
.map((g) => g.gymId)
.filter((id): id is string => !!id)
: [];
const where: Prisma.GymWhereInput = {
...(query.kind ? { kind: query.kind } : {}),
...(term
@@ -114,20 +140,7 @@ export async function listGyms(
{ city: { contains: term, mode: 'insensitive' } },
{ addressLine1: { contains: term, mode: 'insensitive' } },
{ postalCode: { contains: term, mode: 'insensitive' } },
{
memberships: {
some: {
roles: { has: 'OWNER' },
user: {
OR: [
{ firstName: { contains: term, mode: 'insensitive' } },
{ lastName: { contains: term, mode: 'insensitive' } },
{ email: { contains: term, mode: 'insensitive' } },
],
},
},
},
},
{ id: { in: ownerGymIdsWhere } },
],
}
: {}),
@@ -135,22 +148,28 @@ export async function listGyms(
const gyms = await prisma.gym.findMany({
where,
orderBy: { name: 'asc' },
include: {
_count: { select: { memberships: true } },
memberships: {
where: { roles: { has: 'OWNER' } },
include: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
orderBy: { user: { createdAt: 'asc' } },
},
},
include: { _count: { select: { memberships: true } } },
});
const ownerRows = await prisma.userRoleGrant.findMany({
where: { gymId: { in: gyms.map((g) => g.id) }, role: { key: ROLE_KEYS.GYM_OWNER } },
include: { user: { select: { ...ownerUserSelect, createdAt: true } } },
orderBy: { user: { createdAt: 'asc' } },
});
const ownersByGym = new Map<
string,
Array<{ id: string; firstName: string | null; lastName: string | null; email: string }>
>();
for (const g of ownerRows) {
if (!g.gymId) continue;
const { createdAt: _createdAt, ...owner } = g.user;
const list = ownersByGym.get(g.gymId);
if (list) list.push(owner);
else ownersByGym.set(g.gymId, [owner]);
}
return {
gyms: gyms.map(({ memberships, ...g }) => ({
gyms: gyms.map((g) => ({
...g,
owners: redactUserDtos(
memberships.map((m) => m.user),
permissions,
),
owners: redactUserDtos(ownersByGym.get(g.id) ?? [], permissions),
})),
};
}
@@ -169,59 +188,58 @@ export async function getGym(
},
photos: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] },
_count: { select: { memberships: true } },
memberships: {
where: { roles: { has: 'OWNER' } },
include: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
orderBy: { user: { createdAt: 'asc' } },
},
},
});
if (!gym) throw Object.assign(new Error('Nie znaleziono siłowni'), { status: 404 });
const { memberships, equipment, ...rest } = gym;
const { equipment, ...rest } = gym;
const ownerRows = await prisma.userRoleGrant.findMany({
where: { gymId, role: { key: ROLE_KEYS.GYM_OWNER } },
include: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
orderBy: { user: { createdAt: 'asc' } },
});
return {
...rest,
equipment: mapEquipmentPhotoDtos(gymId, equipment),
owners: redactUserDtos(
memberships.map((m) => m.user),
ownerRows.map((g) => g.user),
permissions,
),
};
}
/** Nadaje użytkownikowi rolę OWNER (admin): tworzy członkostwo albo dopisuje rolę. */
/** Nadaje użytkownikowi rolę GYM_OWNER (admin): gwarantuje członkostwo + grant. */
export async function addGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
await ensureUser(prisma, userId);
await grantGymOwner(prisma, gymId, userId);
await prisma.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
if (membership) {
if (membership.roles.includes('OWNER')) return { membership };
const updated = await prisma.gymMembership.update({
where: { id: membership.id },
data: { roles: ['OWNER', ...membership.roles] },
});
return { membership: updated };
}
const created = await prisma.gymMembership.create({
data: { userId, gymId, roles: ['OWNER'] },
});
return { membership: created };
return { membership: { ...membership, roles: ['OWNER'] } };
}
/** Zdejmuje rolę OWNER (admin); usuwa członkostwo, gdy nie zostanie żadna rola. */
/** Zdejmuje rolę GYM_OWNER (admin); jak legacy — członkostwo pada, gdy nie ma już żadnej roli w tym gymie. */
export async function removeGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
const role = await prisma.role.findUnique({
where: { key: ROLE_KEYS.GYM_OWNER },
select: { id: true },
});
if (!role) throw notFound('Gym owner not found');
const grant = await prisma.userRoleGrant.findFirst({
where: { userId, gymId, roleId: role.id },
select: { id: true },
});
if (!grant) throw notFound('Gym owner not found');
await prisma.$transaction(async (tx) => {
await tx.userRoleGrant.delete({ where: { id: grant.id } });
const left = await tx.userRoleGrant.count({ where: { userId, gymId } });
if (left === 0) {
await tx.gymMembership.deleteMany({ where: { userId, gymId } });
}
await tx.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
});
if (!membership || !membership.roles.includes('OWNER')) throw notFound('Gym owner not found');
const roles = membership.roles.filter((r) => r !== 'OWNER');
if (roles.length === 0) {
await prisma.gymMembership.delete({ where: { id: membership.id } });
} else {
await prisma.gymMembership.update({ where: { id: membership.id }, data: { roles } });
}
}
export interface GymMembersQuery {
@@ -241,9 +259,15 @@ export async function listGymMembers(
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
const term = query.q?.trim();
const roleKey =
query.role === 'OWNER'
? ROLE_KEYS.GYM_OWNER
: query.role === 'TRAINER'
? ROLE_KEYS.GYM_TRAINER
: null;
const where: Prisma.GymMembershipWhereInput = {
gymId,
...(query.role ? { roles: { has: query.role } } : {}),
...(roleKey ? { user: { roleGrants: { some: { gymId, role: { key: roleKey } } } } } : {}),
...(term
? {
user: {
@@ -256,7 +280,7 @@ export async function listGymMembers(
}
: {}),
};
const [total, memberships, active] = await Promise.all([
const [total, memberships, active, gymGrants] = await Promise.all([
prisma.gymMembership.count({ where }),
prisma.gymMembership.findMany({
where,
@@ -265,11 +289,22 @@ export async function listGymMembers(
},
}),
prisma.gymPresence.findMany({ where: { gymId, status: 'ACTIVE' }, select: { userId: true } }),
prisma.userRoleGrant.findMany({
where: { gymId },
include: { role: { select: { key: true } } },
}),
]);
const keysByUser = new Map<string, string[]>();
for (const g of gymGrants) {
const list = keysByUser.get(g.userId);
if (list) list.push(g.role.key);
else keysByUser.set(g.userId, [g.role.key]);
}
const live = new Set(active.map((p) => p.userId));
const sorted = memberships.sort(
(a, b) =>
Number(b.roles.includes('OWNER')) - Number(a.roles.includes('OWNER')) ||
Number((keysByUser.get(b.userId) ?? []).includes(ROLE_KEYS.GYM_OWNER)) -
Number((keysByUser.get(a.userId) ?? []).includes(ROLE_KEYS.GYM_OWNER)) ||
a.createdAt.getTime() - b.createdAt.getTime(),
);
const limit = query.limit ?? 50;
@@ -277,7 +312,7 @@ export async function listGymMembers(
return {
members: sorted.slice(offset, offset + limit).map((m) => ({
membershipId: m.id,
roles: m.roles,
roles: deriveMembershipRoles(keysByUser.get(m.userId) ?? [], true),
joinedAt: m.createdAt.toISOString(),
checkedInNow: live.has(m.userId),
user: redactUserRef(m.user, permissions),
@@ -346,8 +381,9 @@ export async function createGym(prisma: PrismaClient, data: CreateGymInput) {
},
});
await tx.gymMembership.create({
data: { userId: ownerId, gymId: created.id, roles: ['OWNER'] },
data: { userId: ownerId, gymId: created.id },
});
await grantGymOwner(tx, created.id, ownerId);
return created;
});
return { gym };
@@ -510,22 +546,35 @@ export async function listUsers(
viewerPermissions: readonly string[] = [],
) {
const term = search?.toLowerCase();
const hasPii = viewerPermissions.includes(PERMISSIONS.PII_READ);
const textFilters: Prisma.UserWhereInput[] = [
{ firstName: { contains: term ?? '', mode: 'insensitive' } },
{ lastName: { contains: term ?? '', mode: 'insensitive' } },
];
// Bez `pii:read` e-mail jest maskowany w odpowiedzi — szukanie po nim
// pozwalałoby zgadywać adresy obcych kont (odcinamy).
if (hasPii) textFilters.push({ email: { contains: term ?? '', mode: 'insensitive' as const } });
const users = await prisma.user.findMany({
where: term
? {
OR: [
{ email: { contains: term, mode: 'insensitive' } },
{ firstName: { contains: term, mode: 'insensitive' } },
{ lastName: { contains: term, mode: 'insensitive' } },
],
}
: undefined,
where: term ? { OR: textFilters } : undefined,
include: {
memberships: { include: { gym: true } },
roleGrants: PLATFORM_GRANTS_INCLUDE,
},
orderBy: { createdAt: 'desc' },
});
const keysByPair = new Map<string, string[]>();
if (users.length > 0) {
const grants = await prisma.userRoleGrant.findMany({
where: { userId: { in: users.map((u) => u.id) }, gymId: { not: null } },
select: { userId: true, gymId: true, role: { select: { key: true } } },
});
for (const g of grants) {
const k = `${g.userId}|${g.gymId}`;
const list = keysByPair.get(k);
if (list) list.push(g.role.key);
else keysByPair.set(k, [g.role.key]);
}
}
return {
users: users.map((u) =>
redactUserDto(
@@ -533,7 +582,7 @@ export async function listUsers(
...publicUser(u),
memberships: u.memberships.map((m) => ({
gymId: m.gymId,
roles: m.roles,
roles: deriveMembershipRoles(keysByPair.get(`${u.id}|${m.gymId}`) ?? [], true),
gym: m.gym,
})),
},
@@ -669,6 +718,48 @@ export async function deleteUser(
return { email: target.email };
}
/**
* Wymiana systemowych ról gymowych (OWNER/TRAINER) na granty; custom role
* ( Role.gymId = gymId) zostają nietknięte. Zwraca true, jeśli coś się zmieniło.
*/
async function syncSystemGymRoles(
tx: Prisma.TransactionClient,
gymId: string,
userId: string,
roles: MembershipRole[],
): Promise<boolean> {
const keys = [ROLE_KEYS.GYM_OWNER, ROLE_KEYS.GYM_TRAINER];
const roleRows = await tx.role.findMany({
where: { key: { in: keys } },
select: { id: true, key: true },
});
const byKey = new Map(roleRows.map((r) => [r.key, r.id]));
const wanted = new Set<string>();
if (roles.includes('OWNER')) wanted.add(ROLE_KEYS.GYM_OWNER);
if (roles.includes('TRAINER')) wanted.add(ROLE_KEYS.GYM_TRAINER);
const current = await tx.userRoleGrant.findMany({
where: { userId, gymId, role: { key: { in: keys } } },
include: { role: { select: { key: true } } },
});
const currentKeys = new Set(current.map((g) => g.role.key));
let changed = false;
for (const g of current) {
if (!wanted.has(g.role.key)) {
await tx.userRoleGrant.delete({ where: { id: g.id } });
changed = true;
}
}
for (const key of wanted) {
if (!currentKeys.has(key)) {
const roleId = byKey.get(key);
if (!roleId) throw new AppError(500, 'ROLE_SEED_MISSING', `System role ${key} missing`);
await tx.userRoleGrant.create({ data: { userId, roleId, gymId } });
changed = true;
}
}
return changed;
}
export async function addMembership(
prisma: PrismaClient,
userId: string,
@@ -683,10 +774,20 @@ export async function addMembership(
where: { userId_gymId: { userId: user.id, gymId } },
});
if (existing) throw conflict('Membership already exists');
const membership = await prisma.gymMembership.create({
data: { userId: user.id, gymId, roles },
const membership = await prisma.$transaction(async (tx) => {
const created = await tx.gymMembership.create({
data: { userId: user.id, gymId },
});
const changed = await syncSystemGymRoles(tx, gymId, user.id, roles);
if (changed) {
await tx.user.update({
where: { id: user.id },
data: { tokenVersion: { increment: 1 } },
});
}
return created;
});
return { membership };
return { membership: { ...membership, roles } };
}
export async function updateMembership(
@@ -699,19 +800,31 @@ export async function updateMembership(
where: { userId_gymId: { userId, gymId } },
});
if (!membership) throw notFound('Membership not found');
const updated = await prisma.gymMembership.update({
where: { userId_gymId: { userId, gymId } },
data: { roles },
const updated = await prisma.$transaction(async (tx) => {
const changed = await syncSystemGymRoles(tx, gymId, userId, roles);
if (changed) {
await tx.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
}
return tx.gymMembership.findUniqueOrThrow({ where: { id: membership.id } });
});
return { membership: updated };
return { membership: { ...updated, roles } };
}
export async function removeMembership(prisma: PrismaClient, userId: string, gymId: string) {
try {
const removed = await prisma.gymMembership.delete({
where: { userId_gymId: { userId, gymId } },
return await prisma.$transaction(async (tx) => {
const grants = await tx.userRoleGrant.findMany({
where: { userId, gymId },
select: { role: { select: { key: true } } },
});
const removed = await tx.gymMembership.delete({
where: { userId_gymId: { userId, gymId } },
});
// granty gymowe bez członkostwa są bezużyteczne — sprzątamy je razem z wierszem
await tx.userRoleGrant.deleteMany({ where: { userId, gymId } });
const keys = grants.map((g) => g.role.key);
return { membership: { ...removed, roles: deriveMembershipRoles(keys, true) } };
});
return { membership: removed };
} catch (e) {
if (isPrismaNotFound(e)) throw badRequest('Membership not found');
throw e;
@@ -862,27 +975,24 @@ export async function approveGymClaim(prisma: PrismaClient, adminId: string, cla
});
const membership = await tx.gymMembership.findUnique({
where: { userId_gymId: { userId: claim.userId, gymId: gym.id } },
select: { id: true },
});
if (membership) {
const roles: GymRole[] = membership.roles.includes('OWNER')
? membership.roles
: ['OWNER', ...membership.roles];
await tx.gymMembership.update({ where: { id: membership.id }, data: { roles } });
} else {
await tx.gymMembership.create({
data: { userId: claim.userId, gymId: gym.id, roles: ['OWNER'] },
});
}
const otherOwners = await tx.gymMembership.findMany({
where: { gymId: gym.id, userId: { not: claim.userId }, roles: { has: 'OWNER' } },
});
for (const m of otherOwners) {
const roles = m.roles.filter((r) => r !== 'OWNER');
await tx.gymMembership.update({
where: { id: m.id },
data: { roles: roles.length > 0 ? roles : ['MEMBER'] },
if (!membership) {
await tx.gymMembership.create({ data: { userId: claim.userId, gymId: gym.id } });
}
await grantGymOwner(tx, gym.id, claim.userId);
// pozostali właściciele tracą grant GYM_OWNER (członkostwa zostają)
const ownerRole = await tx.role.findUnique({
where: { key: ROLE_KEYS.GYM_OWNER },
select: { id: true },
});
if (ownerRole) {
await tx.userRoleGrant.deleteMany({
where: { gymId: gym.id, userId: { not: claim.userId }, roleId: ownerRole.id },
});
}
// po approve zatwierdzający jest już właścicielem; uprawnienia czytanymi z DB per request —
// bez bumpa tokenVersion (semantyka legacy: nie wygaszamy sesji applicantowi)
await tx.gymClaim.updateMany({
where: { gymId: gym.id, status: 'PENDING', id: { not: claim.id } },
data: {
@@ -904,8 +1014,9 @@ export async function approveGymClaim(prisma: PrismaClient, adminId: string, cla
},
});
await tx.gymMembership.create({
data: { userId: claim.userId, gymId: gym.id, roles: ['OWNER'] },
data: { userId: claim.userId, gymId: gym.id },
});
await grantGymOwner(tx, gym.id, claim.userId);
await tx.gymClaim.update({ where: { id: claim.id }, data: { gymId: gym.id } });
}

View File

@@ -1,5 +1,7 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, forbidden, notFound } from '../lib/errors.js';
import { GYM_PERMISSIONS } from '../lib/permissions.js';
import { canGym, resolveGymPermissions } from '../lib/gymPermissions.js';
import { authorInfos } from './feed.js';
import type { DayAvailability } from './me.js';
@@ -8,35 +10,28 @@ export interface AnnouncementInput {
body: string;
}
/**
* Lokalny zamiast importu `assertGymOwner` z `gyms/core.js` — ten moduł jest
* importowany przez core (ogłoszenia automatyczne), więc import zwrotny
* stworzyłby cykl.
*/
async function assertGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { memberships: { where: { userId } } },
});
/** Zarządzanie ogłoszeniami = uprawnienie gymowe `gym:announcements` (faza 2). */
async function assertGymAnnounce(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
if (!gym.memberships.some((m) => m.roles.includes('OWNER')))
const perms = await resolveGymPermissions(prisma, userId, gymId);
if (!canGym(perms, GYM_PERMISSIONS.GYM_ANNOUNCEMENTS))
throw forbidden('Only the gym owner can manage this gym');
}
/** Wymaga członkostwa w siłowni (dowolna rola); `canManage` = OWNER. */
/** Wymaga członkostwa w siłowni (dowolna rola); `canManage` = `gym:announcements`. */
export async function listGymAnnouncements(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { memberships: { where: { userId } } },
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
if (!gym) throw notFound('Gym not found');
const membership = gym.memberships[0];
if (!membership) throw notFound('Gym not found');
const announcements = await prisma.announcement.findMany({
where: { gymId },
orderBy: { createdAt: 'desc' },
});
const infos = await authorInfos(prisma, announcements);
const perms = await resolveGymPermissions(prisma, userId, gymId);
return {
announcements: announcements.map((a) => ({
...a,
@@ -44,7 +39,7 @@ export async function listGymAnnouncements(prisma: PrismaClient, gymId: string,
? infos.get(a.authorId)
: { authorId: null, authorName: null, authorRole: null }),
})),
canManage: membership.roles.includes('OWNER'),
canManage: canGym(perms, GYM_PERMISSIONS.GYM_ANNOUNCEMENTS),
};
}
@@ -55,7 +50,7 @@ export async function createGymAnnouncement(
userId: string,
data: AnnouncementInput,
) {
await assertGymOwner(prisma, gymId, userId);
await assertGymAnnounce(prisma, gymId, userId);
const announcement = await prisma.announcement.create({
data: { gymId, authorId: userId, kind: 'MANUAL', title: data.title, body: data.body },
});
@@ -70,7 +65,7 @@ export async function updateGymAnnouncement(
announcementId: string,
data: AnnouncementInput,
) {
await assertGymOwner(prisma, gymId, userId);
await assertGymAnnounce(prisma, gymId, userId);
const announcement = await prisma.announcement.findUnique({ where: { id: announcementId } });
if (!announcement || announcement.gymId !== gymId) throw notFound('Announcement not found');
if (announcement.kind !== 'MANUAL') throw badRequest('System announcements cannot be edited');
@@ -88,7 +83,7 @@ export async function deleteGymAnnouncement(
userId: string,
announcementId: string,
) {
await assertGymOwner(prisma, gymId, userId);
await assertGymAnnounce(prisma, gymId, userId);
const announcement = await prisma.announcement.findUnique({ where: { id: announcementId } });
if (!announcement || announcement.gymId !== gymId) throw notFound('Announcement not found');
if (announcement.kind !== 'MANUAL') throw badRequest('System announcements cannot be deleted');

View File

@@ -1,6 +1,7 @@
import type { NotificationType, Prisma, PrismaClient } from '@prisma/client';
import { notFound } from '../lib/errors.js';
import { ROLE_KEYS } from '../lib/permissions.js';
import { gymRoleKeys, loadGymGrants } from '../lib/gymPermissions.js';
/** Grant roli ADMIN (platformowy) — do przypisywania atrybutu „ADMIN" autorom ogłoszeń. */
const ADMIN_GRANT_SELECT = {
@@ -98,6 +99,12 @@ type AnnouncementAuthorSelect = {
roleGrants: { id: string }[];
};
/** Rola „od kogo" z kluczy grantów gym (kolumna `GymMembership.roles` martwa). */
function authorRoleFromKeys(keys: readonly string[]): AnnouncementAuthorRole {
if (keys.includes(ROLE_KEYS.GYM_TRAINER)) return 'TRAINER';
return 'OWNER';
}
/**
* Pola „od kogo" dla listy ogłoszeń: zbiorcze membershipy autorów w siłowni
* (bez N+1 per wiersz) + fallback OWNER dla ręcznych ogłoszeń po utracie
@@ -110,18 +117,26 @@ export async function authorInfos(
const authorIds = [
...new Set(announcements.map((a) => a.authorId).filter((v): v is string => !!v)),
];
const memberships =
const grants =
authorIds.length === 0
? []
: await prisma.gymMembership.findMany({
: await prisma.userRoleGrant.findMany({
where: {
userId: { in: authorIds },
gymId: {
in: [...new Set(announcements.map((a) => a.gymId).filter((v): v is string => !!v))],
},
},
select: { userId: true, gymId: true, roles: true },
select: { userId: true, gymId: true, role: { select: { key: true } } },
});
const keysByPair = new Map<string, string[]>();
for (const g of grants) {
if (!g.gymId) continue;
const k = `${g.userId}|${g.gymId}`;
const list = keysByPair.get(k);
if (list) list.push(g.role.key);
else keysByPair.set(k, [g.role.key]);
}
const authors =
authorIds.length === 0
? []
@@ -135,15 +150,11 @@ export async function authorInfos(
if (!a.authorId) continue;
const author = byAuthor.get(a.authorId);
if (!author) continue;
const membership = memberships.find((m) => m.userId === a.authorId && m.gymId === a.gymId);
const keys = a.gymId ? keysByPair.get(`${a.authorId}|${a.gymId}`) : undefined;
const role: AnnouncementAuthorRole | null = author.roleGrants.length
? 'ADMIN'
: membership
? membership.roles.includes('OWNER')
? 'OWNER'
: membership.roles.includes('TRAINER')
? 'TRAINER'
: 'OWNER'
: keys
? authorRoleFromKeys(keys)
: a.kind === 'MANUAL'
? 'OWNER'
: null;
@@ -156,7 +167,7 @@ export async function authorInfos(
return result;
}
/** Pola „od kogo" dla pojedynczego ogłoszenia (jeden membership). */
/** Pola „od kogo" dla pojedynczego ogłoszenia (jeden zestaw grantów). */
async function authorInfo(
prisma: PrismaClient,
author: AnnouncementAuthorSelect | null,
@@ -164,20 +175,11 @@ async function authorInfo(
kind: string,
): Promise<AnnouncementAuthorInfo> {
if (!author) return { authorId: null, authorName: null, authorRole: null };
const membership = gymId
? await prisma.gymMembership.findFirst({
where: { userId: author.id, gymId },
select: { roles: true },
})
: null;
const grants = gymId ? await loadGymGrants(prisma, author.id, gymId) : [];
const role: AnnouncementAuthorRole | null = author.roleGrants.length
? 'ADMIN'
: membership
? membership.roles.includes('OWNER')
? 'OWNER'
: membership.roles.includes('TRAINER')
? 'TRAINER'
: 'OWNER'
: grants.length
? authorRoleFromKeys(gymRoleKeys(grants))
: kind === 'MANUAL'
? 'OWNER'
: null;

View File

@@ -1,10 +1,13 @@
import type { PrismaClient } from '@prisma/client';
import { forbidden, notFound } from '../../lib/errors.js';
import { GYM_PERMISSIONS, type GymPermissionKey } from '../../lib/permissions.js';
import { canGym, resolveGymPermissions } from '../../lib/gymPermissions.js';
/**
* Kontakt członek ↔ właściciele siłowni. Wątek wspólny na parę (gymId, userId):
* wszyscy aktualni OWNER gyma widzą wątek i odpowiadają (dostęp dynamiczny —
* rola/członkostwo sprawdzane przy każdym odczycie i zapisie), admin ponadto.
* Kontakt członek ↔ obsługa siłowni. Wątek wspólny na parę (gymId, userId):
* wszyscy z uprawnieniem `gym:contact` (dawniej: rola OWNER) widzą wątek i
* odpowiadają (dostęp dynamiczny — członkostwo/uprawnienie sprawdzane przy
* każdym odczycie i zapisie), admin ponadto.
* Nieuczestnik zobaczy 404 (spójnie z wątkiem coachingu).
*/
@@ -16,12 +19,18 @@ function displayName(u: { firstName: string | null; lastName: string | null; ema
return [u.firstName, u.lastName].filter(Boolean).join(' ') || u.email;
}
async function membershipRoles(prisma: PrismaClient, userId: string, gymId: string) {
/** Uprawnienia gymowe członka; null = brak członkostwa. */
async function memberPerms(
prisma: PrismaClient,
userId: string,
gymId: string,
): Promise<GymPermissionKey[] | null> {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { roles: true },
select: { id: true },
});
return membership?.roles ?? [];
if (!membership) return null;
return resolveGymPermissions(prisma, userId, gymId);
}
/** Uczestnicy: conversation.userId (aktywne członkostwo) + aktualni OWNER gyma + admin. */
@@ -32,12 +41,12 @@ async function threadAccess(
conversation: { gymId: string; userId: string },
): Promise<GymThreadRole> {
if (isAdmin) return 'admin';
const roles = await membershipRoles(prisma, userId, conversation.gymId);
const perms = await memberPerms(prisma, userId, conversation.gymId);
if (conversation.userId === userId) {
if (roles.length === 0) throw forbidden('You are no longer a member of this gym');
if (perms === null) throw forbidden('You are no longer a member of this gym');
return 'member';
}
if (roles.includes('OWNER')) return 'owner';
if (perms && canGym(perms, GYM_PERMISSIONS.GYM_CONTACT)) return 'owner';
throw notFound('Conversation not found');
}
@@ -169,9 +178,9 @@ export async function getGymContactView(
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
const roles = await membershipRoles(prisma, userId, gymId);
if (!isAdmin && !roles.includes('OWNER')) {
if (roles.length === 0) throw forbidden('Only gym members can contact the owners');
const perms = await memberPerms(prisma, userId, gymId);
if (!isAdmin && !(perms && canGym(perms, GYM_PERMISSIONS.GYM_CONTACT))) {
if (perms === null) throw forbidden('Only gym members can contact the owners');
// widok członka: jego własny wątek (lazily)
const conversation = await prisma.gymConversation.findUnique({
where: { gymId_userId: { gymId, userId } },
@@ -242,8 +251,8 @@ export async function startOrReply(
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
const roles = await membershipRoles(prisma, userId, gymId);
if (roles.length === 0) throw forbidden('Only gym members can contact the owners');
const perms = await memberPerms(prisma, userId, gymId);
if (perms === null) throw forbidden('Only gym members can contact the owners');
const now = new Date();
const conversation = await prisma.gymConversation.upsert({
where: { gymId_userId: { gymId, userId } },
@@ -298,11 +307,17 @@ export async function listOwnerInbox(prisma: PrismaClient, userId: string, isAdm
: {
gymId: {
in: (
await prisma.gymMembership.findMany({
where: { userId, roles: { has: 'OWNER' } },
await prisma.userRoleGrant.findMany({
where: {
userId,
gymId: { not: null },
role: { permissions: { has: GYM_PERMISSIONS.GYM_CONTACT } },
},
select: { gymId: true },
})
).map((m) => m.gymId),
)
.map((g) => g.gymId)
.filter((id): id is string => !!id),
},
};
const conversations = await prisma.gymConversation.findMany({

View File

@@ -3,12 +3,21 @@ import { badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { formatAddress } from '../../lib/address.js';
import { isPrismaNotFound } from '../../lib/prisma.js';
import { removeGymClaimFiles, removeGymPhotoFiles } from '../../lib/uploads.js';
import { GYM_PERMISSIONS, ROLE_KEYS, type GymPermissionKey } from '../../lib/permissions.js';
import {
canGym,
deriveMembershipRoles,
gymPermissionsFromGrants,
isGymOwner,
loadGymGrants,
} from '../../lib/gymPermissions.js';
import { toPrismaAvailability, type Availability } from '../me.js';
import { gymCoverInclude, gymEquipmentInclude } from './includes.js';
import { coverUrlOf } from './photos.js';
import { announceHoursChange } from '../announcements.js';
import { notifyGymDeleted } from '../feed.js';
import { countActiveByGym } from '../presence.js';
import { grantGymOwner } from '../roles.js';
export type GymKind = 'VIRTUAL' | 'REAL';
@@ -51,13 +60,31 @@ export async function listUserGyms(prisma: PrismaClient, userId: string) {
prisma,
memberships.filter((m) => m.gym.kind === 'REAL').map((m) => m.gym.id),
);
// Uprawnienia gymowe per siłownia z grantów (kolumna `roles` jest martwa).
const grants = await prisma.userRoleGrant.findMany({
where: { userId, gymId: { not: null } },
include: { role: { select: { key: true, permissions: true } } },
});
const keysByGym = new Map<string, string[]>();
const permsByGym = new Map<string, GymPermissionKey[]>();
for (const g of grants) {
if (!g.gymId) continue;
const list = keysByGym.get(g.gymId);
if (list) list.push(g.role.key);
else keysByGym.set(g.gymId, [g.role.key]);
const merged = [
...new Set([...(permsByGym.get(g.gymId) ?? []), ...gymPermissionsFromGrants([g])]),
];
permsByGym.set(g.gymId, merged);
}
return {
gyms: memberships.map((m) => {
const { photos, ...gym } = m.gym;
return {
...gym,
coverPhoto: coverUrlOf(gym.id, photos),
roles: m.roles,
roles: deriveMembershipRoles(keysByGym.get(gym.id) ?? [], true),
permissions: permsByGym.get(gym.id) ?? [],
currentOccupancy: gym.kind === 'REAL' ? (counts.get(gym.id) ?? 0) : null,
};
}),
@@ -85,6 +112,11 @@ export async function listAllGyms(prisma: PrismaClient) {
* Public: score (up-down) desc, then name asc; own private last, by name.
*/
export async function listVirtualGyms(prisma: PrismaClient, userId: string) {
const ownerGrants = await prisma.userRoleGrant.findMany({
where: { userId, gymId: { not: null }, role: { key: ROLE_KEYS.GYM_OWNER } },
select: { gymId: true },
});
const ownedGymIds = ownerGrants.map((g) => g.gymId).filter((id): id is string => !!id);
const [publicGyms, privateGyms, claims, myRatings] = await Promise.all([
prisma.gym.findMany({
where: { kind: 'VIRTUAL', isPrivate: false },
@@ -94,7 +126,7 @@ export async function listVirtualGyms(prisma: PrismaClient, userId: string) {
where: {
kind: 'VIRTUAL',
isPrivate: true,
memberships: { some: { userId, roles: { has: 'OWNER' } } },
id: { in: ownedGymIds },
},
include: { ...gymEquipmentInclude, _count: { select: { memberships: true } } },
}),
@@ -158,10 +190,8 @@ export async function rateGym(
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL' || gym.isPrivate)
throw conflict('Only public virtual gyms can be rated');
const isOwner = await prisma.gymMembership.findFirst({
where: { gymId, userId, roles: { has: 'OWNER' } },
});
if (isOwner) throw forbidden('The gym owner cannot rate their own gym');
if (await isGymOwner(prisma, userId, gymId))
throw forbidden('The gym owner cannot rate their own gym');
const existing = await prisma.gymRating.findUnique({
where: { gymId_userId: { gymId, userId } },
});
@@ -242,20 +272,26 @@ export async function createGym(
isPrivate,
},
});
await prisma.gymMembership.create({
data: { userId, gymId: gym.id, roles: ['OWNER'] },
});
await grantGymOwner(prisma, gym.id, userId);
return { gym: { ...gym, roles: ['OWNER'] } };
}
export async function assertGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
/** Strażnik capability gymowy (faza 2): rola z grantów, nie z kolumny `roles`. */
export async function assertGymOwner(
prisma: PrismaClient,
gymId: string,
userId: string,
permission: GymPermissionKey = GYM_PERMISSIONS.GYM_EDIT,
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { memberships: { where: { userId } }, equipment: true },
include: { equipment: true },
});
if (!gym) throw notFound('Gym not found');
const isOwner = gym.memberships.some((m) => m.roles.includes('OWNER'));
if (!isOwner) throw forbidden('Only the gym owner can manage this gym');
const grants = await loadGymGrants(prisma, userId, gymId);
if (!canGym(gymPermissionsFromGrants(grants), permission)) {
throw forbidden('Only the gym owner can manage this gym');
}
return gym;
}
@@ -339,7 +375,7 @@ function canonical(v: unknown): string {
/** Delete a gym (owner only). Memberships are removed; user plans are kept. */
export async function deleteOwnedGym(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await assertGymOwner(prisma, gymId, userId);
const gym = await assertGymOwner(prisma, gymId, userId, GYM_PERMISSIONS.GYM_DELETE);
const claimIds = await listGymClaimIds(prisma, gymId);
// Najpierw fan-out powiadomień — twarde usunięcie zabiłoby źródło, a nazwa
// siłowni jest duplikowana w payload.

View File

@@ -10,6 +10,7 @@ import {
storedFileName,
} from '../../lib/uploads.js';
import { canManageGym, loadGymDto, type UploadedPhotoFile } from './photos.js';
import { GYM_PERMISSIONS } from '../../lib/permissions.js';
async function loadInstance(prisma: PrismaClient, gymId: string, instanceId: string) {
const instance = await prisma.gymEquipment.findUnique({ where: { id: instanceId } });
@@ -26,7 +27,7 @@ export async function addEquipmentPhotos(
instanceId: string,
files: UploadedPhotoFile[],
) {
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
if (!(await canManageGym(prisma, gymId, userId, isAdmin, GYM_PERMISSIONS.GYM_EQUIPMENT)))
throw forbidden('Only the gym owner or an admin can manage equipment photos');
await loadInstance(prisma, gymId, instanceId);
const existing = await prisma.equipmentPhoto.count({ where: { gymEquipmentId: instanceId } });
@@ -66,7 +67,7 @@ export async function deleteEquipmentPhoto(
instanceId: string,
photoId: string,
) {
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
if (!(await canManageGym(prisma, gymId, userId, isAdmin, GYM_PERMISSIONS.GYM_EQUIPMENT)))
throw forbidden('Only the gym owner or an admin can manage equipment photos');
await loadInstance(prisma, gymId, instanceId);
const photo = await prisma.equipmentPhoto.findUnique({ where: { id: photoId } });

View File

@@ -5,6 +5,7 @@ import { isPrismaUnique } from '../../lib/prisma.js';
import { removeEquipmentPhotoFiles } from '../../lib/uploads.js';
import { toPrismaJson, type DayAvailability } from '../me.js';
import { assertGymOwner } from './core.js';
import { GYM_PERMISSIONS } from '../../lib/permissions.js';
import { gymEquipmentInclude } from './includes.js';
import { announceException } from '../announcements.js';
@@ -17,7 +18,7 @@ export interface CreateGymExceptionInput {
/** List a gym's upcoming schedule exceptions (owner only). */
export async function listOwnedGymExceptions(prisma: PrismaClient, gymId: string, userId: string) {
await assertGymOwner(prisma, gymId, userId);
await assertGymOwner(prisma, gymId, userId, GYM_PERMISSIONS.GYM_EXCEPTIONS);
const exceptions = await prisma.gymException.findMany({
where: { gymId },
orderBy: { date: 'asc' },
@@ -32,7 +33,7 @@ export async function createOwnedGymException(
userId: string,
data: CreateGymExceptionInput,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const gym = await assertGymOwner(prisma, gymId, userId, GYM_PERMISSIONS.GYM_EXCEPTIONS);
const date = new Date(data.date);
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
try {
@@ -58,7 +59,7 @@ export async function deleteOwnedGymException(
userId: string,
exceptionId: string,
) {
await assertGymOwner(prisma, gymId, userId);
await assertGymOwner(prisma, gymId, userId, GYM_PERMISSIONS.GYM_EXCEPTIONS);
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
await prisma.gymException.delete({ where: { id: exceptionId } });
@@ -78,7 +79,7 @@ export async function addEquipment(
quantity = 1,
spec?: unknown,
) {
await assertGymOwner(prisma, gymId, userId);
await assertGymOwner(prisma, gymId, userId, GYM_PERMISSIONS.GYM_EXCEPTIONS);
const item = await prisma.equipment.findUnique({ where: { id: equipmentId } });
if (!item) throw notFound('Equipment not found');
// Brak / null = instancja dziedziczy spec z katalogu (bez walidacji);
@@ -111,7 +112,7 @@ export async function updateEquipment(
data: { quantity?: number; spec?: unknown },
specProvided: boolean,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const gym = await assertGymOwner(prisma, gymId, userId, GYM_PERMISSIONS.GYM_EXCEPTIONS);
const link = gym.equipment.find((e) => e.id === instanceId);
if (!link) throw badRequest('Equipment not found in this gym');
const payload: Prisma.GymEquipmentUpdateInput = {};
@@ -145,7 +146,7 @@ export async function removeEquipment(
userId: string,
instanceId: string,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const gym = await assertGymOwner(prisma, gymId, userId, GYM_PERMISSIONS.GYM_EXCEPTIONS);
const link = gym.equipment.find((e) => e.id === instanceId);
if (!link) throw badRequest('Equipment not found in this gym');
await prisma.gymEquipment.delete({ where: { id: instanceId } });

View File

@@ -1,5 +1,7 @@
import type { PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { GYM_PERMISSIONS } from '../../lib/permissions.js';
import { canGym, resolveGymPermissions } from '../../lib/gymPermissions.js';
import { INVITATION_TTL_DAYS } from '../trainer.js';
async function assertGymOwnerOf(
@@ -7,11 +9,9 @@ async function assertGymOwnerOf(
gymId: string,
userId: string,
): Promise<void> {
const membership = await prisma.gymMembership.findFirst({
where: { gymId, userId, roles: { has: 'OWNER' } },
select: { id: true },
});
if (!membership) throw forbidden('Only the gym owner can do this');
const perms = await resolveGymPermissions(prisma, userId, gymId);
if (!canGym(perms, GYM_PERMISSIONS.GYM_MEMBERS))
throw forbidden('Only the gym owner can do this');
}
/**

View File

@@ -11,6 +11,14 @@ import {
} from '../../lib/uploads.js';
import { gymEquipmentWithPhotosInclude, gymPhotosInclude } from './includes.js';
import { countActiveByGym } from '../presence.js';
import { GYM_PERMISSIONS, type GymPermissionKey } from '../../lib/permissions.js';
import {
canInGym,
deriveMembershipRoles,
gymRoleKeys,
isGymOwner,
loadGymGrants,
} from '../../lib/gymPermissions.js';
export interface GymPhotoDto {
id: string;
@@ -84,19 +92,15 @@ export async function loadGymDto(prisma: PrismaClient, gymId: string) {
return gymToDto(gym);
}
/** True when the user may manage the gym: an admin or a member with the OWNER role. */
/** True when the user may manage the given gym capability: admin or gym grant (faza 2). */
export async function canManageGym(
prisma: PrismaClient,
gymId: string,
userId: string,
isAdmin: boolean,
permission: GymPermissionKey = GYM_PERMISSIONS.GYM_GALLERY,
): Promise<boolean> {
if (isAdmin) return true;
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { roles: true },
});
return !!membership?.roles.includes('OWNER');
return canInGym(prisma, userId, gymId, permission, isAdmin);
}
/**
@@ -115,11 +119,17 @@ export async function getGymPublic(
include: { ...gymEquipmentWithPhotosInclude, ...gymPhotosInclude },
});
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && gym.isPrivate && !(await canManageGym(prisma, gymId, userId, isAdmin)))
if (
gym.kind !== 'REAL' &&
gym.isPrivate &&
!(isAdmin || (await isGymOwner(prisma, userId, gymId)))
)
throw forbidden('You do not have access to this gym');
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
const grants = membership ? await loadGymGrants(prisma, userId, gymId) : [];
// Publiczny licznik „teraz: N" — tylko REAL (VIRTUAL nie przyjmuje meldunków).
const currentOccupancy =
gym.kind === 'REAL' ? ((await countActiveByGym(prisma, [gymId])).get(gymId) ?? 0) : null;
@@ -135,7 +145,7 @@ export async function getGymPublic(
: null;
return {
gym: { ...gymToDto(gym), currentOccupancy, myVote },
roles: membership?.roles ?? [],
roles: deriveMembershipRoles(gymRoleKeys(grants), !!membership),
isAdmin,
};
}

View File

@@ -2,7 +2,12 @@ import bcrypt from 'bcryptjs';
import { Prisma } from '@prisma/client';
import type { PrismaClient } from '@prisma/client';
import { publicUser } from '../lib/publicUser.js';
import { permissionsFromGrants, PLATFORM_GRANTS_INCLUDE } from '../lib/permissions.js';
import {
permissionsFromGrants,
PLATFORM_GRANTS_INCLUDE,
type GymPermissionKey,
} from '../lib/permissions.js';
import { deriveMembershipRoles, gymPermissionsFromGrants } from '../lib/gymPermissions.js';
import { AppError, conflict, notFound } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
import { latestWeightAtOrBefore } from './exerciseProgress.js';
@@ -99,11 +104,28 @@ export async function getProfile(prisma: PrismaClient, userId: string) {
},
});
if (!user) throw notFound('User not found');
const gymGrants = await prisma.userRoleGrant.findMany({
where: { userId, gymId: { not: null } },
include: { role: { select: { key: true, permissions: true } } },
});
const keysByGym = new Map<string, string[]>();
const permsByGym = new Map<string, GymPermissionKey[]>();
for (const g of gymGrants) {
if (!g.gymId) continue;
const list = keysByGym.get(g.gymId);
if (list) list.push(g.role.key);
else keysByGym.set(g.gymId, [g.role.key]);
const merged = [
...new Set([...(permsByGym.get(g.gymId) ?? []), ...gymPermissionsFromGrants([g])]),
];
permsByGym.set(g.gymId, merged);
}
return {
user: { ...publicUser(user), permissions: permissionsFromGrants(user) },
memberships: user.memberships.map((m) => ({
gymId: m.gymId,
roles: m.roles,
roles: deriveMembershipRoles(keysByGym.get(m.gymId) ?? [], true),
permissions: permsByGym.get(m.gymId) ?? [],
gym: m.gym,
})),
};

View File

@@ -1,5 +1,7 @@
import type { Prisma, PrismaClient } from '@prisma/client';
import { badRequest, forbidden, notFound } from '../lib/errors.js';
import { GYM_PERMISSIONS, ROLE_KEYS } from '../lib/permissions.js';
import { canInGym } from '../lib/gymPermissions.js';
export type PresenceSourceInput = 'QR' | 'MANUAL';
@@ -430,11 +432,8 @@ export async function getGymPresenceTelemetry(
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && !caller.isAdmin) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: caller.userId, gymId } },
select: { roles: true },
});
if (!membership?.roles.includes('OWNER')) throw forbidden('You do not have access to this gym');
if (!(await canInGym(prisma, caller.userId, gymId, GYM_PERMISSIONS.GYM_STATS)))
throw forbidden('You do not have access to this gym');
}
return getGymStats(prisma, gymId, range);
}
@@ -457,32 +456,41 @@ export async function getGymStatsOverview(
});
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL') throw badRequest('Statistics are available for real gyms');
if (!caller.isAdmin) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: caller.userId, gymId } },
select: { roles: true },
});
if (!membership?.roles.includes('OWNER'))
throw forbidden('Only the gym owner can view statistics');
}
const [presences, live, memberships] = await Promise.all([
if (!(await canInGym(prisma, caller.userId, gymId, GYM_PERMISSIONS.GYM_STATS, caller.isAdmin)))
throw forbidden('Only the gym owner can view statistics');
const [presences, live, memberships, roleGrants] = await Promise.all([
prisma.gymPresence.findMany({
where: { gymId, ...rangeWhere(range) },
orderBy: { checkedInAt: 'asc' },
}),
prisma.gymPresence.count({ where: { gymId, status: 'ACTIVE' } }),
prisma.gymMembership.findMany({ where: { gymId }, select: { roles: true, createdAt: true } }),
prisma.gymMembership.findMany({
where: { gymId },
select: { userId: true, createdAt: true },
}),
prisma.userRoleGrant.findMany({
where: { gymId },
select: { userId: true, role: { select: { key: true } } },
}),
]);
const { topEquipment: _topEquipment, ...stats } = await buildStats(prisma, presences);
const dayMs = 24 * 60 * 60 * 1000;
const days = Math.max(1, Math.ceil((range.to.getTime() - range.from.getTime()) / dayMs));
const ownerSet = new Set(
roleGrants.filter((g) => g.role.key === ROLE_KEYS.GYM_OWNER).map((g) => g.userId),
);
const trainerSet = new Set(
roleGrants.filter((g) => g.role.key === ROLE_KEYS.GYM_TRAINER).map((g) => g.userId),
);
const byRole = { OWNER: 0, TRAINER: 0, MEMBER: 0 };
let newInRange = 0;
for (const m of memberships) {
for (const role of m.roles) {
if (role === 'OWNER' || role === 'TRAINER' || role === 'MEMBER') byRole[role] += 1;
}
const owner = ownerSet.has(m.userId);
const trainer = trainerSet.has(m.userId);
if (owner) byRole.OWNER += 1;
if (trainer) byRole.TRAINER += 1;
if (!owner && !trainer) byRole.MEMBER += 1;
if (m.createdAt >= range.from && m.createdAt <= range.to) newInRange += 1;
}
@@ -539,14 +547,8 @@ export async function getEquipmentUsage(
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL') {
if (!caller.isAdmin) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: caller.userId, gymId } },
select: { roles: true },
});
if (!membership?.roles.includes('OWNER'))
throw forbidden('You do not have access to this gym');
}
if (!(await canInGym(prisma, caller.userId, gymId, GYM_PERMISSIONS.GYM_STATS, caller.isAdmin)))
throw forbidden('You do not have access to this gym');
return { equipment: [] };
}
const presences = await prisma.gymPresence.findMany({

View File

@@ -1,6 +1,18 @@
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
import { knownPermissions, PERMISSIONS } from '../lib/permissions.js';
import {
GYM_PERMISSIONS,
knownGymPermissions,
knownPermissions,
PERMISSIONS,
ROLE_KEYS,
} from '../lib/permissions.js';
import {
canGym,
filterAssignableGymPermissions,
gymRoleKeyFor,
resolveGymPermissions,
} from '../lib/gymPermissions.js';
import { Prisma, type PrismaClient } from '@prisma/client';
/** Klucz roli: stabilny identyfikator używany w danych, logach i tłumaczeniach. */
@@ -69,8 +81,17 @@ export async function assertTargetNotLastRolesManager(prisma: PrismaClient, user
}
}
/**
* Katalog ról platformy (panel admina). Role gymowe: globalne systemowe
* (GYM_OWNER/GYM_TRAINER — mają klucze gym) i customki (gymId ustawiony) są
* filtrowane; widoczne tylko per-siłownia (`listGymRoles`).
*/
export async function listRoles(prisma: PrismaClient) {
const roles = await prisma.role.findMany({
where: {
gymId: null,
NOT: { permissions: { hasSome: Object.values(GYM_PERMISSIONS) } },
},
orderBy: [{ isSystem: 'desc' }, { key: 'asc' }],
include: { _count: { select: { grants: { where: { gymId: null } } } } },
});
@@ -119,7 +140,7 @@ export async function updateRole(
input: { name?: string; permissions?: string[] },
) {
const role = await prisma.role.findUnique({ where: { id } });
if (!role) throw notFound('Role not found');
if (!role || role.gymId) throw notFound('Role not found');
const data: Prisma.RoleUpdateInput = {};
if (input.name !== undefined) {
@@ -173,7 +194,7 @@ export async function deleteRole(prisma: PrismaClient, id: string) {
where: { id },
include: { _count: { select: { grants: true } } },
});
if (!role) throw notFound('Role not found');
if (!role || role.gymId) throw notFound('Role not found');
if (role.isSystem) throw forbidden('Cannot delete a system role');
if (role._count.grants > 0) throw conflict('Role is still assigned to users');
await prisma.role.delete({ where: { id } });
@@ -233,3 +254,289 @@ export async function setUserPlatformRoles(
});
return { roles: keys };
}
/* ------------------------------------------------------------------ */
/* Role gymowe (faza 2): katalog per-siłownia + mutacje grantów gym */
/* ------------------------------------------------------------------ */
export interface GymRoleDto {
id: string;
key: string;
name: string | null;
permissions: string[];
isSystem: boolean;
grantCount: number;
}
async function ensureGym(prisma: PrismaClient, gymId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
select: { id: true, name: true },
});
if (!gym) throw notFound('Gym not found');
return gym;
}
/** Katalog ról do przydzielania w siłowni: globalne systemowe gym + customki tej siłowni. */
export async function listGymRoles(prisma: PrismaClient, gymId: string) {
await ensureGym(prisma, gymId);
const roles = await prisma.role.findMany({
where: {
OR: [
{ gymId },
{ gymId: null, isSystem: true, permissions: { hasSome: Object.values(GYM_PERMISSIONS) } },
],
},
include: { _count: { select: { grants: { where: { gymId } } } } },
orderBy: [{ isSystem: 'desc' }, { key: 'asc' }],
});
return {
roles: roles.map((r): GymRoleDto => ({
id: r.id,
key: r.key,
name: r.name,
permissions: r.permissions,
isSystem: r.isSystem,
grantCount: r._count.grants,
})),
};
}
/** Tworzenie roli custom danej siłowni. Klucz generowany serwerowo, `gym:delegate` odrzucany. */
export async function createGymRole(
prisma: PrismaClient,
gymId: string,
input: { name: string; permissions: string[] },
) {
const gym = await ensureGym(prisma, gymId);
const name = input.name.trim();
if (!name || name.length > 60) throw badRequest('Role name is required (max 60 characters)');
const permissions = filterAssignableGymPermissions(input.permissions ?? []);
if (permissions.length === 0) throw badRequest('Select at least one permission');
let key = gymRoleKeyFor(gym.name, gym.id, name);
for (let i = 0; ; i++) {
const candidate = i === 0 ? key : `${key}_${i}`.slice(0, 40);
const taken = await prisma.role.findUnique({ where: { key: candidate } });
if (!taken) {
key = candidate;
break;
}
if (i > 20) throw conflict('Role key collision');
}
const role = await prisma.role.create({
data: { key, name, permissions, gymId },
});
return {
role: {
id: role.id,
key: role.key,
name: role.name,
permissions: role.permissions,
isSystem: role.isSystem,
},
};
}
/** Edycja tylko customki tej samej siłowni (systemowe = zakaz). */
export async function updateGymRole(
prisma: PrismaClient,
gymId: string,
id: string,
input: { name?: string; permissions?: string[] },
) {
await ensureGym(prisma, gymId);
const role = await prisma.role.findUnique({ where: { id } });
if (!role || role.gymId !== gymId) throw notFound('Role not found');
if (role.isSystem) throw forbidden('Cannot edit a system role');
const data: Prisma.RoleUpdateInput = {};
if (input.name !== undefined) {
const name = input.name.trim();
if (!name || name.length > 60) throw badRequest('Role name is required (max 60 characters)');
data.name = name;
}
if (input.permissions !== undefined) {
const permissions = filterAssignableGymPermissions(input.permissions);
if (permissions.length === 0) throw badRequest('Select at least one permission');
data.permissions = permissions;
}
const updated = await prisma.role.update({ where: { id }, data });
return {
role: {
id: updated.id,
key: updated.key,
name: updated.name,
permissions: updated.permissions,
isSystem: updated.isSystem,
},
};
}
export async function deleteGymRole(prisma: PrismaClient, gymId: string, id: string) {
const role = await prisma.role.findUnique({
where: { id },
include: { _count: { select: { grants: true } } },
});
if (!role || role.gymId !== gymId) throw notFound('Role not found');
if (role.isSystem) throw forbidden('Cannot delete a system role');
if (role._count.grants > 0) throw conflict('Role is still assigned to users');
await prisma.role.delete({ where: { id } });
return { role: { id: role.id, key: role.key } };
}
/** Rola systemowa gymowa (globalna, gymId=null) albo customka tej siłowni; odrzuca role platformowe. */
function assertGymAssignableRow(
role: { key: string; gymId: string | null; isSystem: boolean; permissions: string[] },
gymId: string,
) {
if (role.gymId === null) {
const isSystemGymRole =
role.isSystem &&
role.permissions.length > 0 &&
knownGymPermissions(role.permissions).length === role.permissions.length;
if (!isSystemGymRole) throw forbidden('Platform roles cannot be assigned to a gym');
return;
}
if (role.gymId !== gymId) throw forbidden('Role belongs to another gym');
}
/**
* Wymiana zbioru grantów gymowych użytkownika w jednej siłowni (PUT).
* Aktor: `gym:delegate` (czyli GYM_OWNER tej siłowni — klucz przypięty) albo
* platformowy `gyms:manage` (nadzór). Właściciela (GYM_OWNER) rusza tylko
* admin. Ostatniego właściciela nie zdjmuje nikt poza adminem.
* Zmiana podbija tokenVersion.
*/
export async function setUserGymRoles(
prisma: PrismaClient,
gymId: string,
userId: string,
roleKeys: string[],
actor: { id: string; permissions: readonly string[] },
) {
await ensureGym(prisma, gymId);
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
if (!membership) throw notFound('User is not a member of this gym');
const isSuperAdmin = actor.permissions.includes(PERMISSIONS.GYMS_MANAGE);
if (!isSuperAdmin) {
const actorPerms = await resolveGymPermissions(prisma, actor.id, gymId);
if (!canGym(actorPerms, GYM_PERMISSIONS.GYM_DELEGATE)) {
throw forbidden('You cannot manage roles in this gym');
}
}
const keys = [...new Set(roleKeys)];
let roles: Array<{
id: string;
key: string;
gymId: string | null;
isSystem: boolean;
permissions: string[];
}> = [];
if (keys.length > 0) {
roles = await prisma.role.findMany({
where: { key: { in: keys } },
select: { id: true, key: true, gymId: true, isSystem: true, permissions: true },
});
if (roles.length !== keys.length) throw badRequest('Unknown role key');
for (const role of roles) {
assertGymAssignableRow(role, gymId);
if (role.key === ROLE_KEYS.GYM_OWNER && !isSuperAdmin) {
throw forbidden('Only platform admins can assign the gym owner role');
}
}
}
const grants = await prisma.userRoleGrant.findMany({
where: { userId, gymId },
include: { role: { select: { key: true } } },
});
const currentKeys = new Set(grants.map((g) => g.role.key));
const hadOwner = currentKeys.has(ROLE_KEYS.GYM_OWNER);
const willHaveOwner = keys.includes(ROLE_KEYS.GYM_OWNER);
if ((hadOwner || willHaveOwner) && !isSuperAdmin) {
throw forbidden('Only platform admins can change gym owner roles');
}
const changed = keys.length !== currentKeys.size || keys.some((k) => !currentKeys.has(k));
if (changed) {
await prisma.$transaction(async (tx) => {
await tx.userRoleGrant.deleteMany({ where: { userId, gymId } });
if (roles.length > 0) {
await tx.userRoleGrant.createMany({
data: roles.map((r) => ({ userId, roleId: r.id, gymId })),
});
}
await tx.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
});
}
return { roles: keys };
}
/** Dołożenie grantu roli systemowej gymowej (przepływy kreacji/claimu). */
async function ensureGymSystemGrant(
prisma: PrismaClient | Prisma.TransactionClient,
gymId: string,
userId: string,
roleKey: string,
) {
const role = await prisma.role.findUnique({ where: { key: roleKey }, select: { id: true } });
if (!role) throw new AppError(500, 'ROLE_SEED_MISSING', `System role ${roleKey} missing`);
await prisma.userRoleGrant.upsert({
where: {
userId_roleId_gymId: { userId, roleId: role.id, gymId },
},
update: {},
create: { userId, roleId: role.id, gymId },
});
}
/** Zdjęcie grantu roli systemowej gymowej. */
async function dropGymSystemGrant(
prisma: PrismaClient,
gymId: string,
userId: string,
roleKey: string,
) {
const role = await prisma.role.findUnique({ where: { key: roleKey }, select: { id: true } });
if (!role) return;
await prisma.userRoleGrant.deleteMany({ where: { userId, gymId, roleId: role.id } });
}
/** Nadaje rolę GYM_OWNER (admin/claim/kreacja): gwarantuje członkostwo + grant. */
export async function grantGymOwner(
prisma: PrismaClient | Prisma.TransactionClient,
gymId: string,
userId: string,
) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
if (!membership) {
await prisma.gymMembership.create({ data: { userId, gymId, roles: ['MEMBER'] } });
}
await ensureGymSystemGrant(prisma, gymId, userId, ROLE_KEYS.GYM_OWNER);
}
/** Zdjęcie GYM_OWNER (admin): usuwa grant; członkostwo zostaje (role wyprowadzane). */
export async function revokeGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
await dropGymSystemGrant(prisma, gymId, userId, ROLE_KEYS.GYM_OWNER);
}
/** Nadaje/zdejmuje rolę GYM_TRAINER (admin; UI ownera idzie przez setUserGymRoles). */
export async function setGymTrainer(
prisma: PrismaClient,
gymId: string,
userId: string,
grant: boolean,
) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
if (!membership && grant) {
await prisma.gymMembership.create({ data: { userId, gymId, roles: ['MEMBER'] } });
}
if (grant) await ensureGymSystemGrant(prisma, gymId, userId, ROLE_KEYS.GYM_TRAINER);
else await dropGymSystemGrant(prisma, gymId, userId, ROLE_KEYS.GYM_TRAINER);
}

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;
}

View File

@@ -29,6 +29,41 @@ async function grantPlatformRole(userId: string, key: string) {
await prisma.userRoleGrant.create({ data: { userId, roleId: role.id } });
}
/**
* Membership + odnośne granty gymowe (faza 2: OWNER/TRAINER czytane z grantów).
* `roles` w kształcie legacy (['OWNER'], ['TRAINER','MEMBER'], ['MEMBER']).
*/
export async function createMembership(
userId: string,
gymId: string,
roles: ('OWNER' | 'TRAINER' | 'MEMBER')[] = ['MEMBER'],
) {
const membership = await prisma.gymMembership.create({
data: { userId, gymId, roles: roles as never },
});
const keys = [
...(roles.includes('OWNER') ? ['GYM_OWNER'] : []),
...(roles.includes('TRAINER') ? ['GYM_TRAINER'] : []),
];
for (const key of keys) {
const role = await prisma.role.findUnique({ where: { key } });
if (!role) throw new Error(`Role ${key} missing — migrations not applied?`);
await prisma.userRoleGrant.create({ data: { userId, roleId: role.id, gymId } });
}
return membership;
}
/** Sam grant gymowy (gdy membership istnieje już z wcześniejszego create). */
export async function grantGymRole(
userId: string,
gymId: string,
key: 'GYM_OWNER' | 'GYM_TRAINER',
) {
const role = await prisma.role.findUnique({ where: { key } });
if (!role) throw new Error(`Role ${key} missing — migrations not applied?`);
await prisma.userRoleGrant.create({ data: { userId, roleId: role.id, gymId } });
}
export async function createUser(overrides: {
email?: string;
password?: string;

View File

@@ -3,6 +3,7 @@ import { prisma } from '../../src/lib/prisma.js';
import {
buildApp,
createUser,
grantGymRole,
loginViaApi,
rand,
registerViaApi,
@@ -222,10 +223,7 @@ describe('admin routes', () => {
expect(byQ.body.total).toBe(1);
// filtr roli: kadra (TRAINER) i OWNER — bez mieszania ról
await prisma.gymMembership.update({
where: { userId_gymId: { userId: member2.id, gymId: gym } },
data: { roles: ['MEMBER', 'TRAINER'] },
});
await grantGymRole(member2.id, gym, 'GYM_TRAINER');
const byTrainer = await app
.get(`/api/v1/admin/gyms/${gym}/members?role=TRAINER`)
.set('Authorization', `Bearer ${adminToken}`);
@@ -333,10 +331,10 @@ describe('admin routes', () => {
countryCode: 'PL',
capacity: 50,
});
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: ownerId, gymId: newGymId } },
const ownerGrant = await prisma.userRoleGrant.findFirst({
where: { userId: ownerId, gymId: newGymId, role: { key: 'GYM_OWNER' } },
});
expect(membership?.roles).toEqual(['OWNER']);
expect(ownerGrant).not.toBeNull();
const detail = await app
.get(`/api/v1/admin/gyms/${newGymId}`)
.set('Authorization', `Bearer ${adminToken}`);

View File

@@ -11,6 +11,7 @@ import {
registerViaApi,
seedPlan,
seedSession,
createMembership,
} from '../helpers.js';
// Data startu musi być z bieżącego lub przyszłego tygodnia — dynamiczny poniedziałek.
@@ -372,7 +373,8 @@ describe('activity logs (audit trail)', () => {
roles: ['MEMBER'],
});
expect(logs[1].details).toMatchObject({ roles: ['TRAINER'] });
expect(logs[2].details).toMatchObject({ roles: ['TRAINER'] });
// usunięcie: role wyprowadzone z grantów w momencie usuwania (faza 2)
expect(logs[2].details).toMatchObject({ roles: ['TRAINER', 'MEMBER'] });
});
it('admin gym CRUD logs gym.created/updated/deleted', async () => {
@@ -424,7 +426,7 @@ describe('activity logs (audit trail)', () => {
const trainer = await createUserWithToken({ firstName: 'Tomasz' });
const trainee = await createUserWithToken({ firstName: 'Anna' });
const gym = await prisma.gym.create({ data: { name: `Cmt Audit Gym ${rand()}` } });
await prisma.gymMembership.create({ data: { userId: trainer.user.id, gymId: gym.id, roles: ['TRAINER'] } });
await createMembership(trainer.user.id, gym.id, ['TRAINER']);
await prisma.gymMembership.create({ data: { userId: trainee.user.id, gymId: gym.id, roles: ['MEMBER'] } });
const app = buildApp();

View File

@@ -1,12 +1,14 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createExercise, createUserWithToken, rand, seedPlan, seedSession } from '../helpers.js';
async function createMembership(userId: string, gymId: string, roles: string[]) {
return prisma.gymMembership.create({
data: { userId, gymId, roles: roles as never },
});
}
import {
buildApp,
createExercise,
createMembership,
createUserWithToken,
rand,
seedPlan,
seedSession,
} from '../helpers.js';
describe('comments — under executed exercises', () => {
let app: ReturnType<typeof buildApp>;

View File

@@ -1,12 +1,14 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createExercise, createUserWithToken, rand, seedPlan, seedSession } from '../helpers.js';
async function createMembership(userId: string, gymId: string, roles: string[]) {
return prisma.gymMembership.create({
data: { userId, gymId, roles: roles as never },
});
}
import {
buildApp,
createExercise,
createMembership,
createUserWithToken,
rand,
seedPlan,
seedSession,
} from '../helpers.js';
describe('exercise progress — per-exercise 1RM + volume', () => {
let app: ReturnType<typeof buildApp>;

View File

@@ -1,6 +1,15 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUser, createExercise, loginViaApi, rand, registerViaApi, PASSWORD } from '../helpers.js';
import {
buildApp,
createMembership,
createUser,
createExercise,
loginViaApi,
rand,
registerViaApi,
PASSWORD,
} from '../helpers.js';
describe('exercises routes', () => {
let token: string;
@@ -58,7 +67,7 @@ describe('gyms routes', () => {
const gym = await prisma.gym.create({ data: { name: `My Gym ${Math.random().toString(36).slice(2)}` } });
const otherGym = await prisma.gym.create({ data: { name: `Other Gym ${Math.random().toString(36).slice(2)}` } });
await prisma.gymMembership.create({ data: { userId: user.id, gymId: gym.id, roles: ['MEMBER'] } });
await prisma.gymMembership.create({ data: { userId: otherUser.id, gymId: otherGym.id, roles: ['OWNER'] } });
await createMembership(otherUser.id, otherGym.id, ['OWNER']);
const token = (await loginViaApi(user.email, PASSWORD)).token;
const res = await app.get('/api/v1/gyms').set('Authorization', `Bearer ${token}`);

View File

@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUser, createUserWithToken, createExercise, rand } from '../helpers.js';
import { buildApp, createMembership, createUser, createUserWithToken, createExercise, rand } from '../helpers.js';
/* Ciało planu jednowyeku z jednym ćwiczeniem (wystarczające do testów powiadomień). */
function planBody(exerciseId: string, title = 'Plan testowy', gymId?: string) {
@@ -50,9 +50,7 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => {
const { user: trainee, token: traineeToken } = await createUserWithToken();
const { user: trainer, token: trainerToken } = await createUserWithToken();
const gym = await prisma.gym.create({ data: { name: `T Gym ${rand()}` } });
await prisma.gymMembership.create({
data: { userId: trainer.id, gymId: gym.id, roles: ['TRAINER'] as never },
});
await createMembership(trainer.id, gym.id, ['TRAINER']);
await activeCoaching(trainer.id, trainee.id);
const ex = await createExercise();
@@ -96,9 +94,7 @@ describe('feed — aktualności (powiadomienia + ogłoszenia)', () => {
const { user: trainee, token: traineeToken } = await createUserWithToken();
const { user: trainer, token: trainerToken } = await createUserWithToken();
const gym = await prisma.gym.create({ data: { name: `T Gym ${rand()}` } });
await prisma.gymMembership.create({
data: { userId: trainer.id, gymId: gym.id, roles: ['TRAINER'] as never },
});
await createMembership(trainer.id, gym.id, ['TRAINER']);
await activeCoaching(trainer.id, trainee.id);
const ex = await createExercise();

View File

@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUserWithToken, rand, seedPlan, seedSession } from '../helpers.js';
import { buildApp, createMembership, createUserWithToken, rand, seedPlan, seedSession } from '../helpers.js';
interface BoardResponse {
gym: { id: string; name: string };
@@ -71,9 +71,7 @@ describe('gym board — tablica statystyk siłowni (REAL)', () => {
data: { name: `Board Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
return gym;
}

View File

@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUserWithToken, rand } from '../helpers.js';
import { buildApp, createMembership, createUserWithToken, rand } from '../helpers.js';
describe('gym contact — wątek członek ↔ właściciele', () => {
let ownerToken: string;
@@ -50,9 +50,7 @@ describe('gym contact — wątek członek ↔ właściciele', () => {
data: { name: `Contact Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
await prisma.gymMembership.create({
data: { userId: memberId, gymId: gym.id, roles: ['MEMBER'] },
});
@@ -177,9 +175,7 @@ describe('gym contact — wątek członek ↔ właściciele', () => {
denied.body.conversations.some((c: { gymId: string }) => c.gymId === gym.id),
).toBe(false);
await prisma.gymMembership.create({
data: { userId: second.user.id, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(second.user.id, gym.id, ['OWNER']);
const inbox = await app.get('/api/v1/gym-contact/conversations').set(auth(second.token));
expect(
inbox.body.conversations.some((c: { gymId: string }) => c.gymId === gym.id),
@@ -244,9 +240,8 @@ describe('gym contact — wątek członek ↔ właściciele', () => {
where: { gymId_userId: { gymId: gym.id, userId: memberId } },
});
await prisma.gymMembership.update({
where: { userId_gymId: { userId: ownerId, gymId: gym.id } },
data: { roles: ['MEMBER'] },
await prisma.userRoleGrant.deleteMany({
where: { userId: ownerId, gymId: gym.id, role: { key: 'GYM_OWNER' } },
});
const single = await app
.get(`/api/v1/gym-contact/conversations/${conv!.id}`)

View File

@@ -1,7 +1,7 @@
import fs from 'node:fs';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUserWithToken, rand } from '../helpers.js';
import { buildApp, createMembership, createUserWithToken, rand } from '../helpers.js';
import { equipmentPhotoDir, removeGymPhotoFiles } from '../../src/lib/uploads.js';
/** Minimal 1x1 transparent PNG. */
@@ -45,9 +45,7 @@ describe('gym equipment — instances, spec overrides, photos', () => {
data: { name: name ?? `Equip Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
return gym;
}

View File

@@ -7,6 +7,7 @@ import {
rand,
seedPlan,
seedSession,
createMembership,
} from '../helpers.js';
interface UsageCell {
@@ -55,9 +56,7 @@ describe('gym equipment-usage — mapa ciepła urządzeń (24h)', () => {
data: { name: `Usage Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
return gym;
}
@@ -66,9 +65,7 @@ describe('gym equipment-usage — mapa ciepła urządzeń (24h)', () => {
data: { name: `Usage Virtual ${rand()}`, kind: 'VIRTUAL' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
return gym;
}

View File

@@ -2,7 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUserWithToken, rand } from '../helpers.js';
import { buildApp, createMembership, createUserWithToken, rand } from '../helpers.js';
import { photoUploadDir, removeGymPhotoFiles } from '../../src/lib/uploads.js';
/** Minimal 1x1 transparent PNG. */
@@ -44,9 +44,7 @@ describe('gym photos — gallery of REAL gyms', () => {
});
gymIds.push(gym.id);
if (ownerUserId) {
await prisma.gymMembership.create({
data: { userId: ownerUserId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerUserId, gym.id, ['OWNER']);
}
return gym;
}
@@ -88,9 +86,7 @@ describe('gym photos — gallery of REAL gyms', () => {
data: { name: `Virtual Owned ${rand()}`, kind: 'VIRTUAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
const res = await app.get(`/api/v1/gyms/${gym.id}`).set('Authorization', `Bearer ${ownerToken}`);
expect(res.status).toBe(200);
expect(res.body.roles).toContain('OWNER');
@@ -132,9 +128,7 @@ describe('gym photos — gallery of REAL gyms', () => {
data: { name: `Virtual NoGallery ${rand()}`, kind: 'VIRTUAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
const res = await app
.post(`/api/v1/gyms/${gym.id}/photos`)
.set('Authorization', `Bearer ${ownerToken}`)

View File

@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUserWithToken, rand } from '../helpers.js';
import { buildApp, createMembership, createUserWithToken, rand } from '../helpers.js';
interface PresenceStatsBody {
gym: { id: string; name: string; kind: string; capacity: number | null };
@@ -50,9 +50,7 @@ describe('gym presence-stats — telemetria bytności (widok ogólny)', () => {
data: { name: `Presence Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
return gym;
}
@@ -61,9 +59,7 @@ describe('gym presence-stats — telemetria bytności (widok ogólny)', () => {
data: { name: `Presence Virtual ${rand()}`, kind: 'VIRTUAL' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
return gym;
}

View File

@@ -6,8 +6,8 @@ import {
rand,
seedPlan,
seedSession,
createMembership,
} from '../helpers.js';
interface OverviewResponse {
gym: { id: string; name: string; kind: string; capacity: number | null };
presence: {
@@ -63,9 +63,7 @@ describe('gym stats overview — statystyki właściciela (REAL)', () => {
data: { name: `Stats Gym ${rand()}`, kind: 'REAL', location: 'Warszawa' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
return gym;
}
@@ -122,9 +120,7 @@ describe('gym stats overview — statystyki właściciela (REAL)', () => {
const exerciser = await createUserWithToken();
// członkostwa: OWNER + TRAINER + MEMBER (utworzone teraz) + MEMBER historyczny (120 dni)
await prisma.gymMembership.create({
data: { userId: exerciser.user.id, gymId: gym.id, roles: ['TRAINER'] },
});
await createMembership(exerciser.user.id, gym.id, ['TRAINER']);
await prisma.gymMembership.create({
data: { userId: memberId, gymId: gym.id, roles: ['MEMBER'] },
});
@@ -258,9 +254,7 @@ describe('gym stats overview — statystyki właściciela (REAL)', () => {
data: { name: `Stats Virtual ${rand()}`, kind: 'VIRTUAL', location: 'Wrocław' },
});
gymIds.push(gym.id);
await prisma.gymMembership.create({
data: { userId: ownerId, gymId: gym.id, roles: ['OWNER'] },
});
await createMembership(ownerId, gym.id, ['OWNER']);
const res = await app
.get(`/api/v1/gyms/${gym.id}/stats/overview`)
.set('Authorization', `Bearer ${ownerToken}`);

View File

@@ -1,6 +1,7 @@
import { describe, it, expect, beforeAll } from 'vitest';
import {
describe, it, expect, beforeAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUser, loginViaApi, rand, PASSWORD } from '../helpers.js';
import { buildApp, createMembership, createUser, loginViaApi, rand, PASSWORD } from '../helpers.js';
const PDF_BUFFER = Buffer.from('%PDF-1.4 test', 'utf8');
@@ -10,7 +11,7 @@ function makePdf(sizeBytes: number): Buffer {
return buf;
}
describe('gym claims — verification and new real gyms', () => {
describe('gym claims — verification and new real gyms', () => {
let adminToken: string;
let userToken: string;
let userId: string;
@@ -41,19 +42,19 @@ describe('gym claims — verification and new real gyms', () => {
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymId', gymId)
.field('description', 'To moja prawdziwa siłownia')
.field('description', 'To moja prawdziwa siłownia')
.field('companyName', 'Fit Sp. z o.o.')
.field('nip', '1234567890')
.field('phone', '+48 600 000 000')
.field('email', 'owner@fit.local')
.field('address', 'ul. Żelazna 1, Katowice')
.field('address', 'ul. Żelazna 1, Katowice')
.attach('files', PDF_BUFFER, { filename: 'umowa.pdf', contentType: 'application/pdf' });
expect(res.status).toBe(201);
expect(res.body.claim).toMatchObject({
gymId,
type: 'verification',
status: 'PENDING',
description: 'To moja prawdziwa siłownia',
description: 'To moja prawdziwa siłownia',
});
expect(res.body.claim.gym).toMatchObject({ id: gymId, kind: 'VIRTUAL' });
expect(res.body.claim.documents).toEqual([
@@ -169,9 +170,9 @@ describe('gym claims — verification and new real gyms', () => {
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymName', `Nowa Realna ${rand()}`)
.field('gymLocation', 'ul. Dźwignia 2, Łódź')
.field('gymLocation', 'ul. Dźwignia 2, Łódź')
.field('gymCapacity', '30')
.field('description', 'Prowadzę tę siłownię od 2020')
.field('description', 'Prowadzę tę siłownię od 2020')
.field('companyName', 'Nowa Fit Sp. z o.o.')
.field('nip', '1234567890');
expect(res.status).toBe(201);
@@ -180,7 +181,7 @@ describe('gym claims — verification and new real gyms', () => {
type: 'new',
status: 'PENDING',
gymName: expect.stringContaining('Nowa Realna'),
gymLocation: 'ul. Dźwignia 2, Łódź',
gymLocation: 'ul. Dźwignia 2, Łódź',
gymCapacity: 30,
});
});
@@ -190,7 +191,7 @@ describe('gym claims — verification and new real gyms', () => {
const res = await app
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymLocation', 'Łódź')
.field('gymLocation', 'Łódź')
.field('description', 'x');
expect(res.status).toBe(400);
});
@@ -212,7 +213,7 @@ describe('gym claims — verification and new real gyms', () => {
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymName', `Wiele ${rand()} ${i}`)
.field('gymLocation', 'Łódź')
.field('gymLocation', 'Łódź')
.field('description', 'x');
expect(res.status).toBe(201);
}
@@ -247,7 +248,7 @@ describe('gym claims — verification and new real gyms', () => {
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${otherToken}`)
.field('gymId', gymId)
.field('description', 'czyjś wniosek');
.field('description', 'czyjĹ› wniosek');
const mine = await app.get('/api/v1/gyms/claims').set('Authorization', `Bearer ${userToken}`);
expect(mine.body.claims.some((c: { id: string }) => c.id === created.body.claim.id)).toBe(false);
});
@@ -280,7 +281,7 @@ describe('gym claims — verification and new real gyms', () => {
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${otherToken}`)
.field('gymId', gymId)
.field('description', 'nie mój');
.field('description', 'nie mĂłj');
const res = await app
.delete(`/api/v1/gyms/claims/${created.body.claim.id}`)
.set('Authorization', `Bearer ${userToken}`);
@@ -294,7 +295,7 @@ describe('gym claims — verification and new real gyms', () => {
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymId', gymId)
.field('description', 'już rozstrzygnięty');
.field('description', 'już rozstrzygnięty');
const claimId = created.body.claim.id as string;
await prisma.gymClaim.update({ where: { id: claimId }, data: { status: 'REJECTED' } });
const res = await app
@@ -304,15 +305,13 @@ describe('gym claims — verification and new real gyms', () => {
});
});
describe('admin — approve / reject', () => {
it('approve (verification): gym → REAL + public, applicant → OWNER, other owners demoted, other claims rejected, location overridden', async () => {
describe('admin — approve / reject', () => {
it('approve (verification): gym → REAL + public, applicant → OWNER, other owners demoted, other claims rejected, location overridden', async () => {
const app = buildApp();
const gymId = await createVirtualGym(userToken);
// a second owner (admin-assigned role) to be demoted
const other = await createUser();
await prisma.gymMembership.create({
data: { userId: other.user.id, gymId, roles: ['OWNER'] },
});
await createMembership(other.user.id, gymId, ['OWNER']);
const otherToken = (await loginViaApi(other.user.email, PASSWORD)).token;
const otherClaim = await app
.post('/api/v1/gyms/claims')
@@ -324,7 +323,7 @@ describe('gym claims — verification and new real gyms', () => {
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymId', gymId)
.field('description', 'mój wniosek')
.field('description', 'mĂłj wniosek')
.field('address', 'ul. Nowa Adres 99, Katowice');
const claimId = myClaim.body.claim.id as string;
@@ -336,15 +335,19 @@ describe('gym claims — verification and new real gyms', () => {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
expect(gym).toMatchObject({ kind: 'REAL', isPrivate: false, location: 'ul. Nowa Adres 99, Katowice' });
const myMembership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
const myGrant = await prisma.userRoleGrant.findFirst({
where: { userId, gymId, role: { key: 'GYM_OWNER' } },
});
expect(myMembership?.roles).toContain('OWNER');
expect(myGrant).not.toBeNull();
const otherMembership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: other.user.id, gymId } },
});
expect(otherMembership?.roles).toEqual(['MEMBER']);
expect(otherMembership).not.toBeNull();
const otherGrant = await prisma.userRoleGrant.findFirst({
where: { userId: other.user.id, gymId, role: { key: 'GYM_OWNER' } },
});
expect(otherGrant).toBeNull();
const otherClaimRow = await prisma.gymClaim.findUnique({ where: { id: otherClaim.body.claim.id } });
expect(otherClaimRow).toMatchObject({ status: 'REJECTED', rejectReason: 'Zatwierdzono inny wniosek' });
@@ -354,14 +357,14 @@ describe('gym claims — verification and new real gyms', () => {
expect(claimRow?.decidedAt).toBeInstanceOf(Date);
});
it('approve (new real): creates a REAL gym, applicant → OWNER, claim.gymId set', async () => {
it('approve (new real): creates a REAL gym, applicant → OWNER, claim.gymId set', async () => {
const app = buildApp();
const created = await app
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymName', `Zatwierdzona Realna ${rand()}`)
.field('gymLocation', 'ul. Tarcza 5, Poznań')
.field('description', 'wniosek o nową realną');
.field('gymLocation', 'ul. Tarcza 5, Poznań')
.field('description', 'wniosek o nowÄ… realnÄ…');
const claimId = created.body.claim.id as string;
const res = await app
@@ -375,14 +378,14 @@ describe('gym claims — verification and new real gyms', () => {
const gym = await prisma.gym.findUnique({ where: { id: claimRow!.gymId! } });
expect(gym).toMatchObject({
name: expect.stringContaining('Zatwierdzona Realna'),
location: 'ul. Tarcza 5, Poznań',
location: 'ul. Tarcza 5, Poznań',
kind: 'REAL',
isPrivate: false,
});
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId: claimRow!.gymId! } },
const ownerGrant = await prisma.userRoleGrant.findFirst({
where: { userId, gymId: claimRow!.gymId!, role: { key: 'GYM_OWNER' } },
});
expect(membership?.roles).toEqual(['OWNER']);
expect(ownerGrant).not.toBeNull();
});
it('reject with a reason', async () => {
@@ -396,20 +399,20 @@ describe('gym claims — verification and new real gyms', () => {
const res = await app
.post(`/api/v1/admin/gyms/claims/${created.body.claim.id}/reject`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ reason: 'Brak dowodu własności' });
.send({ reason: 'Brak dowodu własności' });
expect(res.status).toBe(200);
const row = await prisma.gymClaim.findUnique({ where: { id: created.body.claim.id } });
expect(row).toMatchObject({ status: 'REJECTED', rejectReason: 'Brak dowodu własności' });
expect(row).toMatchObject({ status: 'REJECTED', rejectReason: 'Brak dowodu własności' });
});
it('approve of a non-PENDING claim → 409', async () => {
it('approve of a non-PENDING claim → 409', async () => {
const app = buildApp();
const gymId = await createVirtualGym(userToken);
const created = await app
.post('/api/v1/gyms/claims')
.set('Authorization', `Bearer ${userToken}`)
.field('gymId', gymId)
.field('description', 'rozstrzygnięty');
.field('description', 'rozstrzygnięty');
await prisma.gymClaim.update({ where: { id: created.body.claim.id }, data: { status: 'REJECTED' } });
const res = await app
.post(`/api/v1/admin/gyms/claims/${created.body.claim.id}/approve`)

View File

@@ -79,10 +79,11 @@ describe('gyms — selection and management', () => {
expect(res.status).toBe(201);
const gym = res.body.gym as { id: string; roles: string[] };
expect(gym.roles).toEqual(['OWNER']);
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId: gym.id } },
// faza 2: OWNER jako grant GYM_OWNER (kolumna `roles` martwa)
const grant = await prisma.userRoleGrant.findFirst({
where: { userId, gymId: gym.id, role: { key: 'GYM_OWNER' } },
});
expect(membership?.roles).toEqual(['OWNER']);
expect(grant).not.toBeNull();
});
it('rejects creating a gym without a name with 400', async () => {

View File

@@ -3,18 +3,13 @@ import { prisma } from '../../src/lib/prisma.js';
import {
buildApp,
createExercise,
createMembership,
createUserWithToken,
rand,
seedPlan,
seedSession,
} from '../helpers.js';
async function createMembership(userId: string, gymId: string, roles: string[]) {
return prisma.gymMembership.create({
data: { userId, gymId, roles: roles as never },
});
}
describe('messages — trainer↔trainee conversations', () => {
let app: ReturnType<typeof buildApp>;
let trainer: { id: string; token: string };

View File

@@ -10,6 +10,7 @@ import {
seedPlan,
seedSession,
PASSWORD,
createMembership,
} from '../helpers.js';
/** Poniedziałek bieżącego tygodnia 00:00 czasu lokalnego. */
@@ -46,12 +47,13 @@ describe('plan templates (kind=TEMPLATE)', () => {
stranger = { id: s.user.id, token: s.token };
const gym = await prisma.gym.create({ data: { name: `Templates Gym ${rand()}` } });
gymId = gym.id;
await prisma.gymMembership.create({ data: { userId: t.user.id, gymId, roles: ['TRAINER'] } });
await prisma.gymMembership.create({ data: { userId: tr.user.id, gymId, roles: ['MEMBER'] } });
await createMembership(t.user.id, gymId, ['TRAINER']);
await createMembership(tr.user.id, gymId, ['MEMBER']);
await prisma.coaching.create({
data: {
trainerId: t.user.id,
userId: tr.user.id,
gymId,
status: 'ACTIVE',
invitedBy: t.user.id,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),

View File

@@ -10,6 +10,7 @@ import {
registerViaApi,
seedPlan,
PASSWORD,
createMembership,
} from '../helpers.js';
// Daty dynamiczne: tydzień startu musi być bieżący lub przyszły (nie miniony).
@@ -1153,9 +1154,7 @@ describe('plans: trainer-created plan (creator + owner access)', () => {
trainerId = t.user.id;
traineeId = tr.user.id;
const gym = await prisma.gym.create({ data: { name: `Vis Gym ${rand()}` } });
await prisma.gymMembership.create({
data: { userId: trainerId, gymId: gym.id, roles: ['TRAINER'] as never },
});
await createMembership(trainerId, gym.id, ['TRAINER']);
await prisma.gymMembership.create({
data: { userId: traineeId, gymId: gym.id, roles: ['MEMBER'] as never },
});
@@ -1223,9 +1222,7 @@ describe('plans: trainer-created plan (creator + owner access)', () => {
it('trainer cannot attach a gym the trainee is NOT a member of (400)', async () => {
const gym = await prisma.gym.create({ data: { name: `Trainer-only Gym ${rand()}` } });
await prisma.gymMembership.create({
data: { userId: trainerId, gymId: gym.id, roles: ['TRAINER'] as never },
});
await createMembership(trainerId, gym.id, ['TRAINER']);
const res = await app
.post(`/api/v1/trainer/trainees/${traineeId}/plans`)
.set('Authorization', `Bearer ${trainerToken}`)

View File

@@ -193,13 +193,21 @@ describe('RBAC roles and permission gating', () => {
},
});
const read = await buildApp()
// faza 2: szukanie po e-mailu wymaga pii:read — moderator nie trafi po adresie
const byEmail = await buildApp()
.get(`/api/v1/admin/users?search=${encodeURIComponent(rawEmail)}`)
.set(auth);
expect(byEmail.status).toBe(200);
expect(byEmail.body.users).toHaveLength(0);
const read = await buildApp()
.get(`/api/v1/admin/users?search=${encodeURIComponent('Pii')}`)
.set(auth);
expect(read.status).toBe(200);
expect(read.body.users[0].email).toBe(maskedEmail);
expect(read.body.users[0].phone).toBeNull();
expect(read.body.users[0].birthDate).toBeNull();
const hit = read.body.users.find((u: { id: string }) => u.id === target.id);
expect(hit.email).toBe(maskedEmail);
expect(hit.phone).toBeNull();
expect(hit.birthDate).toBeNull();
});
it('shows full PII to pii:read holders', async () => {

View File

@@ -3,6 +3,7 @@ import { prisma } from '../../src/lib/prisma.js';
import {
buildApp,
createExercise,
createMembership,
createUser,
loginViaApi,
rand,
@@ -11,12 +12,6 @@ import {
PASSWORD,
} from '../helpers.js';
async function createMembership(userId: string, gymId: string, roles: string[]) {
return prisma.gymMembership.create({
data: { userId, gymId, roles: roles as never },
});
}
describe('trainer — invitations and trainees', () => {
let app: ReturnType<typeof buildApp>;
let trainer: { id: string; email: string; token: string };
@@ -198,6 +193,7 @@ describe('trainer — invitations and trainees', () => {
const gym2 = await prisma.gym.create({ data: { name: `Expired Gym ${rand()}` } });
const other = await createUser({ firstName: 'Ewa' });
await createMembership(other.user.id, gym2.id, ['MEMBER']);
await createMembership(trainer.id, gym2.id, ['TRAINER']);
const otherToken = (await loginViaApi(other.user.email, PASSWORD)).token;
const expired = await prisma.coaching.create({
data: {
@@ -218,6 +214,7 @@ describe('trainer — invitations and trainees', () => {
const gym2 = await prisma.gym.create({ data: { name: `Withdraw Gym ${rand()}` } });
const other = await createUser({ firstName: 'Iga' });
await createMembership(other.user.id, gym2.id, ['MEMBER']);
await createMembership(trainer.id, gym2.id, ['TRAINER']);
const created = await app
.post('/api/v1/trainer/invitations')
.set('Authorization', `Bearer ${trainer.token}`)
@@ -235,6 +232,7 @@ describe('trainer — invitations and trainees', () => {
const gym2 = await prisma.gym.create({ data: { name: `NoWithdraw Gym ${rand()}` } });
const other = await createUser({ firstName: 'Ola' });
await createMembership(other.user.id, gym2.id, ['MEMBER']);
await createMembership(trainer.id, gym2.id, ['TRAINER']);
const created = await app
.post('/api/v1/trainer/invitations')
.set('Authorization', `Bearer ${trainer.token}`)
@@ -251,6 +249,7 @@ describe('trainer — invitations and trainees', () => {
const gym2 = await prisma.gym.create({ data: { name: `Reverse Gym ${rand()}` } });
const newTrainer = await createUser({ firstName: 'Marek' });
await createMembership(newTrainer.user.id, gym2.id, ['TRAINER']);
await createMembership(plain.id, gym2.id, ['MEMBER']);
const token = (await loginViaApi(newTrainer.user.email, PASSWORD)).token;
const res = await app
.post('/api/v1/trainer/invitations')
@@ -268,6 +267,7 @@ describe('trainer — invitations and trainees', () => {
const gym2 = await prisma.gym.create({ data: { name: `Limit Gym ${rand()}` } });
const limited = await createUser({ firstName: 'Limit' });
await createMembership(limited.user.id, gym2.id, ['MEMBER']);
await createMembership(trainer.id, gym2.id, ['TRAINER']);
for (let i = 0; i < 10; i += 1) {
const filler = await createUser({ firstName: `Filler${i}` });
await createMembership(filler.user.id, gym2.id, ['MEMBER']);

View File

@@ -0,0 +1,136 @@
import { describe, expect, it, vi } from 'vitest';
import {
assertGymPermission,
canGym,
canInGym,
deriveMembershipRoles,
filterAssignableGymPermissions,
gymPermissionsFromGrants,
gymRoleKeyFor,
gymRoleKeys,
gymRoleLabel,
hasGymRoleKey,
isGymOwner,
} from '../../src/lib/gymPermissions.js';
import { GYM_PERMISSIONS, ROLE_KEYS } from '../../src/lib/permissions.js';
const grant = (key: string, permissions: string[]) => ({ role: { key, permissions } });
function prismaWithGrants(grants: ReturnType<typeof grant>[]) {
return {
userRoleGrant: { findMany: vi.fn().mockResolvedValue(grants) },
} as never;
}
describe('gymPermissionsFromGrants', () => {
it('merges permissions of all grants and drops unknown keys', () => {
const perms = gymPermissionsFromGrants([
grant(ROLE_KEYS.GYM_TRAINER, [GYM_PERMISSIONS.TRAINER_CLIENTS, 'users:read']),
grant('G_GYM_1234_RECEPCJA', [GYM_PERMISSIONS.GYM_CONTACT, GYM_PERMISSIONS.TRAINER_CLIENTS]),
]);
expect(perms).toEqual([GYM_PERMISSIONS.TRAINER_CLIENTS, GYM_PERMISSIONS.GYM_CONTACT]);
});
it('empty grants -> empty permissions', () => {
expect(gymPermissionsFromGrants([])).toEqual([]);
});
});
describe('canGym / gymRoleKeys / hasGymRoleKey', () => {
it('checks permission membership', () => {
expect(canGym([GYM_PERMISSIONS.GYM_STATS], GYM_PERMISSIONS.GYM_STATS)).toBe(true);
expect(canGym([GYM_PERMISSIONS.GYM_STATS], GYM_PERMISSIONS.GYM_DELETE)).toBe(false);
});
it('reads role keys from grants', () => {
const grants = [grant(ROLE_KEYS.GYM_OWNER, []), grant(ROLE_KEYS.GYM_TRAINER, [])];
expect(gymRoleKeys(grants)).toEqual([ROLE_KEYS.GYM_OWNER, ROLE_KEYS.GYM_TRAINER]);
expect(hasGymRoleKey(grants, ROLE_KEYS.GYM_TRAINER)).toBe(true);
expect(hasGymRoleKey(grants, 'OTHER')).toBe(false);
});
});
describe('deriveMembershipRoles', () => {
it('OWNER alone -> [OWNER] (legacy shape, no MEMBER)', () => {
expect(deriveMembershipRoles([ROLE_KEYS.GYM_OWNER], true)).toEqual(['OWNER']);
});
it('OWNER + TRAINER -> [OWNER, TRAINER]', () => {
expect(deriveMembershipRoles([ROLE_KEYS.GYM_OWNER, ROLE_KEYS.GYM_TRAINER], true)).toEqual([
'OWNER',
'TRAINER',
]);
});
it('TRAINER without owner -> [TRAINER, MEMBER]', () => {
expect(deriveMembershipRoles([ROLE_KEYS.GYM_TRAINER], true)).toEqual(['TRAINER', 'MEMBER']);
});
it('plain member -> [MEMBER]', () => {
expect(deriveMembershipRoles([], true)).toEqual(['MEMBER']);
});
it('not member, no grants -> []', () => {
expect(deriveMembershipRoles([], false)).toEqual([]);
});
});
describe('filterAssignableGymPermissions', () => {
it('keeps catalog keys and never allows gym:delegate', () => {
const out = filterAssignableGymPermissions([
GYM_PERMISSIONS.GYM_EDIT,
GYM_PERMISSIONS.GYM_DELEGATE,
'users:manage',
]);
expect(out).toEqual([GYM_PERMISSIONS.GYM_EDIT]);
});
});
describe('gymRoleKeyFor', () => {
it('builds ASCII slug with gym id suffix', () => {
const key = gymRoleKeyFor('Siłownia „Żółwik”', 'ckx1234abcd', 'Recepcja główna');
expect(key).toBe('G_SILOWNIA_ZOLWIK_abcd_RECEPCJA_GLOWNA');
expect(key.length).toBeLessThanOrEqual(40);
expect(key).toMatch(/^[A-Z0-9_]+$/i);
});
});
describe('gymRoleLabel', () => {
it('prefers custom name, falls back to key', () => {
expect(gymRoleLabel({ key: 'G_A_1_B', name: 'Recepcja' })).toBe('Recepcja');
expect(gymRoleLabel({ key: ROLE_KEYS.GYM_TRAINER, name: null })).toBe(ROLE_KEYS.GYM_TRAINER);
});
});
describe('isGymOwner / assertGymPermission / canInGym', () => {
const ownerGrants = [grant(ROLE_KEYS.GYM_OWNER, [GYM_PERMISSIONS.GYM_EDIT])];
it('isGymOwner true only with GYM_OWNER grant', async () => {
await expect(isGymOwner(prismaWithGrants(ownerGrants), 'u1', 'g1')).resolves.toBe(true);
await expect(
isGymOwner(prismaWithGrants([grant(ROLE_KEYS.GYM_TRAINER, [])]), 'u1', 'g1'),
).resolves.toBe(false);
});
it('assertGymPermission resolves via grants and admin override skips the query', async () => {
const prisma = prismaWithGrants([
grant('G_G_1_RECEPCJA', [GYM_PERMISSIONS.GYM_CONTACT]),
]);
await expect(
assertGymPermission(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_CONTACT),
).resolves.toBeUndefined();
await expect(
assertGymPermission(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_DELETE),
).rejects.toMatchObject({ status: 403 });
await expect(
assertGymPermission(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_DELETE, true),
).resolves.toBeUndefined();
});
it('canInGym flag semantics', async () => {
const prisma = prismaWithGrants([grant(ROLE_KEYS.GYM_TRAINER, [GYM_PERMISSIONS.TRAINER_CLIENTS])]);
await expect(canInGym(prisma, 'u1', 'g1', GYM_PERMISSIONS.TRAINER_CLIENTS)).resolves.toBe(true);
await expect(canInGym(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_STATS)).resolves.toBe(false);
await expect(canInGym(prisma, 'u1', 'g1', GYM_PERMISSIONS.GYM_STATS, true)).resolves.toBe(true);
});
});

View File

@@ -9,7 +9,27 @@ import {
import { PERMISSIONS } from '../../src/lib/permissions.js';
function mockPrisma() {
const tx = {
role: {
findMany: vi.fn().mockResolvedValue([
{ id: 'r-owner', key: 'GYM_OWNER' },
{ id: 'r-trainer', key: 'GYM_TRAINER' },
]),
},
userRoleGrant: {
findMany: vi.fn().mockResolvedValue([]),
create: vi.fn(),
delete: vi.fn(),
},
gymMembership: {
create: vi.fn(),
findUniqueOrThrow: vi.fn(),
},
user: { update: vi.fn() },
};
return {
$tx: tx,
$transaction: vi.fn(async (cb: (t: typeof tx) => unknown) => cb(tx)),
user: { findUnique: vi.fn(), count: vi.fn(), update: vi.fn(), delete: vi.fn() },
gym: { findUnique: vi.fn(), update: vi.fn(), delete: vi.fn() },
gymMembership: { findUnique: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
@@ -117,7 +137,7 @@ describe('updateMembership', () => {
});
});
it('sets the roles list of an existing membership', async () => {
it('replaces OWNER/TRAINER system grants and bumps tokenVersion', async () => {
const prisma = mockPrisma();
prisma.gymMembership.findUnique.mockResolvedValue({
id: 'm1',
@@ -125,18 +145,20 @@ describe('updateMembership', () => {
gymId: 'g1',
roles: ['MEMBER'],
});
prisma.gymMembership.update.mockResolvedValue({
prisma.$tx.gymMembership.findUniqueOrThrow.mockResolvedValue({
id: 'm1',
userId: 'u1',
gymId: 'g1',
roles: ['OWNER', 'TRAINER'],
});
const result = await updateMembership(prisma, 'u1', 'g1', ['OWNER', 'TRAINER']);
expect(result.membership).toMatchObject({ roles: ['OWNER', 'TRAINER'] });
expect(prisma.gymMembership.update).toHaveBeenCalledWith({
where: { userId_gymId: { userId: 'u1', gymId: 'g1' } },
data: { roles: ['OWNER', 'TRAINER'] },
expect(prisma.$tx.userRoleGrant.create).toHaveBeenCalledTimes(2);
expect(prisma.$tx.userRoleGrant.create).toHaveBeenCalledWith({
data: { userId: 'u1', roleId: 'r-owner', gymId: 'g1' },
});
expect(prisma.$tx.user.update).toHaveBeenCalledWith(
expect.objectContaining({ data: { tokenVersion: { increment: 1 } } }),
);
});
});