API: konsola sirowni - logi operacji (GET /gyms/:id/logs), czlonkowie z q/role, related, lista sirowni z q/kind + owners; usuwanie czlonkostwa z powodem w audycie membership.deleted (swagger, testy integracyjne)

This commit is contained in:
tisachi
2026-10-29 21:20:50 +01:00
parent 8f802675cd
commit 2305649493
5 changed files with 688 additions and 66 deletions

View File

@@ -36,6 +36,8 @@ import {
getGym,
getGymClaim,
listGymClaims,
listGymMembers,
listGymRelated,
listGyms,
listUsers,
rejectGymClaim,
@@ -63,7 +65,7 @@ import {
listAnnouncementsForAdmin,
updateAnnouncementAsAdmin,
} from '../services/announcements.js';
import { listActivityLogs, logActivity } from '../services/audit.js';
import { listActivityLogs, listGymAuditLogs, logActivity } from '../services/audit.js';
import { asyncHandler } from '../lib/asyncHandler.js';
const gymSchema = z.object({
@@ -186,23 +188,35 @@ const updateMembershipSchema = z.object({
roles: z.array(z.enum(GYM_ROLES)).min(1),
});
const removeMembershipSchema = z.object({
reason: z.string().trim().min(3).max(300).optional(),
});
export function createAdminRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma), requireAdmin);
const listGymsQuerySchema = z.object({
q: z.string().trim().max(200).optional(),
kind: z.enum(['REAL', 'VIRTUAL']).optional(),
});
/**
* @openapi
* /admin/gyms:
* get:
* summary: List gyms (admin)
* summary: List gyms (admin). Query: q (nazwa/adres/miasto/kod/właściciel), kind (REAL|VIRTUAL).
* Each gym includes `owners` (members with OWNER role) and `_count.memberships`.
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get(
'/gyms',
asyncHandler(async (_req, res) => {
const result = await listGyms(prisma);
validate(listGymsQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const q = req.query as z.infer<typeof listGymsQuerySchema>;
const result = await listGyms(prisma, { q: q.q, kind: q.kind });
res.json(result);
}),
);
@@ -337,6 +351,83 @@ export function createAdminRoutes({ prisma }: AppDeps) {
}),
);
const gymLogsQuerySchema = z.object({
limit: z.coerce.number().int().min(1).max(500).optional(),
offset: z.coerce.number().int().min(0).optional(),
});
/**
* @openapi
* /admin/gyms/{id}/logs:
* get:
* summary: Audit log of one gym (admin) — gym.* entries, membership.* tied to this gym
* (details.gymId) and this gym's claims/invitations. Query: limit (default 50, max 500), offset.
* tags: [Admin]
* responses:
* 200: { description: OK, returns { logs, total } }
* 404: { description: Gym not found }
*/
router.get(
'/gyms/:id/logs',
validate(gymLogsQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const gym = await prisma.gym.findUnique({
where: { id: req.params.id },
select: { id: true },
});
if (!gym) throw notFound('Gym not found');
const q = req.query as z.infer<typeof gymLogsQuerySchema>;
const result = await listGymAuditLogs(prisma, req.params.id, q.limit ?? 50, q.offset ?? 0);
res.json(result);
}),
);
const gymMembersQuerySchema = z.object({
q: z.string().trim().max(200).optional(),
role: z.enum(['OWNER', 'TRAINER', 'MEMBER']).optional(),
limit: z.coerce.number().int().min(1).max(200).optional(),
offset: z.coerce.number().int().min(0).optional(),
});
/**
* @openapi
* /admin/gyms/{id}/members:
* get:
* summary: Members of one gym (admin). Query: q (imię/nazwisko/email), role (OWNER|TRAINER|MEMBER), limit (default 50, max 200), offset.
* OWNER first, then by join date; each member carries roles, joinedAt, account status and `checkedInNow`.
* tags: [Admin]
* responses:
* 200: { description: OK, returns { members, total } }
* 404: { description: Gym not found }
*/
router.get(
'/gyms/:id/members',
validate(gymMembersQuerySchema, 'query'),
asyncHandler(async (req, res) => {
const q = req.query as z.infer<typeof gymMembersQuerySchema>;
const result = await listGymMembers(prisma, req.params.id, q);
res.json(result);
}),
);
/**
* @openapi
* /admin/gyms/{id}/related:
* get:
* summary: Claims and invitations tied to one gym (admin), newest first.
* tags: [Admin]
* responses:
* 200: { description: OK, returns { claims, invitations } }
* 404: { description: Gym not found }
*/
router.get(
'/gyms/:id/related',
asyncHandler(async (req, res) => {
const result = await listGymRelated(prisma, req.params.id);
res.json(result);
}),
);
/**
* @openapi
* /admin/gyms/{id}/exceptions:
@@ -842,14 +933,16 @@ export function createAdminRoutes({ prisma }: AppDeps) {
* @openapi
* /admin/users/{id}/memberships/{gymId}:
* delete:
* summary: Remove gym membership (admin)
* summary: Remove gym membership (admin). Optional body: { reason } (audyt).
* tags: [Admin]
* responses:
* 204: { description: Deleted }
*/
router.delete(
'/users/:id/memberships/:gymId',
validate(removeMembershipSchema),
asyncHandler(async (req, res) => {
const { reason } = req.body as z.infer<typeof removeMembershipSchema>;
const result = await removeMembership(prisma, req.params.id, req.params.gymId);
await logActivity(prisma, {
actorId: req.user!.id,
@@ -860,6 +953,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
userId: req.params.id,
gymId: req.params.gymId,
roles: result.membership.roles,
...(reason ? { reason } : {}),
},
});
res.status(204).end();

View File

@@ -9,12 +9,7 @@ import {
removeGymClaimFiles,
removeGymPhotoFiles,
} from '../lib/uploads.js';
import {
availabilityChanged,
gymPhotoUrl,
listGymClaimIds,
mapEquipmentPhotoDtos,
} from './gyms.js';
import { availabilityChanged, listGymClaimIds, mapEquipmentPhotoDtos } from './gyms.js';
import { announceHoursChange } from './announcements.js';
import { notifyGymDeleted } from './feed.js';
import { formatAddress, type AddressParts } from '../lib/address.js';
@@ -91,26 +86,59 @@ export async function ensureUser(prisma: PrismaClient, userId: string) {
if (!user) throw notFound('User not found');
}
export async function listGyms(prisma: PrismaClient) {
export interface ListGymsQuery {
/** Szukane hasło: nazwa, adres, miasto, kod lub nazwisko/e-mail właściciela. */
q?: string;
kind?: 'REAL' | 'VIRTUAL';
}
export async function listGyms(prisma: PrismaClient, query: ListGymsQuery = {}) {
const term = query.q?.trim();
const where: Prisma.GymWhereInput = {
...(query.kind ? { kind: query.kind } : {}),
...(term
? {
OR: [
{ name: { contains: term, mode: 'insensitive' } },
{ location: { contains: term, mode: 'insensitive' } },
{ 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' } },
],
},
},
},
},
],
}
: {}),
};
const gyms = await prisma.gym.findMany({
where,
orderBy: { name: 'asc' },
include: {
_count: { select: { memberships: true } },
equipment: {
include: { equipment: true },
orderBy: { equipment: { name: 'asc' } },
},
photos: {
orderBy: [{ order: 'asc' }, { createdAt: 'asc' }],
take: 1,
memberships: {
where: { roles: { has: 'OWNER' } },
include: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
orderBy: { user: { createdAt: 'asc' } },
},
},
});
return {
gyms: gyms.map((g) => {
const { photos, ...rest } = g;
return { ...rest, coverPhoto: photos[0] ? gymPhotoUrl(g.id, photos[0].id) : null };
}),
gyms: gyms.map(({ memberships, ...g }) => ({
...g,
owners: memberships.map((m) => m.user),
})),
};
}
@@ -176,6 +204,108 @@ export async function removeGymOwner(prisma: PrismaClient, gymId: string, userId
}
}
export interface GymMembersQuery {
q?: string;
role?: 'OWNER' | 'TRAINER' | 'MEMBER';
limit?: number;
offset?: number;
}
/** Lista członków jednej siłowni (admin): OWNER najpierw, potem wg dołączenia; `checkedInNow` z ACTIVE bytności. */
export async function listGymMembers(
prisma: PrismaClient,
gymId: string,
query: GymMembersQuery = {},
) {
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 where: Prisma.GymMembershipWhereInput = {
gymId,
...(query.role ? { roles: { has: query.role } } : {}),
...(term
? {
user: {
OR: [
{ firstName: { contains: term, mode: 'insensitive' } },
{ lastName: { contains: term, mode: 'insensitive' } },
{ email: { contains: term, mode: 'insensitive' } },
],
},
}
: {}),
};
const [total, memberships, active] = await Promise.all([
prisma.gymMembership.count({ where }),
prisma.gymMembership.findMany({
where,
include: {
user: { select: { id: true, firstName: true, lastName: true, email: true, status: true } },
},
}),
prisma.gymPresence.findMany({ where: { gymId, status: 'ACTIVE' }, select: { userId: true } }),
]);
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')) ||
a.createdAt.getTime() - b.createdAt.getTime(),
);
const limit = query.limit ?? 50;
const offset = query.offset ?? 0;
return {
members: sorted.slice(offset, offset + limit).map((m) => ({
membershipId: m.id,
roles: m.roles,
joinedAt: m.createdAt.toISOString(),
checkedInNow: live.has(m.userId),
user: m.user,
})),
total,
};
}
/** Wnioski i zaproszenia powiązane z jedną siłownią (admin), najnowsze pierwsze. */
export async function listGymRelated(prisma: PrismaClient, gymId: string) {
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } });
if (!gym) throw notFound('Gym not found');
const [claims, invitations] = await Promise.all([
prisma.gymClaim.findMany({
where: { gymId },
include: {
user: { select: { id: true, firstName: true, lastName: true, email: true } },
_count: { select: { documents: true } },
},
orderBy: { createdAt: 'desc' },
}),
prisma.gymInvitation.findMany({
where: { gymId },
include: {
user: { select: { id: true, firstName: true, lastName: true, email: true } },
invitedBy: { select: { id: true, firstName: true, lastName: true, email: true } },
},
orderBy: { createdAt: 'desc' },
}),
]);
return {
claims: claims.map((c) => ({
id: c.id,
status: c.status,
createdAt: c.createdAt.toISOString(),
user: c.user,
documentCount: c._count.documents,
})),
invitations: invitations.map((i) => ({
id: i.id,
status: i.status,
invitedAt: i.invitedAt.toISOString(),
expiresAt: i.expiresAt.toISOString(),
user: i.user,
invitedBy: i.invitedBy,
})),
};
}
/** Tworzy siłownię REAL z adresem; `location` derivowany, wyznaczony `ownerId` dostaje rolę OWNER. */
export async function createGym(prisma: PrismaClient, data: CreateGymInput) {
const { availability, ownerId, ...rest } = data;

View File

@@ -63,6 +63,27 @@ export interface ActivityLogEntry {
actor: ActivityLogActor;
}
async function fetchActivityLogs(
prisma: PrismaClient,
where: Prisma.ActivityLogWhereInput,
limit: number,
offset: number,
) {
const [logs, total] = await Promise.all([
prisma.activityLog.findMany({
where,
include: {
actor: { select: { id: true, email: true, firstName: true, lastName: true } },
},
orderBy: { createdAt: 'desc' },
take: limit,
skip: offset,
}),
prisma.activityLog.count({ where }),
]);
return { logs, total };
}
export async function listActivityLogs(prisma: PrismaClient, filters: ActivityLogFilters) {
const where: Prisma.ActivityLogWhereInput = {
...(filters.action ? { action: filters.action } : {}),
@@ -77,17 +98,35 @@ export async function listActivityLogs(prisma: PrismaClient, filters: ActivityLo
}
: undefined,
};
const [logs, total] = await Promise.all([
prisma.activityLog.findMany({
where,
include: {
actor: { select: { id: true, email: true, firstName: true, lastName: true } },
},
orderBy: { createdAt: 'desc' },
take: filters.limit,
skip: filters.offset,
}),
prisma.activityLog.count({ where }),
]);
return { logs, total };
return fetchActivityLogs(prisma, where, filters.limit, filters.offset);
}
/**
* Logi przypisane do jednej siłowni: operacje na encji `gym`,
* `membership.*` powiązane przez `details.gymId` oraz wnioski (claims)
* i zaproszenia tej siłowni.
*/
export async function listGymAuditLogs(
prisma: PrismaClient,
gymId: string,
limit: number,
offset: number,
) {
const [claims, invitations] = await Promise.all([
prisma.gymClaim.findMany({ where: { gymId }, select: { id: true } }),
prisma.gymInvitation.findMany({ where: { gymId }, select: { id: true } }),
]);
const where: Prisma.ActivityLogWhereInput = {
OR: [
{ entityType: 'gym', entityId: gymId },
{ entityType: 'membership', details: { path: ['gymId'], equals: gymId } },
...(claims.length
? [{ entityType: 'gym-claim', entityId: { in: claims.map((c) => c.id) } }]
: []),
...(invitations.length
? [{ entityType: 'gym-invitation', entityId: { in: invitations.map((i) => i.id) } }]
: []),
],
};
return fetchActivityLogs(prisma, where, limit, offset);
}

View File

@@ -1797,33 +1797,6 @@ export const openapi: Record<string, unknown> = {
],
},
},
'/admin/gyms/occupancy': {
get: {
tags: ['Admin'],
summary: 'Live occupancy of all real gyms (admin)',
security: [{ bearerAuth: [] }],
responses: {
200: { description: 'OK, returns { gyms: [{ gymId, name, capacity, count }] }' },
},
},
},
'/admin/gyms/{id}/presence-stats': {
get: {
tags: ['Admin'],
summary:
'Presence telemetry of a gym (admin): live count, day×hour heatmap, avg stay, visits/day, peak, top equipment (default range: last 30 days)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'from', in: 'query', schema: { type: 'string', format: 'date-time' } },
{ name: 'to', in: 'query', schema: { type: 'string', format: 'date-time' } },
],
responses: {
200: { description: 'OK, returns { gym, stats }' },
404: { description: 'Gym not found' },
},
},
},
'/admin/gyms/{id}/equipment-usage': {
get: {
tags: ['Admin'],
@@ -1847,8 +1820,23 @@ export const openapi: Record<string, unknown> = {
'/admin/gyms': {
get: {
tags: ['Admin'],
summary: 'List gyms (admin)',
summary:
'List gyms (admin). Query: q (matches name/location/city/address/postal code/owner name or email), kind (REAL|VIRTUAL). Each gym includes owners[] (OWNER members) and _count.memberships.',
security: [{ bearerAuth: [] }],
parameters: [
{
name: 'q',
in: 'query',
required: false,
schema: { type: 'string', maxLength: 200 },
},
{
name: 'kind',
in: 'query',
required: false,
schema: { type: 'string', enum: ['REAL', 'VIRTUAL'] },
},
],
},
post: {
tags: ['Admin'],
@@ -1930,6 +1918,79 @@ export const openapi: Record<string, unknown> = {
],
},
},
'/admin/gyms/{id}/logs': {
get: {
tags: ['Admin'],
summary:
"Audit log of one gym (admin) — gym.* entries, membership.* tied to this gym (details.gymId) and this gym's claims/invitations",
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
{
name: 'limit',
in: 'query',
required: false,
schema: { type: 'integer', minimum: 1, maximum: 500, default: 50 },
},
{
name: 'offset',
in: 'query',
required: false,
schema: { type: 'integer', minimum: 0, default: 0 },
},
],
responses: {
200: { description: 'OK, returns { logs, total }' },
404: { description: 'Gym not found' },
},
},
},
'/admin/gyms/{id}/members': {
get: {
tags: ['Admin'],
summary:
'Members of one gym (admin) — OWNER first, then by join date; roles, joinedAt, account status, checkedInNow',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'q', in: 'query', required: false, schema: { type: 'string', maxLength: 200 } },
{
name: 'role',
in: 'query',
required: false,
schema: { type: 'string', enum: ['OWNER', 'TRAINER', 'MEMBER'] },
},
{
name: 'limit',
in: 'query',
required: false,
schema: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
},
{
name: 'offset',
in: 'query',
required: false,
schema: { type: 'integer', minimum: 0, default: 0 },
},
],
responses: {
200: { description: 'OK, returns { members, total }' },
404: { description: 'Gym not found' },
},
},
},
'/admin/gyms/{id}/related': {
get: {
tags: ['Admin'],
summary: 'Claims and invitations tied to one gym (admin), newest first',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
200: { description: 'OK, returns { claims, invitations }' },
404: { description: 'Gym not found' },
},
},
},
'/admin/gyms/{id}/exceptions': {
get: {
tags: ['Admin'],
@@ -2136,12 +2197,25 @@ export const openapi: Record<string, unknown> = {
tags: ['Admin'],
summary: 'Remove gym membership (admin)',
description:
'Writes an ActivityLog entry: membership.deleted (details: userId, gymId, roles).',
'Writes an ActivityLog entry: membership.deleted (details: userId, gymId, roles, optional reason).',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
],
requestBody: {
required: false,
content: {
'application/json': {
schema: {
type: 'object',
properties: {
reason: { type: 'string', minLength: 3, maxLength: 300 },
},
},
},
},
},
},
},
'/admin/users/{id}/killstreak': {

View File

@@ -1,6 +1,13 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { prisma } from '../../src/lib/prisma.js';
import { buildApp, createUser, loginViaApi, registerViaApi, PASSWORD } from '../helpers.js';
import {
buildApp,
createUser,
loginViaApi,
rand,
registerViaApi,
PASSWORD,
} from '../helpers.js';
describe('admin routes', () => {
let adminToken: string;
@@ -51,6 +58,257 @@ describe('admin routes', () => {
const gym = res.body.gyms.find((g: { id: string }) => g.id === gymId);
expect(gym).toBeDefined();
expect(gym._count.memberships).toBe(0);
expect(gym.owners).toEqual([]);
});
it('filters the gym list by q (name/city/owner) and kind, exposing owners', async () => {
const app = buildApp();
const suffix = rand();
const owner = (await createUser({ firstName: `Jan`, lastName: `Kowalski${suffix}` })).user;
const created = await app
.post('/api/v1/admin/gyms')
.set('Authorization', `Bearer ${adminToken}`)
.send({
name: `FitTest ${suffix}`,
addressLine1: 'Kwiatowa 5',
postalCode: '30-001',
city: `Krakow`,
ownerId: owner.id,
});
expect(created.status).toBe(201);
const newGymId = created.body.gym.id as string;
const byName = await app
.get(`/api/v1/admin/gyms?q=${encodeURIComponent(`FitTest ${suffix}`)}`)
.set('Authorization', `Bearer ${adminToken}`);
expect(byName.status).toBe(200);
expect(byName.body.gyms.map((g: { id: string }) => g.id)).toEqual([newGymId]);
expect(byName.body.gyms[0].owners).toEqual([
expect.objectContaining({ id: owner.id, lastName: `Kowalski${suffix}` }),
]);
// ten sam obiekt znajdziemy po mieście i po nazwisku właściciela
const byCity = await app
.get(`/api/v1/admin/gyms?q=${encodeURIComponent(`Kwiatowa 5`)}`)
.set('Authorization', `Bearer ${adminToken}`);
expect(byCity.body.gyms.map((g: { id: string }) => g.id)).toContain(newGymId);
const byOwner = await app
.get(`/api/v1/admin/gyms?q=${encodeURIComponent(`kowalski${suffix}`.toUpperCase())}`)
.set('Authorization', `Bearer ${adminToken}`);
expect(byOwner.body.gyms.map((g: { id: string }) => g.id)).toEqual([newGymId]);
// filtr typu: REAL zawiera, VIRTUAL wyklucza
const realOnly = await app
.get(`/api/v1/admin/gyms?q=${encodeURIComponent(suffix)}&kind=REAL`)
.set('Authorization', `Bearer ${adminToken}`);
expect(realOnly.body.gyms.map((g: { id: string }) => g.id)).toEqual([newGymId]);
const virtualOnly = await app
.get(`/api/v1/admin/gyms?q=${encodeURIComponent(suffix)}&kind=VIRTUAL`)
.set('Authorization', `Bearer ${adminToken}`);
expect(virtualOnly.body.gyms).toHaveLength(0);
});
it('lists audit logs scoped to one gym (gym.*, membership.*, 404 for unknown gym)', async () => {
const app = buildApp();
const tag = rand();
const gymA = (
await app
.post('/api/v1/admin/gyms')
.set('Authorization', `Bearer ${adminToken}`)
.send({
name: `LogA ${tag}`,
addressLine1: 'A 1',
postalCode: '00-001',
city: 'A',
ownerId,
})
).body.gym.id as string;
const gymB = (
await app
.post('/api/v1/admin/gyms')
.set('Authorization', `Bearer ${adminToken}`)
.send({
name: `LogB ${tag}`,
addressLine1: 'B 1',
postalCode: '00-002',
city: 'B',
ownerId: ownerId2,
})
).body.gym.id as string;
// osobne konto — nie zatruwamy memberships `target` używanego dalej w pliku
const memberForLogs = (await createUser()).user.id;
for (const gid of [gymA, gymB]) {
const m = await app
.post(`/api/v1/admin/users/${memberForLogs}/memberships`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ gymId: gid, roles: ['MEMBER'] });
expect(m.status).toBe(201);
}
const res = await app
.get(`/api/v1/admin/gyms/${gymA}/logs`)
.set('Authorization', `Bearer ${adminToken}`);
expect(res.status).toBe(200);
const logs = res.body.logs as {
action: string;
entityType: string;
entityId: string | null;
details: { gymId?: string } | null;
}[];
expect(logs.some((l) => l.action === 'gym.created' && l.entityId === gymA)).toBe(true);
expect(
logs.some((l) => l.action === 'membership.created' && l.details?.gymId === gymA),
).toBe(true);
// logi innej siłowni nie przeciekają
expect(logs.some((l) => l.entityType === 'gym' && l.entityId === gymB)).toBe(false);
expect(logs.some((l) => l.details?.gymId === gymB)).toBe(false);
expect(res.body.total).toBeGreaterThanOrEqual(2);
const unknown = await app
.get('/api/v1/admin/gyms/unknown-gym/logs')
.set('Authorization', `Bearer ${adminToken}`);
expect(unknown.status).toBe(404);
});
it('lists members of one gym (OWNER first, q and role filters, checkedInNow, 404 for unknown gym)', async () => {
const app = buildApp();
const tag = rand();
const gym = (
await app
.post('/api/v1/admin/gyms')
.set('Authorization', `Bearer ${adminToken}`)
.send({
name: `Members ${tag}`,
addressLine1: 'M 1',
postalCode: '00-010',
city: 'M',
ownerId,
})
).body.gym.id as string;
const member1 = (await createUser({ firstName: `Ala${tag}`, lastName: `Marek` })).user;
const member2 = (await createUser({ firstName: `Ola${tag}` })).user;
for (const uid of [member1.id, member2.id]) {
const m = await app
.post(`/api/v1/admin/users/${uid}/memberships`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ gymId: gym, roles: ['MEMBER'] });
expect(m.status).toBe(201);
}
// member1 "teraz na siłowni"
await prisma.gymPresence.create({ data: { userId: member1.id, gymId: gym } });
const res = await app
.get(`/api/v1/admin/gyms/${gym}/members`)
.set('Authorization', `Bearer ${adminToken}`);
expect(res.status).toBe(200);
const members = res.body.members as {
roles: string[];
checkedInNow: boolean;
joinedAt: string;
user: { id: string; status: string };
}[];
expect(res.body.total).toBe(3);
// OWNER najpierw, potem pozostali wg dołączenia
expect(members.map((m) => m.user.id)).toEqual([ownerId, member1.id, member2.id]);
expect(members[0].roles).toEqual(['OWNER']);
expect(members.map((m) => m.checkedInNow)).toEqual([false, true, false]);
expect(members.every((m) => m.user.status === 'ACTIVE' && m.joinedAt)).toBe(true);
const byQ = await app
.get(`/api/v1/admin/gyms/${gym}/members?q=marek`)
.set('Authorization', `Bearer ${adminToken}`);
expect(byQ.body.members.map((m: { user: { id: string } }) => m.user.id)).toEqual([member1.id]);
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'] },
});
const byTrainer = await app
.get(`/api/v1/admin/gyms/${gym}/members?role=TRAINER`)
.set('Authorization', `Bearer ${adminToken}`);
expect(byTrainer.status).toBe(200);
expect(byTrainer.body.members.map((m: { user: { id: string } }) => m.user.id)).toEqual([
member2.id,
]);
expect(byTrainer.body.total).toBe(1);
const byOwner = await app
.get(`/api/v1/admin/gyms/${gym}/members?role=OWNER`)
.set('Authorization', `Bearer ${adminToken}`);
expect(byOwner.body.members.map((m: { user: { id: string } }) => m.user.id)).toEqual([ownerId]);
const unknown = await app
.get('/api/v1/admin/gyms/unknown-gym/members')
.set('Authorization', `Bearer ${adminToken}`);
expect(unknown.status).toBe(404);
});
it('lists claims and invitations tied to one gym only', async () => {
const app = buildApp();
const tag = rand();
const gym = (
await app
.post('/api/v1/admin/gyms')
.set('Authorization', `Bearer ${adminToken}`)
.send({
name: `Rel ${tag}`,
addressLine1: 'R 1',
postalCode: '00-020',
city: 'R',
ownerId,
})
).body.gym.id as string;
const other = (
await app
.post('/api/v1/admin/gyms')
.set('Authorization', `Bearer ${adminToken}`)
.send({
name: `RelOther ${tag}`,
addressLine1: 'R 2',
postalCode: '00-021',
city: 'R',
ownerId: ownerId2,
})
).body.gym.id as string;
await prisma.gymClaim.create({
data: { gymId: gym, userId: targetId, description: `claim-${tag}` },
});
await prisma.gymClaim.create({
data: { gymId: other, userId: targetId, description: `claim-other-${tag}` },
});
await prisma.gymInvitation.create({
data: {
gymId: gym,
userId: targetId,
invitedById: ownerId,
expiresAt: new Date(Date.now() + 86_400_000),
},
});
const res = await app
.get(`/api/v1/admin/gyms/${gym}/related`)
.set('Authorization', `Bearer ${adminToken}`);
expect(res.status).toBe(200);
expect(res.body.claims).toHaveLength(1);
expect(res.body.claims[0]).toMatchObject({
status: 'PENDING',
user: { id: targetId },
documentCount: 0,
});
expect(res.body.invitations).toHaveLength(1);
expect(res.body.invitations[0]).toMatchObject({
status: 'PENDING',
user: { id: targetId },
invitedBy: { id: ownerId },
});
const unknown = await app
.get('/api/v1/admin/gyms/unknown-gym/related')
.set('Authorization', `Bearer ${adminToken}`);
expect(unknown.status).toBe(404);
});
it('creates a gym and makes the designated owner OWNER', async () => {
@@ -477,6 +735,33 @@ describe('admin routes', () => {
expect(again.status).toBe(400);
});
it('records the removal reason in the audit log (membership.deleted)', async () => {
const app = buildApp();
const target = (await createUser({ firstName: 'Powod' })).user;
const add = await app
.post(`/api/v1/admin/users/${target.id}/memberships`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ gymId, roles: ['MEMBER'] });
expect(add.status).toBe(201);
const membershipId = add.body.membership.id as string;
const del = await app
.delete(`/api/v1/admin/users/${target.id}/memberships/${gymId}`)
.set('Authorization', `Bearer ${adminToken}`)
.send({ reason: 'Wielokrotne łamanie regulaminu' });
expect(del.status).toBe(204);
const log = await prisma.activityLog.findFirst({
where: { action: 'membership.deleted', entityId: membershipId },
});
expect(log).not.toBeNull();
expect(log!.details).toMatchObject({
reason: 'Wielokrotne łamanie regulaminu',
gymId,
roles: ['MEMBER'],
});
});
it('changes a membership roles', async () => {
const app = buildApp();
const target = await prisma.user.findUnique({ where: { email: targetEmail } });