Refaktoryzacja struktury i podział modułów (app/admin/api), konsolidacja testów w test/, komunikator (lista kontaktów, załącznik bez treści), profil podopiecznego (menu kontekstowe, nagłówek, zapamiętywanie zakładki), Tabs: strzałki poza scrollem + scroll-snap do całych zakładek, podniesione limity rate-limit

This commit is contained in:
tisachi
2026-09-04 23:19:28 +02:00
parent 1c8594ad96
commit e0f70ffa58
144 changed files with 5283 additions and 4788 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,178 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Prisma, PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { logger } from '../../lib/logger.js';
import { claimUploadDir, removeClaimFiles, storedFileName } from '../../lib/uploads.js';
import { toPrismaAvailability, type Availability } from '../me.js';
export interface GymClaimInput {
/** Set = verification of that virtual gym; absent = claim for a NEW real gym. */
gymId?: string;
description: string;
companyName?: string;
nip?: string;
phone?: string;
email?: string;
/** Verification claims only: overrides gym.location on approval. */
address?: string;
/** New-real claims only: */
gymName?: string;
gymLocation?: string;
gymAvailability?: Availability | null;
gymCapacity?: number;
}
export interface UploadedClaimFile {
originalName: string;
mimeType: string;
sizeBytes: number;
/** Temp path (multer) — moved into the per-claim directory. */
path: string;
}
type ClaimWithRelations = Prisma.GymClaimGetPayload<{
include: {
gym: { select: { id: true; name: true; kind: true; isPrivate: true } };
documents: {
select: { id: true; originalName: true; mimeType: true; sizeBytes: true; createdAt: true };
};
};
}>;
export function claimToDto(c: ClaimWithRelations) {
return {
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,
gymAvailability: c.gymAvailability,
gymCapacity: c.gymCapacity,
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(),
updatedAt: c.updatedAt.toISOString(),
documents: c.documents.map((d) => ({
id: d.id,
originalName: d.originalName,
mimeType: d.mimeType,
sizeBytes: d.sizeBytes,
createdAt: d.createdAt.toISOString(),
})),
};
}
/**
* Create a gym claim (multipart). gymId set → verification of a virtual gym;
* absent → claim for a new real gym (gymName/gymLocation required).
* Files are moved from the temp dir into UPLOAD_DIR/<claimId>/.
*/
export async function createGymClaim(
prisma: PrismaClient,
userId: string,
data: GymClaimInput,
files: UploadedClaimFile[],
) {
if (data.gymId) {
const gym = await prisma.gym.findUnique({ where: { id: data.gymId } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL') throw conflict('Only virtual gyms can be verified');
const pending = await prisma.gymClaim.findFirst({
where: { gymId: data.gymId, userId, status: 'PENDING' },
select: { id: true },
});
if (pending) throw conflict('You already have a pending claim for this gym');
} else {
if (!data.gymName?.trim()) throw badRequest('Gym name is required');
if (!data.gymLocation?.trim()) throw badRequest('Gym location is required');
}
const claim = await prisma.gymClaim.create({
data: {
gymId: data.gymId ?? null,
userId,
gymName: data.gymId ? null : data.gymName?.trim() ?? null,
gymLocation: data.gymId ? null : data.gymLocation?.trim() ?? null,
gymAvailability: data.gymId ? undefined : toPrismaAvailability(data.gymAvailability ?? null),
gymCapacity: data.gymId ? null : data.gymCapacity ?? null,
description: data.description,
companyName: data.companyName ?? null,
nip: data.nip ?? null,
phone: data.phone ?? null,
email: data.email ?? null,
address: data.address ?? null,
},
});
if (files.length > 0) {
const claimDir = claimUploadDir(claim.id);
try {
fs.mkdirSync(claimDir, { recursive: true });
for (const f of files) {
const storedName = storedFileName(f.mimeType);
fs.renameSync(f.path, path.join(claimDir, storedName));
await prisma.gymClaimDocument.create({
data: {
claimId: claim.id,
originalName: f.originalName,
storedName,
mimeType: f.mimeType,
sizeBytes: f.sizeBytes,
},
});
}
} catch (e) {
// storage failure: roll the claim back and clean up moved/temp files
await prisma.gymClaim.delete({ where: { id: claim.id } }).catch(() => undefined);
removeClaimFiles(claim.id);
logger.error({ err: e, claimId: claim.id }, 'Failed to store claim files');
throw new AppError(500, 'UPLOAD_FAILED', 'Failed to store uploaded files');
}
}
const created = await prisma.gymClaim.findUnique({
where: { id: claim.id },
include: {
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
documents: {
select: { id: true, originalName: true, mimeType: true, sizeBytes: true, createdAt: true },
},
},
});
return { claim: claimToDto(created!) };
}
/** The user's own claims (all statuses, newest first). */
export async function listMyGymClaims(prisma: PrismaClient, userId: string) {
const claims = await prisma.gymClaim.findMany({
where: { userId },
include: {
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
documents: {
select: { id: true, originalName: true, mimeType: true, sizeBytes: true, createdAt: true },
},
},
orderBy: { createdAt: 'desc' },
});
return { claims: claims.map(claimToDto) };
}
/** Withdraw the user's own PENDING claim (files removed best-effort). */
export async function withdrawGymClaim(prisma: PrismaClient, userId: string, claimId: string) {
const claim = await prisma.gymClaim.findUnique({ where: { id: claimId } });
if (!claim) throw notFound('Claim not found');
if (claim.userId !== userId) throw forbidden('Only the claim author can withdraw it');
if (claim.status !== 'PENDING') throw conflict('Only pending claims can be withdrawn');
await prisma.gymClaim.delete({ where: { id: claimId } });
removeClaimFiles(claimId);
}

View File

@@ -0,0 +1,266 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { isPrismaNotFound } from '../../lib/prisma.js';
import { removeGymClaimFiles, removeGymPhotoFiles } from '../../lib/uploads.js';
import { toPrismaAvailability, type Availability } from '../me.js';
import { gymCoverInclude, gymEquipmentInclude } from './includes.js';
import { coverUrlOf } from './photos.js';
export type GymKind = 'VIRTUAL' | 'REAL';
export interface CreateGymInput {
name: string;
location?: string | null;
availability?: Availability | null;
capacity?: number | null;
kind?: GymKind;
isPrivate?: boolean;
}
export interface UpdateGymInput {
name?: string;
location?: string | null;
availability?: Availability | null;
capacity?: number | null;
isPrivate?: boolean;
}
export async function listUserGyms(prisma: PrismaClient, userId: string) {
const memberships = await prisma.gymMembership.findMany({
where: { userId },
include: { gym: { include: { ...gymEquipmentInclude, ...gymCoverInclude } } },
orderBy: { gym: { name: 'asc' } },
});
return {
gyms: memberships.map((m) => {
const { photos, ...gym } = m.gym;
return { ...gym, coverPhoto: coverUrlOf(gym.id, photos), roles: m.roles };
}),
};
}
/** All REAL gyms in the system (for selecting an existing gym). */
export async function listAllGyms(prisma: PrismaClient) {
const gyms = await prisma.gym.findMany({
where: { kind: 'REAL' },
include: { ...gymEquipmentInclude, ...gymCoverInclude },
orderBy: { name: 'asc' },
});
return {
gyms: gyms.map((g) => {
const { photos, ...rest } = g;
return { ...rest, coverPhoto: coverUrlOf(g.id, photos) };
}),
};
}
/**
* Public virtual gyms (with rating counts, the caller's vote and claim status)
* plus the caller's own private virtual gyms (no rating fields).
* Public: score (up-down) desc, then name asc; own private last, by name.
*/
export async function listVirtualGyms(prisma: PrismaClient, userId: string) {
const [publicGyms, privateGyms, claims, myRatings] = await Promise.all([
prisma.gym.findMany({
where: { kind: 'VIRTUAL', isPrivate: false },
include: { ...gymEquipmentInclude, ratings: true, _count: { select: { memberships: true } } },
}),
prisma.gym.findMany({
where: {
kind: 'VIRTUAL',
isPrivate: true,
memberships: { some: { userId, roles: { has: 'OWNER' } } },
},
include: { ...gymEquipmentInclude, _count: { select: { memberships: true } } },
}),
prisma.gymClaim.findMany({
where: { userId, status: { in: ['PENDING', 'REJECTED'] } },
select: { gymId: true, status: true, rejectReason: true },
orderBy: { createdAt: 'desc' },
}),
prisma.gymRating.findMany({
where: { userId },
select: { gymId: true, vote: true },
}),
]);
const myVoteByGym = new Map(myRatings.map((r) => [r.gymId, r.vote]));
const claimByGym = new Map<string, { status: string; rejectReason: string | null }>();
for (const c of claims) {
if (c.gymId && !claimByGym.has(c.gymId)) claimByGym.set(c.gymId, c);
}
const publicList = publicGyms.map((g) => {
const up = g.ratings.filter((r) => r.vote === 'UP').length;
const down = g.ratings.filter((r) => r.vote === 'DOWN').length;
const claim = claimByGym.get(g.id);
return {
id: g.id,
name: g.name,
location: g.location,
availability: g.availability,
capacity: g.capacity,
kind: g.kind,
isPrivate: g.isPrivate,
equipment: g.equipment,
memberCount: g._count.memberships,
up,
down,
myVote: myVoteByGym.get(g.id) ?? null,
claimStatus: claim?.status ?? null,
rejectReason: claim?.status === 'REJECTED' ? claim.rejectReason ?? null : null,
};
});
publicList.sort(
(a, b) => b.up - b.down - (a.up - a.down) || a.name.localeCompare(b.name, 'pl'),
);
const privateList = privateGyms
.map((g) => ({ ...g, isPrivate: true, memberCount: g._count.memberships }))
.sort((a, b) => a.name.localeCompare(b.name, 'pl'));
return { gyms: [...publicList, ...privateList] };
}
/**
* Thumb vote on a public virtual gym (how well it mirrors the real one).
* Upsert with toggle: the same vote again removes it. The owner cannot vote.
*/
export async function rateGym(
prisma: PrismaClient,
userId: string,
gymId: string,
vote: 'UP' | 'DOWN',
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL' || gym.isPrivate)
throw conflict('Only public virtual gyms can be rated');
const isOwner = await prisma.gymMembership.findFirst({
where: { gymId, userId, roles: { has: 'OWNER' } },
});
if (isOwner) throw forbidden('The gym owner cannot rate their own gym');
const existing = await prisma.gymRating.findUnique({
where: { gymId_userId: { gymId, userId } },
});
if (existing?.vote === vote) {
await prisma.gymRating.delete({ where: { id: existing.id } });
} else {
await prisma.gymRating.upsert({
where: { gymId_userId: { gymId, userId } },
update: { vote },
create: { gymId, userId, vote },
});
}
const [up, down] = await Promise.all([
prisma.gymRating.count({ where: { gymId, vote: 'UP' } }),
prisma.gymRating.count({ where: { gymId, vote: 'DOWN' } }),
]);
return { vote: existing?.vote === vote ? null : vote, up, down };
}
/** Join an existing gym (creates a MEMBER membership). */
export async function joinGym(prisma: PrismaClient, userId: string, gymId: string) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
const existing = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
if (existing) throw conflict('Already a member of this gym');
const membership = await prisma.gymMembership.create({
data: { userId, gymId, roles: ['MEMBER'] },
});
return { membership: { gymId, name: gym.name, roles: membership.roles } };
}
/**
* Create a gym; the creator becomes its OWNER.
* Non-admins can only create VIRTUAL gyms (location required); passing REAL → 403.
* Admins pick the kind (default VIRTUAL); isPrivate is only allowed for VIRTUAL.
*/
export async function createGym(
prisma: PrismaClient,
userId: string,
data: CreateGymInput,
isAdmin: boolean,
) {
let kind: GymKind = data.kind ?? 'VIRTUAL';
if (!isAdmin) {
if (kind === 'REAL') throw forbidden('Only admins can create real gyms');
kind = 'VIRTUAL';
}
if (kind === 'VIRTUAL' && !data.location?.trim())
throw badRequest('Location is required for virtual gyms');
const isPrivate = data.isPrivate ?? false;
if (kind === 'REAL' && isPrivate) throw badRequest('Real gyms are always public');
const gym = await prisma.gym.create({
data: {
name: data.name,
location: data.location ?? null,
availability: toPrismaAvailability(data.availability ?? null),
capacity: data.capacity ?? null,
kind,
isPrivate,
},
});
await prisma.gymMembership.create({
data: { userId, gymId: gym.id, roles: ['OWNER'] },
});
return { gym: { ...gym, roles: ['OWNER'] } };
}
export async function assertGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { memberships: { where: { userId } }, equipment: true },
});
if (!gym) throw notFound('Gym not found');
const isOwner = gym.memberships.some((m) => m.roles.includes('OWNER'));
if (!isOwner) throw forbidden('Only the gym owner can manage this gym');
return gym;
}
/** Update a gym's data (owner only). isPrivate is only allowed for VIRTUAL gyms. */
export async function updateOwnedGym(
prisma: PrismaClient,
gymId: string,
userId: string,
data: UpdateGymInput,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
if (data.isPrivate === true && gym.kind === 'REAL')
throw badRequest('Real gyms are always public');
try {
const { availability, ...rest } = data;
const updated = await prisma.gym.update({
where: { id: gymId },
data: { ...rest, availability: toPrismaAvailability(availability) },
});
return { gym: updated };
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
throw e;
}
}
/** Delete a gym (owner only). Memberships are removed; user plans are kept. */
export async function deleteOwnedGym(prisma: PrismaClient, gymId: string, userId: string) {
const gym = await assertGymOwner(prisma, gymId, userId);
const claimIds = await listGymClaimIds(prisma, gymId);
try {
await prisma.gym.delete({ where: { id: gymId } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
throw e;
}
await removeGymClaimFiles(claimIds);
removeGymPhotoFiles(gymId);
return { name: gym.name };
}
export async function listGymClaimIds(prisma: PrismaClient, gymId: string): Promise<string[]> {
const claims = await prisma.gymClaim.findMany({
where: { gymId },
select: { id: true },
});
return claims.map((c) => c.id);
}

View File

@@ -0,0 +1,175 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, conflict, notFound } from '../../lib/errors.js';
import { isPrismaUnique } from '../../lib/prisma.js';
import { toPrismaJson, type DayAvailability } from '../me.js';
import { assertGymOwner } from './core.js';
import { gymEquipmentInclude } from './includes.js';
export interface CreateGymExceptionInput {
/** ISO date (YYYY-MM-DD) the exception applies to. */
date: string;
/** null = closed, { start, end } = different hours. */
availability: DayAvailability | null;
}
/** List a gym's upcoming schedule exceptions (owner only). */
export async function listOwnedGymExceptions(
prisma: PrismaClient,
gymId: string,
userId: string,
) {
await assertGymOwner(prisma, gymId, userId);
const exceptions = await prisma.gymException.findMany({
where: { gymId },
orderBy: { date: 'asc' },
});
return { exceptions };
}
/** Add a one-off schedule exception for a specific date (owner only). */
export async function createOwnedGymException(
prisma: PrismaClient,
gymId: string,
userId: string,
data: CreateGymExceptionInput,
) {
await assertGymOwner(prisma, gymId, userId);
const date = new Date(data.date);
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
try {
const exception = await prisma.gymException.create({
data: {
gymId,
date,
availability: toPrismaJson(data.availability),
},
});
return { exception };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
throw e;
}
}
/** Remove a schedule exception (owner only). */
export async function deleteOwnedGymException(
prisma: PrismaClient,
gymId: string,
userId: string,
exceptionId: string,
) {
await assertGymOwner(prisma, gymId, userId);
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
await prisma.gymException.delete({ where: { id: exceptionId } });
}
/** Add a catalog equipment item to a gym with a quantity (owner only). */
export async function addEquipment(
prisma: PrismaClient,
gymId: string,
userId: string,
equipmentId: string,
quantity = 1,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const item = await prisma.equipment.findUnique({ where: { id: equipmentId } });
if (!item) throw notFound('Equipment not found');
if (gym.equipment.some((e) => e.equipmentId === equipmentId))
throw conflict('Equipment already exists in this gym — update its quantity instead');
try {
await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } });
} catch (e) {
if (isPrismaUnique(e)) throw conflict('Equipment already exists in this gym — update its quantity instead');
throw e;
}
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: gymEquipmentInclude,
});
return { gym: updated };
}
/** Change the quantity of a gym's equipment item (owner only). */
export async function updateEquipmentQuantity(
prisma: PrismaClient,
gymId: string,
userId: string,
equipmentId: string,
quantity: number,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
if (!link) throw badRequest('Equipment not found in this gym');
await prisma.gymEquipment.update({ where: { id: link.id }, data: { quantity } });
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: gymEquipmentInclude,
});
return { gym: updated };
}
/** Remove a catalog equipment item from a gym (owner only). */
export async function removeEquipment(
prisma: PrismaClient,
gymId: string,
userId: string,
equipmentId: string,
) {
const gym = await assertGymOwner(prisma, gymId, userId);
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
if (!link) throw badRequest('Equipment not found in this gym');
await prisma.gymEquipment.delete({ where: { id: link.id } });
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: gymEquipmentInclude,
});
return { gym: updated };
}
/** List a gym's upcoming schedule exceptions. */
export async function listGymExceptions(prisma: PrismaClient, gymId: string) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
const exceptions = await prisma.gymException.findMany({
where: { gymId },
orderBy: { date: 'asc' },
});
return { exceptions };
}
/** Add a one-off schedule exception for a specific date. */
export async function createGymException(
prisma: PrismaClient,
gymId: string,
data: CreateGymExceptionInput,
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
const date = new Date(data.date);
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
try {
const exception = await prisma.gymException.create({
data: {
gymId,
date,
availability: toPrismaJson(data.availability),
},
});
return { exception };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
throw e;
}
}
/** Remove a schedule exception. */
export async function deleteGymException(
prisma: PrismaClient,
gymId: string,
exceptionId: string,
) {
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
await prisma.gymException.delete({ where: { id: exceptionId } });
}

View File

@@ -0,0 +1,20 @@
/** Gym equipment links with the catalog item, ordered by equipment name. */
export const gymEquipmentInclude = {
equipment: {
include: { equipment: true },
orderBy: { equipment: { name: 'asc' as const } },
},
};
/** Gallery photos, cover first (smallest order, tie → oldest). */
export const gymPhotosInclude = {
photos: { orderBy: [{ order: 'asc' as const }, { createdAt: 'asc' as const }] },
};
/** Only the cover photo (for lists). */
export const gymCoverInclude = {
photos: {
orderBy: [{ order: 'asc' as const }, { createdAt: 'asc' as const }],
take: 1,
},
};

View File

@@ -0,0 +1,199 @@
import type { PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { INVITATION_TTL_DAYS } from '../trainer.js';
async function assertGymOwnerOf(prisma: PrismaClient, gymId: string, userId: string): Promise<void> {
const membership = await prisma.gymMembership.findFirst({
where: { gymId, userId, roles: { has: 'OWNER' } },
select: { id: true },
});
if (!membership) throw forbidden('Only the gym owner can do this');
}
/**
* Invite a user to a PRIVATE virtual gym. Owner only. A re-invite after DECLINED
* updates the existing row (new invitedAt/expiresAt/invitedBy).
*/
export async function sendGymInvitation(
prisma: PrismaClient,
ownerId: string,
gymId: string,
userId: string,
) {
if (ownerId === userId) throw badRequest('Cannot invite yourself');
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL' || !gym.isPrivate)
throw conflict('Only private virtual gyms can receive invitations');
await assertGymOwnerOf(prisma, gymId, ownerId);
const target = await prisma.user.findUnique({ where: { id: userId } });
if (!target) throw notFound('User not found');
const member = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { id: true },
});
if (member) throw conflict('User is already a member of this gym');
const existing = await prisma.gymInvitation.findFirst({ where: { gymId, userId } });
if (existing?.status === 'PENDING') throw conflict('Invitation already exists');
const now = new Date();
const expiresAt = new Date(now.getTime() + INVITATION_TTL_DAYS * 24 * 60 * 60 * 1000);
const invitation = existing
? await prisma.gymInvitation.update({
where: { id: existing.id },
data: { status: 'PENDING', invitedAt: now, expiresAt, invitedById: ownerId },
})
: await prisma.gymInvitation.create({
data: { gymId, userId, invitedById: ownerId, expiresAt },
});
return { invitation };
}
/** Pending, not-expired gym invitations of the user — sent and received. */
export async function listGymInvitations(prisma: PrismaClient, userId: string) {
const now = new Date();
const invitations = await prisma.gymInvitation.findMany({
where: {
status: 'PENDING',
expiresAt: { gt: now },
OR: [{ userId }, { invitedById: userId }],
},
include: {
gym: { select: { id: true, name: true, location: true, kind: true, isPrivate: true } },
user: { select: { id: true, firstName: true, lastName: true, email: true } },
invitedBy: { select: { id: true, firstName: true, lastName: true, email: true } },
},
orderBy: { invitedAt: 'desc' },
});
return {
invitations: invitations.map((i) => {
const direction = i.invitedById === userId ? ('sent' as const) : ('received' as const);
return {
id: i.id,
direction,
gym: {
id: i.gym.id,
name: i.gym.name,
location: i.gym.location,
kind: i.gym.kind,
isPrivate: i.gym.isPrivate,
},
user:
direction === 'sent'
? {
id: i.user.id,
firstName: i.user.firstName,
lastName: i.user.lastName,
email: i.user.email,
}
: null,
invitedBy:
direction === 'received'
? {
id: i.invitedBy.id,
firstName: i.invitedBy.firstName,
lastName: i.invitedBy.lastName,
email: i.invitedBy.email,
}
: null,
invitedAt: i.invitedAt.toISOString(),
expiresAt: i.expiresAt.toISOString(),
};
}),
};
}
/**
* Search users to invite to a private virtual gym (owner only).
* Excludes the owner, current members and users with a pending invitation.
*/
export async function searchGymInvitees(
prisma: PrismaClient,
ownerId: string,
gymId: string,
firstName: string,
lastName: string,
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
await assertGymOwnerOf(prisma, gymId, ownerId);
const [members, pending] = await Promise.all([
prisma.gymMembership.findMany({ where: { gymId }, select: { userId: true } }),
prisma.gymInvitation.findMany({ where: { gymId, status: 'PENDING' }, select: { userId: true } }),
]);
const excludeIds = new Set([
ownerId,
...members.map((m) => m.userId),
...pending.map((p) => p.userId),
]);
const users = await prisma.user.findMany({
where: {
firstName: { contains: firstName, mode: 'insensitive' },
lastName: { contains: lastName, mode: 'insensitive' },
NOT: { id: { in: [...excludeIds] } },
},
select: { id: true, firstName: true, lastName: true, email: true, phone: true },
take: 20,
orderBy: { createdAt: 'asc' },
});
return { users };
}
async function loadPendingGymInvitation(prisma: PrismaClient, invitationId: string) {
const invitation = await prisma.gymInvitation.findUnique({ where: { id: invitationId } });
if (!invitation) throw notFound('Invitation not found');
if (invitation.status !== 'PENDING') throw conflict('Invitation is not pending');
if (invitation.expiresAt <= new Date()) throw new AppError(410, 'GONE', 'Invitation expired');
return invitation;
}
/** Accept a gym invitation (invited user only) → MEMBER membership (idempotent). */
export async function acceptGymInvitation(
prisma: PrismaClient,
userId: string,
invitationId: string,
) {
const invitation = await loadPendingGymInvitation(prisma, invitationId);
if (invitation.userId !== userId) throw forbidden('You are not the invited user');
const existing = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId: invitation.gymId } },
select: { id: true },
});
if (!existing) {
await prisma.gymMembership.create({
data: { userId, gymId: invitation.gymId, roles: ['MEMBER'] },
});
}
const updated = await prisma.gymInvitation.update({
where: { id: invitationId },
data: { status: 'ACCEPTED' },
});
return { invitation: updated };
}
/** Decline a gym invitation (invited user only). */
export async function declineGymInvitation(
prisma: PrismaClient,
userId: string,
invitationId: string,
) {
const invitation = await loadPendingGymInvitation(prisma, invitationId);
if (invitation.userId !== userId) throw forbidden('You are not the invited user');
const updated = await prisma.gymInvitation.update({
where: { id: invitationId },
data: { status: 'DECLINED' },
});
return { invitation: updated };
}
/** Withdraw a pending gym invitation (sender only) — removes the row. */
export async function withdrawGymInvitation(
prisma: PrismaClient,
userId: string,
invitationId: string,
) {
const invitation = await prisma.gymInvitation.findUnique({ where: { id: invitationId } });
if (!invitation) throw notFound('Invitation not found');
if (invitation.status !== 'PENDING') throw conflict('Invitation is not pending');
if (invitation.invitedById !== userId) throw forbidden('Only the sender can withdraw the invitation');
await prisma.gymInvitation.delete({ where: { id: invitationId } });
}

View File

@@ -0,0 +1,200 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Prisma, PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
import { logger } from '../../lib/logger.js';
import {
MAX_GYM_PHOTOS,
photoUploadDir,
removeGymPhotoFile,
storedFileName,
} from '../../lib/uploads.js';
import { gymEquipmentInclude, gymPhotosInclude } from './includes.js';
export interface GymPhotoDto {
id: string;
url: string;
order: number;
createdAt: string;
}
/** Public photo URL (served by GET /gyms/:gymId/photos/:photoId). */
export function gymPhotoUrl(gymId: string, photoId: string): string {
return `/gyms/${gymId}/photos/${photoId}`;
}
export function coverUrlOf(gymId: string, photos: { id: string }[]): string | null {
return photos[0] ? gymPhotoUrl(gymId, photos[0].id) : null;
}
type GymWithPhotos = Prisma.GymGetPayload<{
include: {
equipment: { include: { equipment: true } };
photos: true;
};
}>;
function gymToDto(g: GymWithPhotos) {
const photos: GymPhotoDto[] = g.photos.map((p) => ({
id: p.id,
url: gymPhotoUrl(g.id, p.id),
order: p.order,
createdAt: p.createdAt.toISOString(),
}));
return {
id: g.id,
name: g.name,
location: g.location,
availability: g.availability,
capacity: g.capacity,
kind: g.kind,
isPrivate: g.isPrivate,
equipment: g.equipment,
photos,
coverPhoto: coverUrlOf(g.id, g.photos),
};
}
async function loadGymDto(prisma: PrismaClient, gymId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
});
if (!gym) throw notFound('Gym not found');
return gymToDto(gym);
}
/** True when the user may manage the gym: an admin or a member with the OWNER role. */
export async function canManageGym(
prisma: PrismaClient,
gymId: string,
userId: string,
isAdmin: boolean,
): Promise<boolean> {
if (isAdmin) return true;
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
select: { roles: true },
});
return !!membership?.roles.includes('OWNER');
}
/**
* Public gym detail. REAL gyms are visible to any logged-in user; VIRTUAL gyms
* only to their managers (owner or admin). Includes the photo gallery.
*/
export async function getGymPublic(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
});
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('You do not have access to this gym');
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
return { gym: gymToDto(gym), roles: membership?.roles ?? [], isAdmin };
}
export interface UploadedPhotoFile {
mimeType: string;
sizeBytes: number;
/** Temp path (multer) — moved into the per-gym directory. */
path: string;
}
/** Add photos to a REAL gym's gallery (owner or admin). */
export async function addGymPhotos(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
files: UploadedPhotoFile[],
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { photos: { select: { order: true } } },
});
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL') throw conflict('Only real gyms have a gallery');
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('Only the gym owner or an admin can manage photos');
if (gym.photos.length + files.length > MAX_GYM_PHOTOS)
throw badRequest(`A gym can have at most ${MAX_GYM_PHOTOS} photos`);
const maxOrder = gym.photos.reduce((m, p) => Math.max(m, p.order), -1);
const dir = photoUploadDir(gymId);
const moved: string[] = [];
try {
fs.mkdirSync(dir, { recursive: true });
for (let i = 0; i < files.length; i++) {
const f = files[i];
const storedName = storedFileName(f.mimeType);
fs.renameSync(f.path, path.join(dir, storedName));
moved.push(path.join(dir, storedName));
await prisma.gymPhoto.create({
data: {
gymId,
storedName,
mimeType: f.mimeType,
sizeBytes: f.sizeBytes,
order: maxOrder + 1 + i,
},
});
}
} catch (e) {
for (const p of moved) fs.rmSync(p, { force: true });
logger.error({ err: e, gymId }, 'Failed to store gym photos');
throw new AppError(500, 'UPLOAD_FAILED', 'Failed to store uploaded photos');
}
return { gym: await loadGymDto(prisma, gymId) };
}
/** Remove a photo from a gym's gallery (owner or admin). */
export async function deleteGymPhoto(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
photoId: string,
) {
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('Only the gym owner or an admin can manage photos');
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
await prisma.gymPhoto.delete({ where: { id: photoId } });
removeGymPhotoFile(gymId, photo.storedName);
return { gym: await loadGymDto(prisma, gymId) };
}
/** Make a photo the gallery cover (order 0; the rest shift by +1). Owner or admin. */
export async function setGymPhotoCover(
prisma: PrismaClient,
userId: string,
isAdmin: boolean,
gymId: string,
photoId: string,
) {
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
throw forbidden('Only the gym owner or an admin can manage photos');
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
if (photo.order !== 0) {
await prisma.$transaction(async (tx) => {
await tx.gymPhoto.update({ where: { id: photoId }, data: { order: 0 } });
const others = await tx.gymPhoto.findMany({
where: { gymId, id: { not: photoId } },
select: { id: true, order: true },
});
for (const p of others) {
await tx.gymPhoto.update({ where: { id: p.id }, data: { order: p.order + 1 } });
}
});
}
return { gym: await loadGymDto(prisma, gymId) };
}

View File

@@ -363,7 +363,7 @@ export async function assertActiveTrainee(prisma: PrismaClient, trainerId: strin
* Restricted trainee detail: training metrics only (no body parameters, no profile).
*/
export async function getTraineeDetail(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
const coaching = await assertActiveTrainee(prisma, trainerId, userId);
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
@@ -381,6 +381,7 @@ export async function getTraineeDetail(prisma: PrismaClient, trainerId: string,
computeTraineeMetrics(prisma, userId),
]);
return {
coachingId: coaching.id,
user: {
id: user.id,
firstName: user.firstName,