Files
FitOS/api/src/services/admin.ts

765 lines
26 KiB
TypeScript

import bcrypt from 'bcryptjs';
import { Prisma, type GymRole, type PrismaClient } from '@prisma/client';
import { validateEquipmentSpec } from '../lib/equipmentSpec.js';
import { isPrismaNotFound } from '../lib/prisma.js';
import { publicUser } from '../lib/publicUser.js';
import { badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import {
removeEquipmentPhotoFiles,
removeGymClaimFiles,
removeGymPhotoFiles,
} from '../lib/uploads.js';
import {
availabilityChanged,
gymPhotoUrl,
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;
age?: number;
isAdmin?: boolean;
}
export interface UpdateUserInput {
email?: string;
firstName?: string | null;
lastName?: string | null;
nickname?: string | null;
socialMedia?: SocialMediaEntry[] | null;
age?: number | null;
heightCm?: number | null;
phone?: string | null;
isAdmin?: boolean;
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 async function listGyms(prisma: PrismaClient) {
const gyms = await prisma.gym.findMany({
orderBy: { name: 'asc' },
include: {
_count: { select: { memberships: true } },
equipment: {
include: { equipment: true },
orderBy: { equipment: { name: 'asc' } },
},
photos: {
orderBy: [{ order: 'asc' }, { createdAt: 'asc' }],
take: 1,
},
},
});
return {
gyms: gyms.map((g) => {
const { photos, ...rest } = g;
return { ...rest, coverPhoto: photos[0] ? gymPhotoUrl(g.id, photos[0].id) : null };
}),
};
}
export async function getGym(prisma: PrismaClient, gymId: 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 } },
memberships: {
where: { roles: { has: 'OWNER' } },
include: { user: { select: { id: true, firstName: true, lastName: true, email: true } } },
orderBy: { user: { createdAt: 'asc' } },
},
},
});
if (!gym) throw Object.assign(new Error('Nie znaleziono siłowni'), { status: 404 });
const { memberships, equipment, ...rest } = gym;
return {
...rest,
equipment: mapEquipmentPhotoDtos(gymId, equipment),
owners: memberships.map((m) => m.user),
};
}
/** Nadaje użytkownikowi rolę OWNER (admin): tworzy członkostwo albo dopisuje rolę. */
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);
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
if (membership) {
if (membership.roles.includes('OWNER')) return { membership };
const updated = await prisma.gymMembership.update({
where: { id: membership.id },
data: { roles: ['OWNER', ...membership.roles] },
});
return { membership: updated };
}
const created = await prisma.gymMembership.create({
data: { userId, gymId, roles: ['OWNER'] },
});
return { membership: created };
}
/** Zdejmuje rolę OWNER (admin); usuwa członkostwo, gdy nie zostanie żadna rola. */
export async function removeGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
if (!membership || !membership.roles.includes('OWNER')) throw notFound('Gym owner not found');
const roles = membership.roles.filter((r) => r !== 'OWNER');
if (roles.length === 0) {
await prisma.gymMembership.delete({ where: { id: membership.id } });
} else {
await prisma.gymMembership.update({ where: { id: membership.id }, data: { roles } });
}
}
/** 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, roles: ['OWNER'] },
});
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 admina”: nie pozwala odebrać roli (lub usunąć konto)
* jedynemu administratorowi — panel straciłby dostęp na stałe (brak UI do
* odzyskiwania). Próba samodegradacji/self-deletion wpada w ten sam warunek,
* gdy w systemie zostaje zero innych adminów.
*/
async function assertNotLastAdmin(prisma: PrismaClient, targetId: string, actorId?: string) {
const otherAdmins = await prisma.user.count({
where: { isAdmin: true, id: { not: targetId } },
});
if (otherAdmins === 0) {
throw forbidden(
actorId === targetId
? 'You cannot remove the last admin role from yourself'
: 'Cannot remove the last admin role',
);
}
}
export async function listUsers(prisma: PrismaClient, search?: string) {
const term = search?.toLowerCase();
const users = await prisma.user.findMany({
where: term
? {
OR: [
{ email: { contains: term, mode: 'insensitive' } },
{ firstName: { contains: term, mode: 'insensitive' } },
{ lastName: { contains: term, mode: 'insensitive' } },
],
}
: undefined,
include: { memberships: { include: { gym: true } } },
orderBy: { createdAt: 'desc' },
});
return {
users: users.map((u) => ({
...publicUser(u),
memberships: u.memberships.map((m) => ({
gymId: m.gymId,
roles: m.roles,
gym: m.gym,
})),
})),
};
}
export async function createUser(prisma: PrismaClient, data: CreateUserInput) {
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,
age: data.age,
isAdmin: data.isAdmin ?? false,
},
});
return { user: publicUser(user) };
}
export async function updateUser(
prisma: PrismaClient,
id: string,
data: UpdateUserInput,
actorId?: string,
) {
const user = await prisma.user.findUnique({ where: { id } });
if (!user) throw notFound('User not found');
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 roleChanged = data.isAdmin !== undefined && data.isAdmin !== user.isAdmin;
const statusChanged = data.status !== undefined && data.status !== user.status;
if (roleChanged && data.isAdmin === false) {
await assertNotLastAdmin(prisma, id, actorId);
}
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 },
data: {
email,
firstName: data.firstName,
lastName: data.lastName,
nickname: data.nickname,
socialMedia: toPrismaJson(data.socialMedia),
age: data.age,
heightCm: data.heightCm,
phone: data.phone,
isAdmin: data.isAdmin,
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,
...(roleChanged || statusChanged ? { tokenVersion: { increment: 1 } } : {}),
},
});
return { user: publicUser(updated) };
}
export async function deleteUser(prisma: PrismaClient, id: string, actorId?: string) {
if (actorId && actorId === id) throw forbidden('You cannot delete your own account');
const target = await prisma.user.findUnique({
where: { id },
select: { isAdmin: true, email: true },
});
if (target?.isAdmin) await assertNotLastAdmin(prisma, id, actorId);
try {
await prisma.user.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('User not found');
throw e;
}
return { email: target?.email ?? null };
}
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.gymMembership.create({
data: { userId: user.id, gymId, roles },
});
return { membership };
}
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.gymMembership.update({
where: { userId_gymId: { userId, gymId } },
data: { roles },
});
return { membership: updated };
}
export async function removeMembership(prisma: PrismaClient, userId: string, gymId: string) {
try {
const removed = await prisma.gymMembership.delete({
where: { userId_gymId: { userId, gymId } },
});
return { membership: removed };
} 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 } },
});
if (membership) {
const roles: GymRole[] = membership.roles.includes('OWNER')
? membership.roles
: ['OWNER', ...membership.roles];
await tx.gymMembership.update({ where: { id: membership.id }, data: { roles } });
} else {
await tx.gymMembership.create({
data: { userId: claim.userId, gymId: gym.id, roles: ['OWNER'] },
});
}
const otherOwners = await tx.gymMembership.findMany({
where: { gymId: gym.id, userId: { not: claim.userId }, roles: { has: 'OWNER' } },
});
for (const m of otherOwners) {
const roles = m.roles.filter((r) => r !== 'OWNER');
await tx.gymMembership.update({
where: { id: m.id },
data: { roles: roles.length > 0 ? roles : ['MEMBER'] },
});
}
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, roles: ['OWNER'] },
});
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(),
},
});
}