import bcrypt from 'bcryptjs'; import { Prisma, type PrismaClient } from '@prisma/client'; import { validateEquipmentSpec } from '../lib/equipmentSpec.js'; import { isPrismaNotFound } from '../lib/prisma.js'; import { publicUser } from '../lib/publicUser.js'; import { ROLE_KEYS } from '../lib/permissions.js'; import { deriveMembershipRoles } from '../lib/gymPermissions.js'; import { PLATFORM_GRANTS_INCLUDE, PERMISSIONS, redactUserDto, redactUserDtos, redactUserRef, } from '../lib/permissions.js'; import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js'; import { assertNotStaffTarget, assertTargetNotLastRolesManager, grantGymOwner } from './roles.js'; import { removeEquipmentPhotoFiles, removeGymClaimFiles, removeGymPhotoFiles, } from '../lib/uploads.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'; import { resolveMuscleConflicts, toPrismaAvailability, toPrismaJson, type Availability, type SocialMediaEntry, } from './me.js'; export interface CreateGymInput { name: string; /** Administrator wyznacza właściciela nowej siłowni (rola OWNER). */ ownerId: string; /** Strukturalny adres (REAL); `location` jest z niego derivowany. */ addressLine1: string; addressLine2?: string | null; postalCode: string; city: string; countryCode?: string; availability?: Availability | null; capacity?: number | null; } export interface UpdateGymInput { name?: string; addressLine1?: string | null; addressLine2?: string | null; postalCode?: string | null; city?: string | null; countryCode?: string | null; availability?: Availability | null; capacity?: number | null; } export interface CreateUserInput { email: string; password: string; firstName?: string; lastName?: string; birthDate?: string | null; } export interface UpdateUserInput { email?: string; firstName?: string | null; lastName?: string | null; nickname?: string | null; socialMedia?: SocialMediaEntry[] | null; birthDate?: string | null; heightCm?: number | null; phone?: string | null; password?: string; availability?: Availability | null; priorities?: string | null; exclusions?: string | null; developMuscles?: string[]; canDoMuscles?: string[]; difficultMuscles?: string[]; avoidMuscles?: string[]; status?: 'ACTIVE' | 'SUSPENDED' | 'BANNED'; suspensionUntil?: string | null; restrictionReason?: string | null; } export type MembershipRole = 'OWNER' | 'TRAINER' | 'MEMBER'; /** Upewnia się, że użytkownik istnieje — endpointy admina per-user zwracają 404 zamiast pustych danych. */ export async function ensureUser(prisma: PrismaClient, userId: string) { const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true } }); if (!user) throw notFound('User not found'); } 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 = {}, permissions: readonly string[] = [], ) { const term = query.q?.trim(); const ownerUserSelect = { id: true, firstName: true, lastName: true, email: true } as const; const ownerWhere: Prisma.UserWhereInput = { OR: [ { firstName: { contains: term ?? '', mode: 'insensitive' } }, { lastName: { contains: term ?? '', mode: 'insensitive' } }, { email: { contains: term ?? '', mode: 'insensitive' } }, ], }; // Właściciele z grantów (kolumna `roles` martwa): najpierw gymy pasujące // przez nazwisko/e-mail właściciela, potem wyciągamy właścicieli hurtowo. const ownerGymIdsWhere = term ? ( await prisma.userRoleGrant.findMany({ where: { gymId: { not: null }, role: { key: ROLE_KEYS.GYM_OWNER }, user: ownerWhere, }, select: { gymId: true }, }) ) .map((g) => g.gymId) .filter((id): id is string => !!id) : []; const where: Prisma.GymWhereInput = { ...(query.kind ? { kind: query.kind } : {}), ...(term ? { 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' } }, { id: { in: ownerGymIdsWhere } }, ], } : {}), }; const gyms = await prisma.gym.findMany({ where, orderBy: { name: 'asc' }, include: { _count: { select: { memberships: true } } }, }); const ownerRows = await prisma.userRoleGrant.findMany({ where: { gymId: { in: gyms.map((g) => g.id) }, role: { key: ROLE_KEYS.GYM_OWNER } }, include: { user: { select: { ...ownerUserSelect, createdAt: true } } }, orderBy: { user: { createdAt: 'asc' } }, }); const ownersByGym = new Map< string, Array<{ id: string; firstName: string | null; lastName: string | null; email: string }> >(); for (const g of ownerRows) { if (!g.gymId) continue; const { createdAt: _createdAt, ...owner } = g.user; const list = ownersByGym.get(g.gymId); if (list) list.push(owner); else ownersByGym.set(g.gymId, [owner]); } return { gyms: gyms.map((g) => ({ ...g, owners: redactUserDtos(ownersByGym.get(g.id) ?? [], permissions), })), }; } export async function getGym( prisma: PrismaClient, gymId: string, permissions: readonly string[] = [], ) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true, photos: { orderBy: { createdAt: 'asc' } } }, orderBy: { equipment: { name: 'asc' } }, }, photos: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] }, _count: { select: { memberships: true } }, }, }); if (!gym) throw Object.assign(new Error('Nie znaleziono siłowni'), { status: 404 }); const { equipment, ...rest } = gym; const ownerRows = await prisma.userRoleGrant.findMany({ where: { gymId, role: { key: ROLE_KEYS.GYM_OWNER } }, include: { user: { select: { id: true, firstName: true, lastName: true, email: true } } }, orderBy: { user: { createdAt: 'asc' } }, }); return { ...rest, equipment: mapEquipmentPhotoDtos(gymId, equipment), owners: redactUserDtos( ownerRows.map((g) => g.user), permissions, ), }; } /** Nadaje użytkownikowi rolę GYM_OWNER (admin): gwarantuje członkostwo + grant. */ export async function addGymOwner(prisma: PrismaClient, gymId: string, userId: string) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } }); if (!gym) throw notFound('Gym not found'); await ensureUser(prisma, userId); await grantGymOwner(prisma, gymId, userId); await prisma.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } }); const membership = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId, gymId } }, }); return { membership: { ...membership, roles: ['OWNER'] } }; } /** Zdejmuje rolę GYM_OWNER (admin); jak legacy — członkostwo pada, gdy nie ma już żadnej roli w tym gymie. */ export async function removeGymOwner(prisma: PrismaClient, gymId: string, userId: string) { const role = await prisma.role.findUnique({ where: { key: ROLE_KEYS.GYM_OWNER }, select: { id: true }, }); if (!role) throw notFound('Gym owner not found'); const grant = await prisma.userRoleGrant.findFirst({ where: { userId, gymId, roleId: role.id }, select: { id: true }, }); if (!grant) throw notFound('Gym owner not found'); await prisma.$transaction(async (tx) => { await tx.userRoleGrant.delete({ where: { id: grant.id } }); const left = await tx.userRoleGrant.count({ where: { userId, gymId } }); if (left === 0) { await tx.gymMembership.deleteMany({ where: { userId, gymId } }); } await tx.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } }); }); } 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 = {}, permissions: readonly string[] = [], ) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } }); if (!gym) throw notFound('Gym not found'); const term = query.q?.trim(); const roleKey = query.role === 'OWNER' ? ROLE_KEYS.GYM_OWNER : query.role === 'TRAINER' ? ROLE_KEYS.GYM_TRAINER : null; const where: Prisma.GymMembershipWhereInput = { gymId, ...(roleKey ? { user: { roleGrants: { some: { gymId, role: { key: roleKey } } } } } : {}), ...(term ? { user: { OR: [ { firstName: { contains: term, mode: 'insensitive' } }, { lastName: { contains: term, mode: 'insensitive' } }, { email: { contains: term, mode: 'insensitive' } }, ], }, } : {}), }; const [total, memberships, active, gymGrants] = 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 } }), prisma.userRoleGrant.findMany({ where: { gymId }, include: { role: { select: { key: true } } }, }), ]); const keysByUser = new Map(); for (const g of gymGrants) { const list = keysByUser.get(g.userId); if (list) list.push(g.role.key); else keysByUser.set(g.userId, [g.role.key]); } const live = new Set(active.map((p) => p.userId)); const sorted = memberships.sort( (a, b) => Number((keysByUser.get(b.userId) ?? []).includes(ROLE_KEYS.GYM_OWNER)) - Number((keysByUser.get(a.userId) ?? []).includes(ROLE_KEYS.GYM_OWNER)) || a.createdAt.getTime() - b.createdAt.getTime(), ); const limit = query.limit ?? 50; const offset = query.offset ?? 0; return { members: sorted.slice(offset, offset + limit).map((m) => ({ membershipId: m.id, roles: deriveMembershipRoles(keysByUser.get(m.userId) ?? [], true), joinedAt: m.createdAt.toISOString(), checkedInNow: live.has(m.userId), user: redactUserRef(m.user, permissions), })), total, }; } /** Wnioski i zaproszenia powiązane z jedną siłownią (admin), najnowsze pierwsze. */ export async function listGymRelated( prisma: PrismaClient, gymId: string, permissions: readonly 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: redactUserRef(c.user, permissions), documentCount: c._count.documents, })), invitations: invitations.map((i) => ({ id: i.id, status: i.status, invitedAt: i.invitedAt.toISOString(), expiresAt: i.expiresAt.toISOString(), user: redactUserRef(i.user, permissions), invitedBy: redactUserRef(i.invitedBy, permissions), })), }; } /** 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; await ensureUser(prisma, ownerId); const location = formatAddress(rest); const gym = await prisma.$transaction(async (tx) => { const created = await tx.gym.create({ data: { ...rest, countryCode: (data.countryCode ?? 'PL').toUpperCase(), location, availability: toPrismaAvailability(availability), }, }); await tx.gymMembership.create({ data: { userId: ownerId, gymId: created.id }, }); await grantGymOwner(tx, created.id, ownerId); return created; }); return { gym }; } /** * Aktualizacja siłowni; przy zmianie któregokolwiek pola adresu reszta jest * scalana ze stanem w bazie, a display string `location` liczony od nowa. */ export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGymInput) { try { const { availability, addressLine1, addressLine2, postalCode, city, countryCode, ...rest } = data; const existing = await prisma.gym.findUniqueOrThrow({ where: { id } }); let addressData: Prisma.GymUpdateInput = {}; const hasAddress = [addressLine1, addressLine2, postalCode, city, countryCode].some( (v) => v !== undefined, ); if (hasAddress) { const merged: AddressParts = { addressLine1: addressLine1 !== undefined ? addressLine1 : existing.addressLine1, addressLine2: addressLine2 !== undefined ? addressLine2 : existing.addressLine2, postalCode: postalCode !== undefined ? postalCode : existing.postalCode, city: city !== undefined ? city : existing.city, countryCode: countryCode !== undefined ? countryCode ? countryCode.trim().toUpperCase() : null : existing.countryCode, }; addressData = { ...merged, location: formatAddress(merged) }; } const gym = await prisma.gym.update({ where: { id }, data: { ...rest, ...addressData, availability: toPrismaAvailability(availability) }, }); if (availabilityChanged(existing.availability, availability)) { await announceHoursChange(prisma, id, gym.name); } return { gym }; } catch (e) { if (isPrismaNotFound(e)) throw notFound('Gym not found'); throw e; } } export async function deleteGym(prisma: PrismaClient, id: string) { const gym = await prisma.gym.findUnique({ where: { id } }); if (!gym) throw notFound('Gym not found'); const claimIds = await listGymClaimIds(prisma, id); // Najpierw fan-out powiadomień (jak przy usuwaniu przez właściciela). await notifyGymDeleted(prisma, id, gym.name); await prisma.gym.delete({ where: { id } }); await removeGymClaimFiles(claimIds); removeGymPhotoFiles(id); return { name: gym.name }; } /** * Tworzy NOWĄ instancję wyposażenia siłowni (admin). `spec` = nadpisanie * specyfikacji katalogowej, walidowane względem `kind`; null/brak = dziedziczy. */ export async function addGymEquipment( prisma: PrismaClient, gymId: string, equipmentId: string, quantity = 1, spec?: unknown, ) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { id: true } }); if (!gym) throw notFound('Gym not found'); const item = await prisma.equipment.findUnique({ where: { id: equipmentId } }); if (!item) throw notFound('Equipment not found'); // Brak / null = instancja dziedziczy spec z katalogu; podana wartość musi pasować do `kind`. const validated = spec === undefined || spec === null ? ({ ok: true, spec: null } as const) : validateEquipmentSpec(item.kind, spec); if (!validated.ok) throw badRequest(validated.error); const created = await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity, spec: toPrismaJson(validated.spec) }, }); const updated = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true } } }, }); return { gym: updated, instance: created }; } /** * Zmiana ilości / specyfikacji instancji wyposażenia (admin). * `spec: null` czyści nadpisanie; brak klucza `spec` = bez zmian. */ export async function updateGymEquipment( prisma: PrismaClient, gymId: string, instanceId: string, data: { quantity?: number; spec?: unknown }, specProvided: boolean, ) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: true }, }); if (!gym) throw notFound('Gym not found'); const link = gym.equipment.find((e) => e.id === instanceId); if (!link) throw badRequest('Equipment not found in this gym'); const payload: Prisma.GymEquipmentUpdateInput = {}; if (data.quantity !== undefined) payload.quantity = data.quantity; if (specProvided) { if (data.spec === null || data.spec === undefined) { payload.spec = Prisma.DbNull; } else { const item = await prisma.equipment.findUnique({ where: { id: link.equipmentId }, select: { kind: true }, }); if (!item) throw notFound('Equipment not found'); const validated = validateEquipmentSpec(item.kind, data.spec); if (!validated.ok) throw badRequest(validated.error); payload.spec = toPrismaJson(validated.spec); } } await prisma.gymEquipment.update({ where: { id: instanceId }, data: payload }); const updated = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true } } }, }); return { gym: updated, equipmentId: link.equipmentId }; } /** Usuwa instancję wyposażenia wraz z plikami zdjęć (admin). */ export async function removeGymEquipment(prisma: PrismaClient, gymId: string, instanceId: string) { const gym = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: true }, }); if (!gym) throw notFound('Gym not found'); const link = gym.equipment.find((e) => e.id === instanceId); if (!link) throw badRequest('Equipment not found in this gym'); await prisma.gymEquipment.delete({ where: { id: instanceId } }); removeEquipmentPhotoFiles(gymId, instanceId); const updated = await prisma.gym.findUnique({ where: { id: gymId }, include: { equipment: { include: { equipment: true } } }, }); return { gym: updated, equipmentId: link.equipmentId }; } /** * Strażnik „ostatniego roles:manage" (uogólnienie dawnego assertNotLastAdmin * na granty ról) żyje w services/roles.ts; stąd korzystają deleteUser/ * updateUser oraz endpointy ról. */ export async function listUsers( prisma: PrismaClient, search?: string, viewerPermissions: readonly string[] = [], ) { const term = search?.toLowerCase(); const hasPii = viewerPermissions.includes(PERMISSIONS.PII_READ); const textFilters: Prisma.UserWhereInput[] = [ { firstName: { contains: term ?? '', mode: 'insensitive' } }, { lastName: { contains: term ?? '', mode: 'insensitive' } }, ]; // Bez `pii:read` e-mail jest maskowany w odpowiedzi — szukanie po nim // pozwalałoby zgadywać adresy obcych kont (odcinamy). if (hasPii) textFilters.push({ email: { contains: term ?? '', mode: 'insensitive' as const } }); const users = await prisma.user.findMany({ where: term ? { OR: textFilters } : undefined, include: { memberships: { include: { gym: true } }, roleGrants: PLATFORM_GRANTS_INCLUDE, }, orderBy: { createdAt: 'desc' }, }); const keysByPair = new Map(); if (users.length > 0) { const grants = await prisma.userRoleGrant.findMany({ where: { userId: { in: users.map((u) => u.id) }, gymId: { not: null } }, select: { userId: true, gymId: true, role: { select: { key: true } } }, }); for (const g of grants) { const k = `${g.userId}|${g.gymId}`; const list = keysByPair.get(k); if (list) list.push(g.role.key); else keysByPair.set(k, [g.role.key]); } } return { users: users.map((u) => redactUserDto( { ...publicUser(u), memberships: u.memberships.map((m) => ({ gymId: m.gymId, roles: deriveMembershipRoles(keysByPair.get(`${u.id}|${m.gymId}`) ?? [], true), gym: m.gym, })), }, viewerPermissions, ), ), }; } /** `YYYY-MM-DD` → północ UTC; null = wyczyść; undefined = nie zmieniaj. */ function toPrismaBirthDate(value: string | null | undefined) { if (value === undefined) return undefined; if (value === null) return null; return new Date(value); } export async function createUser( prisma: PrismaClient, data: CreateUserInput, viewerPermissions: readonly string[] = [], ) { const existing = await prisma.user.findUnique({ where: { email: data.email.toLowerCase() }, }); if (existing) throw conflict('Email already registered'); const passwordHash = await bcrypt.hash(data.password, 10); const user = await prisma.user.create({ data: { email: data.email.toLowerCase(), passwordHash, firstName: data.firstName, lastName: data.lastName, birthDate: toPrismaBirthDate(data.birthDate), }, include: { roleGrants: PLATFORM_GRANTS_INCLUDE }, }); return { user: redactUserDto(publicUser(user), viewerPermissions) }; } export async function updateUser( prisma: PrismaClient, id: string, data: UpdateUserInput, opts: { actorId?: string; permissions?: readonly string[] } = {}, ) { const viewerPermissions = opts.permissions ?? []; const user = await prisma.user.findUnique({ where: { id } }); if (!user) throw notFound('User not found'); // anty-eskalacja: jakakolwiek mutacja konta z grantem platformowym wymaga roles:manage await assertNotStaffTarget(prisma, id, viewerPermissions); // bez pii:read pola PII są nieakceptowalne (nawet null — czyściec też jest zmianą) if ( !viewerPermissions.includes(PERMISSIONS.PII_READ) && (data.email !== undefined || data.phone !== undefined || data.birthDate !== undefined) ) { throw new AppError(403, 'PII_FORBIDDEN', 'Missing permission: pii:read'); } const email = data.email?.toLowerCase(); if (email && email !== user.email) { const existing = await prisma.user.findUnique({ where: { email } }); if (existing) throw conflict('Email already registered'); } const phone = data.phone; if (phone && phone !== user.phone) { const phoneOwner = await prisma.user.findUnique({ where: { phone } }); if (phoneOwner) throw conflict('Phone already registered'); } const statusChanged = data.status !== undefined && data.status !== user.status; const passwordHash = data.password ? await bcrypt.hash(data.password, 10) : undefined; const muscles = data.developMuscles !== undefined || data.canDoMuscles !== undefined || data.difficultMuscles !== undefined || data.avoidMuscles !== undefined ? resolveMuscleConflicts( { developMuscles: user.developMuscles, canDoMuscles: user.canDoMuscles, difficultMuscles: user.difficultMuscles, avoidMuscles: user.avoidMuscles, }, data, ) : {}; const updated = await prisma.user.update({ where: { id: user.id }, include: { roleGrants: PLATFORM_GRANTS_INCLUDE }, data: { email, firstName: data.firstName, lastName: data.lastName, nickname: data.nickname, socialMedia: toPrismaJson(data.socialMedia), birthDate: toPrismaBirthDate(data.birthDate), heightCm: data.heightCm, phone: data.phone, passwordHash, // kara czyści się przy przywróceniu; zmiana statusu wygłasza aktywne sesje status: data.status, suspensionUntil: data.status === 'ACTIVE' ? null : data.suspensionUntil ? new Date(data.suspensionUntil) : undefined, restrictionReason: data.status === 'ACTIVE' ? null : (data.restrictionReason ?? undefined), availability: toPrismaAvailability(data.availability), priorities: data.priorities, exclusions: data.exclusions, ...muscles, ...(statusChanged ? { tokenVersion: { increment: 1 } } : {}), }, }); return { user: redactUserDto(publicUser(updated), viewerPermissions) }; } export async function deleteUser( prisma: PrismaClient, id: string, opts: { actorId?: string; permissions?: readonly string[] } = {}, ) { if (opts.actorId && opts.actorId === id) throw forbidden('You cannot delete your own account'); const target = await prisma.user.findUnique({ where: { id }, select: { email: true } }); if (!target) throw notFound('User not found'); await assertNotStaffTarget(prisma, id, opts.permissions ?? []); await assertTargetNotLastRolesManager(prisma, id); try { await prisma.user.delete({ where: { id } }); } catch (e) { if (isPrismaNotFound(e)) throw notFound('User not found'); throw e; } return { email: target.email }; } /** * Wymiana systemowych ról gymowych (OWNER/TRAINER) na granty; custom role * ( Role.gymId = gymId) zostają nietknięte. Zwraca true, jeśli coś się zmieniło. */ async function syncSystemGymRoles( tx: Prisma.TransactionClient, gymId: string, userId: string, roles: MembershipRole[], ): Promise { const keys = [ROLE_KEYS.GYM_OWNER, ROLE_KEYS.GYM_TRAINER]; const roleRows = await tx.role.findMany({ where: { key: { in: keys } }, select: { id: true, key: true }, }); const byKey = new Map(roleRows.map((r) => [r.key, r.id])); const wanted = new Set(); if (roles.includes('OWNER')) wanted.add(ROLE_KEYS.GYM_OWNER); if (roles.includes('TRAINER')) wanted.add(ROLE_KEYS.GYM_TRAINER); const current = await tx.userRoleGrant.findMany({ where: { userId, gymId, role: { key: { in: keys } } }, include: { role: { select: { key: true } } }, }); const currentKeys = new Set(current.map((g) => g.role.key)); let changed = false; for (const g of current) { if (!wanted.has(g.role.key)) { await tx.userRoleGrant.delete({ where: { id: g.id } }); changed = true; } } for (const key of wanted) { if (!currentKeys.has(key)) { const roleId = byKey.get(key); if (!roleId) throw new AppError(500, 'ROLE_SEED_MISSING', `System role ${key} missing`); await tx.userRoleGrant.create({ data: { userId, roleId, gymId } }); changed = true; } } return changed; } export async function addMembership( prisma: PrismaClient, userId: string, gymId: string, roles: MembershipRole[], ) { const gym = await prisma.gym.findUnique({ where: { id: gymId } }); if (!gym) throw notFound('Gym not found'); const user = await prisma.user.findUnique({ where: { id: userId } }); if (!user) throw notFound('User not found'); const existing = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId: user.id, gymId } }, }); if (existing) throw conflict('Membership already exists'); const membership = await prisma.$transaction(async (tx) => { const created = await tx.gymMembership.create({ data: { userId: user.id, gymId }, }); const changed = await syncSystemGymRoles(tx, gymId, user.id, roles); if (changed) { await tx.user.update({ where: { id: user.id }, data: { tokenVersion: { increment: 1 } }, }); } return created; }); return { membership: { ...membership, roles } }; } export async function updateMembership( prisma: PrismaClient, userId: string, gymId: string, roles: MembershipRole[], ) { const membership = await prisma.gymMembership.findUnique({ where: { userId_gymId: { userId, gymId } }, }); if (!membership) throw notFound('Membership not found'); const updated = await prisma.$transaction(async (tx) => { const changed = await syncSystemGymRoles(tx, gymId, userId, roles); if (changed) { await tx.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } }); } return tx.gymMembership.findUniqueOrThrow({ where: { id: membership.id } }); }); return { membership: { ...updated, roles } }; } export async function removeMembership(prisma: PrismaClient, userId: string, gymId: string) { try { return await prisma.$transaction(async (tx) => { const grants = await tx.userRoleGrant.findMany({ where: { userId, gymId }, select: { role: { select: { key: true } } }, }); const removed = await tx.gymMembership.delete({ where: { userId_gymId: { userId, gymId } }, }); // granty gymowe bez członkostwa są bezużyteczne — sprzątamy je razem z wierszem await tx.userRoleGrant.deleteMany({ where: { userId, gymId } }); const keys = grants.map((g) => g.role.key); return { membership: { ...removed, roles: deriveMembershipRoles(keys, true) } }; }); } catch (e) { if (isPrismaNotFound(e)) throw badRequest('Membership not found'); throw e; } } // ---------- gym claims (admin verification) ---------- export type ClaimStatus = 'PENDING' | 'APPROVED' | 'REJECTED'; /** List gym claims (both types), PENDING first, then createdAt desc. Opcjonalny filtr po statusie i użytkowniku. */ export async function listGymClaims(prisma: PrismaClient, status?: ClaimStatus, userId?: string) { const claims = await prisma.gymClaim.findMany({ where: status || userId ? { ...(status ? { status } : {}), ...(userId ? { userId } : {}) } : undefined, include: { gym: { select: { id: true, name: true, kind: true, isPrivate: true } }, user: { select: { id: true, firstName: true, lastName: true, email: true } }, _count: { select: { documents: true } }, }, }); claims.sort( (a, b) => Number(a.status !== 'PENDING') - Number(b.status !== 'PENDING') || b.createdAt.getTime() - a.createdAt.getTime(), ); return { claims: claims.map((c) => ({ id: c.id, gymId: c.gymId, type: c.gymId ? ('verification' as const) : ('new' as const), gym: c.gym ? { id: c.gym.id, name: c.gym.name, kind: c.gym.kind, isPrivate: c.gym.isPrivate } : null, gymName: c.gymName, gymLocation: c.gymLocation, description: c.description, companyName: c.companyName, nip: c.nip, phone: c.phone, email: c.email, address: c.address, status: c.status, rejectReason: c.rejectReason, createdAt: c.createdAt.toISOString(), user: { id: c.user.id, firstName: c.user.firstName, lastName: c.user.lastName, email: c.user.email, }, documentCount: c._count.documents, })), }; } /** Full claim detail (admin): claim + gym + user + documents. */ export async function getGymClaim(prisma: PrismaClient, claimId: string) { const claim = await prisma.gymClaim.findUnique({ where: { id: claimId }, include: { gym: { select: { id: true, name: true, kind: true, isPrivate: true } }, user: { select: { id: true, firstName: true, lastName: true, email: true, phone: true } }, documents: { select: { id: true, originalName: true, storedName: true, mimeType: true, sizeBytes: true, createdAt: true, }, }, }, }); if (!claim) throw notFound('Claim not found'); return { claim: { id: claim.id, gymId: claim.gymId, type: claim.gymId ? ('verification' as const) : ('new' as const), gym: claim.gym ? { id: claim.gym.id, name: claim.gym.name, kind: claim.gym.kind, isPrivate: claim.gym.isPrivate, } : null, gymName: claim.gymName, gymLocation: claim.gymLocation, gymAvailability: claim.gymAvailability, gymCapacity: claim.gymCapacity, description: claim.description, companyName: claim.companyName, nip: claim.nip, phone: claim.phone, email: claim.email, address: claim.address, status: claim.status, rejectReason: claim.rejectReason, decidedAt: claim.decidedAt ? claim.decidedAt.toISOString() : null, createdAt: claim.createdAt.toISOString(), user: { id: claim.user.id, firstName: claim.user.firstName, lastName: claim.user.lastName, email: claim.user.email, phone: claim.user.phone, }, documents: claim.documents.map((d) => ({ id: d.id, originalName: d.originalName, mimeType: d.mimeType, sizeBytes: d.sizeBytes, createdAt: d.createdAt.toISOString(), })), }, }; } /** * Approve a PENDING claim (transaction): * - verification: gym → REAL + public, applicant → OWNER, other owners → MEMBER, * other pending claims for the gym → REJECTED, address overrides gym.location; * - new real: creates a REAL gym from the claim data, applicant → OWNER, * claim.gymId → the new gym. */ export async function approveGymClaim(prisma: PrismaClient, adminId: string, claimId: string) { await prisma.$transaction(async (tx) => { const claim = await tx.gymClaim.findUnique({ where: { id: claimId } }); if (!claim) throw notFound('Claim not found'); if (claim.status !== 'PENDING') throw conflict('Claim is not pending'); if (claim.gymId) { const gym = await tx.gym.findUnique({ where: { id: claim.gymId } }); if (!gym) throw notFound('Gym not found'); if (gym.kind !== 'VIRTUAL') throw conflict('Only virtual gyms can be verified'); await tx.gym.update({ where: { id: gym.id }, data: { kind: 'REAL', isPrivate: false, ...(claim.address ? { location: claim.address } : {}), }, }); const membership = await tx.gymMembership.findUnique({ where: { userId_gymId: { userId: claim.userId, gymId: gym.id } }, select: { id: true }, }); if (!membership) { await tx.gymMembership.create({ data: { userId: claim.userId, gymId: gym.id } }); } await grantGymOwner(tx, gym.id, claim.userId); // pozostali właściciele tracą grant GYM_OWNER (członkostwa zostają) const ownerRole = await tx.role.findUnique({ where: { key: ROLE_KEYS.GYM_OWNER }, select: { id: true }, }); if (ownerRole) { await tx.userRoleGrant.deleteMany({ where: { gymId: gym.id, userId: { not: claim.userId }, roleId: ownerRole.id }, }); } // po approve zatwierdzający jest już właścicielem; uprawnienia czytanymi z DB per request — // bez bumpa tokenVersion (semantyka legacy: nie wygaszamy sesji applicantowi) await tx.gymClaim.updateMany({ where: { gymId: gym.id, status: 'PENDING', id: { not: claim.id } }, data: { status: 'REJECTED', rejectReason: 'Zatwierdzono inny wniosek', decidedById: adminId, decidedAt: new Date(), }, }); } else { const gym = await tx.gym.create({ data: { name: claim.gymName!, location: claim.gymLocation!, availability: claim.gymAvailability === null ? Prisma.DbNull : claim.gymAvailability, capacity: claim.gymCapacity, kind: 'REAL', isPrivate: false, }, }); await tx.gymMembership.create({ data: { userId: claim.userId, gymId: gym.id }, }); await grantGymOwner(tx, gym.id, claim.userId); await tx.gymClaim.update({ where: { id: claim.id }, data: { gymId: gym.id } }); } await tx.gymClaim.update({ where: { id: claim.id }, data: { status: 'APPROVED', decidedById: adminId, decidedAt: new Date() }, }); }); } /** Reject a PENDING claim with an optional reason. */ export async function rejectGymClaim( prisma: PrismaClient, adminId: string, claimId: string, reason?: string, ) { const claim = await prisma.gymClaim.findUnique({ where: { id: claimId } }); if (!claim) throw notFound('Claim not found'); if (claim.status !== 'PENDING') throw conflict('Claim is not pending'); await prisma.gymClaim.update({ where: { id: claimId }, data: { status: 'REJECTED', rejectReason: reason?.trim() ? reason.trim() : null, decidedById: adminId, decidedAt: new Date(), }, }); }