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

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