API: tworzenie silowni wymaga wlasciciela (ownerId -> rola OWNER + endpointy nadawania/odejmowania)
This commit is contained in:
@@ -24,6 +24,7 @@ import { getExerciseProgress } from '../services/exerciseProgress.js';
|
||||
import { getKillstreak } from '../services/killstreak.js';
|
||||
import {
|
||||
addGymEquipment,
|
||||
addGymOwner,
|
||||
addMembership,
|
||||
approveGymClaim,
|
||||
createGym,
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
listUsers,
|
||||
rejectGymClaim,
|
||||
removeGymEquipment,
|
||||
removeGymOwner,
|
||||
removeMembership,
|
||||
updateGym,
|
||||
updateGymEquipmentQuantity,
|
||||
@@ -64,7 +66,8 @@ const gymSchema = z.object({
|
||||
capacity: z.number().int().positive().max(100000).nullable().optional(),
|
||||
});
|
||||
|
||||
const createGymSchema = gymSchema;
|
||||
// Admin tworząc siłownię zawsze wyznacza jej właściciela (ownerId → członkostwo OWNER).
|
||||
const createGymSchema = gymSchema.extend({ ownerId: z.string().min(1) });
|
||||
const updateGymSchema = gymSchema.partial();
|
||||
|
||||
const gymExceptionSchema = z.object({
|
||||
@@ -145,7 +148,7 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
* @openapi
|
||||
* /admin/gyms:
|
||||
* post:
|
||||
* summary: Create gym (admin)
|
||||
* summary: Create gym (admin; ownerId becomes OWNER)
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 201: { description: Created }
|
||||
@@ -160,6 +163,46 @@ export function createAdminRoutes({ prisma }: AppDeps) {
|
||||
}),
|
||||
);
|
||||
|
||||
const gymOwnerSchema = z.object({ userId: z.string().min(1) });
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /admin/gyms/{id}/owners:
|
||||
* post:
|
||||
* summary: Grant the OWNER role to a user in a gym (admin)
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 404: { description: Gym or user not found }
|
||||
*/
|
||||
router.post(
|
||||
'/gyms/:id/owners',
|
||||
validate(gymOwnerSchema),
|
||||
asyncHandler(async (req, res) => {
|
||||
const { userId } = req.body as z.infer<typeof gymOwnerSchema>;
|
||||
const result = await addGymOwner(prisma, req.params.id, userId);
|
||||
res.json(result);
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /admin/gyms/{id}/owners/{userId}:
|
||||
* delete:
|
||||
* summary: Revoke the OWNER role in a gym (admin; membership removed when no roles left)
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 204: { description: Revoked }
|
||||
* 404: { description: Owner not found }
|
||||
*/
|
||||
router.delete(
|
||||
'/gyms/:id/owners/:userId',
|
||||
asyncHandler(async (req, res) => {
|
||||
await removeGymOwner(prisma, req.params.id, req.params.userId);
|
||||
res.status(204).end();
|
||||
}),
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /admin/gyms/{id}:
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface CreateGymInput {
|
||||
location?: string | null;
|
||||
availability?: Availability | null;
|
||||
capacity?: number | null;
|
||||
/** Administrator wyznacza właściciela nowej siłowni (rola OWNER). */
|
||||
ownerId: string;
|
||||
}
|
||||
|
||||
export interface UpdateGymInput {
|
||||
@@ -94,16 +96,66 @@ export async function getGym(prisma: PrismaClient, gymId: string) {
|
||||
equipment: { include: { equipment: true }, 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 });
|
||||
return gym;
|
||||
const { memberships, ...rest } = gym;
|
||||
return { ...rest, 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ę; wyznaczony przez admina `ownerId` otrzymuje członkostwo z rolą OWNER. */
|
||||
export async function createGym(prisma: PrismaClient, data: CreateGymInput) {
|
||||
const { availability, ...rest } = data;
|
||||
const gym = await prisma.gym.create({
|
||||
data: { ...rest, availability: toPrismaAvailability(availability) },
|
||||
const { availability, ownerId, ...rest } = data;
|
||||
await ensureUser(prisma, ownerId);
|
||||
const gym = await prisma.$transaction(async (tx) => {
|
||||
const created = await tx.gym.create({
|
||||
data: { ...rest, availability: toPrismaAvailability(availability) },
|
||||
});
|
||||
await tx.gymMembership.create({
|
||||
data: { userId: ownerId, gymId: created.id, roles: ['OWNER'] },
|
||||
});
|
||||
return created;
|
||||
});
|
||||
return { gym };
|
||||
}
|
||||
|
||||
@@ -915,16 +915,17 @@ export const openapi: Record<string, unknown> = {
|
||||
},
|
||||
post: {
|
||||
tags: ['Admin'],
|
||||
summary: 'Create gym (admin)',
|
||||
summary: 'Create gym (admin; ownerId becomes OWNER member)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
requestBody: {
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['name'],
|
||||
required: ['name', 'ownerId'],
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
ownerId: { type: 'string', description: 'User mianowany właścicielem (OWNER)' },
|
||||
location: { type: 'string' },
|
||||
availability: {
|
||||
type: 'array',
|
||||
@@ -943,6 +944,36 @@ export const openapi: Record<string, unknown> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
'/admin/gyms/{id}/owners': {
|
||||
post: {
|
||||
tags: ['Admin'],
|
||||
summary: 'Grant the OWNER role to a user in a gym (admin)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
requestBody: {
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['userId'],
|
||||
properties: { userId: { type: 'string' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'/admin/gyms/{id}/owners/{userId}': {
|
||||
delete: {
|
||||
tags: ['Admin'],
|
||||
summary: 'Revoke the OWNER role in a gym (admin; membership removed when no roles left)',
|
||||
security: [{ bearerAuth: [] }],
|
||||
parameters: [
|
||||
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
|
||||
{ name: 'userId', in: 'path', required: true, schema: { type: 'string' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
'/admin/gyms/{id}': {
|
||||
patch: {
|
||||
tags: ['Admin'],
|
||||
|
||||
@@ -8,12 +8,19 @@ describe('admin routes', () => {
|
||||
let memberToken: string;
|
||||
let gymId: string;
|
||||
let targetEmail: string;
|
||||
let targetId: string;
|
||||
// Osobne konta na właścicieli tworzonych siłowni — bez zatruwania członkostw `target`.
|
||||
let ownerId: string;
|
||||
let ownerId2: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
const { user: admin } = await createUser({ isAdmin: true });
|
||||
adminEmail = admin.email;
|
||||
const { user: target } = await createUser();
|
||||
targetEmail = target.email;
|
||||
targetId = target.id;
|
||||
ownerId = (await createUser()).user.id;
|
||||
ownerId2 = (await createUser()).user.id;
|
||||
adminToken = (await loginViaApi(admin.email, PASSWORD)).token;
|
||||
memberToken = (await registerViaApi()).token;
|
||||
const gym = await prisma.gym.create({
|
||||
@@ -46,14 +53,23 @@ describe('admin routes', () => {
|
||||
expect(gym._count.memberships).toBe(0);
|
||||
});
|
||||
|
||||
it('creates a gym', async () => {
|
||||
it('creates a gym and makes the designated owner OWNER', async () => {
|
||||
const app = buildApp();
|
||||
const res = await app
|
||||
.post('/api/v1/admin/gyms')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ name: 'Nowa siłownia', location: 'Kraków', capacity: 50 });
|
||||
.send({ name: 'Nowa siłownia', location: 'Kraków', capacity: 50, ownerId });
|
||||
expect(res.status).toBe(201);
|
||||
const newGymId = res.body.gym.id as string;
|
||||
expect(res.body.gym).toMatchObject({ name: 'Nowa siłownia', location: 'Kraków', capacity: 50 });
|
||||
const membership = await prisma.gymMembership.findUnique({
|
||||
where: { userId_gymId: { userId: ownerId, gymId: newGymId } },
|
||||
});
|
||||
expect(membership?.roles).toEqual(['OWNER']);
|
||||
const detail = await app
|
||||
.get(`/api/v1/admin/gyms/${newGymId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(detail.body.owners).toEqual([expect.objectContaining({ id: ownerId })]);
|
||||
});
|
||||
|
||||
it('rejects a gym without a name with 400', async () => {
|
||||
@@ -65,12 +81,67 @@ describe('admin routes', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects creating a gym without a designated owner with 400', async () => {
|
||||
const app = buildApp();
|
||||
const res = await app
|
||||
.post('/api/v1/admin/gyms')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ name: 'Bez właściciela' });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects creating a gym with an unknown owner with 404', async () => {
|
||||
const app = buildApp();
|
||||
const res = await app
|
||||
.post('/api/v1/admin/gyms')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ name: 'Nieistniejący właściciel', ownerId: 'no-such-user' });
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('grants and revokes the OWNER role for a user in a gym', async () => {
|
||||
const app = buildApp();
|
||||
const add = await app
|
||||
.post(`/api/v1/admin/gyms/${gymId}/owners`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ userId: targetId });
|
||||
expect(add.status).toBe(200);
|
||||
expect(add.body.membership.roles).toEqual(['OWNER']);
|
||||
|
||||
// ponowne nadanie jest idempotentne (bez duplikatu roli)
|
||||
const again = await app
|
||||
.post(`/api/v1/admin/gyms/${gymId}/owners`)
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ userId: targetId });
|
||||
expect(again.status).toBe(200);
|
||||
expect(again.body.membership.roles).toEqual(['OWNER']);
|
||||
|
||||
const detail = await app
|
||||
.get(`/api/v1/admin/gyms/${gymId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(detail.body.owners.map((o: { id: string }) => o.id)).toContain(targetId);
|
||||
|
||||
const del = await app
|
||||
.delete(`/api/v1/admin/gyms/${gymId}/owners/${targetId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(del.status).toBe(204);
|
||||
const membership = await prisma.gymMembership.findUnique({
|
||||
where: { userId_gymId: { userId: targetId, gymId } },
|
||||
});
|
||||
expect(membership).toBeNull();
|
||||
|
||||
const delAgain = await app
|
||||
.delete(`/api/v1/admin/gyms/${gymId}/owners/${targetId}`)
|
||||
.set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(delAgain.status).toBe(404);
|
||||
});
|
||||
|
||||
it('updates a gym', async () => {
|
||||
const app = buildApp();
|
||||
const created = await app
|
||||
.post('/api/v1/admin/gyms')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ name: 'Do edycji' });
|
||||
.send({ name: 'Do edycji', ownerId: ownerId2 });
|
||||
const id = created.body.gym.id;
|
||||
const res = await app
|
||||
.patch(`/api/v1/admin/gyms/${id}`)
|
||||
@@ -94,7 +165,7 @@ describe('admin routes', () => {
|
||||
const created = await app
|
||||
.post('/api/v1/admin/gyms')
|
||||
.set('Authorization', `Bearer ${adminToken}`)
|
||||
.send({ name: 'Do usunięcia' });
|
||||
.send({ name: 'Do usunięcia', ownerId: ownerId2 });
|
||||
const id = created.body.gym.id;
|
||||
const res = await app.delete(`/api/v1/admin/gyms/${id}`).set('Authorization', `Bearer ${adminToken}`);
|
||||
expect(res.status).toBe(204);
|
||||
|
||||
Reference in New Issue
Block a user