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': {