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:
@@ -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;
|
||||
|
||||
@@ -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}`);
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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>;
|
||||
|
||||
@@ -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}`);
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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}`);
|
||||
|
||||
@@ -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`)
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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']);
|
||||
|
||||
136
api/test/unit/gym-permissions.test.ts
Normal file
136
api/test/unit/gym-permissions.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
@@ -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 } } }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user