feat: manage waitlist and remove group members
- Add group-waitlist module (list/promote/remove entries) - Remove attendee with optional atomic promotion from waitlist - Block removal when attendee has payments (attendee_has_payments) - Waitlist detail modal matching members UI; optimistic add-to-waitlist - Responsive tweaks for the members/waitlist tabs
This commit is contained in:
@@ -116,4 +116,11 @@ export function alreadyWaitlistedProblem(): ProblemDetails {
|
||||
detail: 'Este número de teléfono ya está en la lista de espera del grupo.',
|
||||
code: 'already_waitlisted',
|
||||
});
|
||||
}
|
||||
|
||||
export function attendeeHasPaymentsProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.',
|
||||
code: 'attendee_has_payments',
|
||||
});
|
||||
}
|
||||
24
apps/backend/src/modules/attendees/features/remove/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/remove/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { type RemoveAttendeeQuery, RemoveAttendeeQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { RemoveAttendee } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.delete('/:groupId/attendees/:attendeeId', validate.query(RemoveAttendeeQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const attendeeId = c.req.param('attendeeId');
|
||||
const query = c.req.valid('query') as RemoveAttendeeQuery;
|
||||
const useCase = new RemoveAttendee();
|
||||
const result = await useCase.execute(groupId, attendeeId, user.id, {
|
||||
promoteFromWaitlist: query.promoteFromWaitlist,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, RemoveAttendeeResult, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { attendeeHasPaymentsProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
toGroupWaitlistEntryDto,
|
||||
} from '@/modules/group-waitlist/lib/helpers';
|
||||
import { promoteFirstPendingWaitlistEntry } from '@/modules/group-waitlist/lib/promote';
|
||||
|
||||
type RemoveAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
type RemoveAttendeeOptions = {
|
||||
promoteFromWaitlist?: boolean;
|
||||
};
|
||||
|
||||
export class RemoveAttendee {
|
||||
constructor(private readonly deps: RemoveAttendeeDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
options: RemoveAttendeeOptions = {},
|
||||
): Promise<Result<RemoveAttendeeResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
const group = groupResult.value;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
const paymentsCount = await db.payment.count({ where: { attendeeId } });
|
||||
if (paymentsCount > 0) {
|
||||
return err(attendeeHasPaymentsProblem());
|
||||
}
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient): Promise<Result<RemoveAttendeeResult, ProblemDetails>> => {
|
||||
await tx.attendee.delete({ where: { id: attendeeId } });
|
||||
|
||||
if (!options.promoteFromWaitlist) {
|
||||
return ok({ removedAttendeeId: attendeeId, promoted: null });
|
||||
}
|
||||
|
||||
const promoteResult = await promoteFirstPendingWaitlistEntry(tx, group);
|
||||
if (!promoteResult.ok) {
|
||||
return err(promoteResult.error);
|
||||
}
|
||||
if (!promoteResult.value) {
|
||||
return ok({ removedAttendeeId: attendeeId, promoted: null });
|
||||
}
|
||||
|
||||
await tx.groupWaitlistEntry.delete({ where: { id: promoteResult.value.entry.id } });
|
||||
return ok({
|
||||
removedAttendeeId: attendeeId,
|
||||
promoted: toGroupWaitlistEntryDto(promoteResult.value.entry),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { type GroupWaitlistQuery, GroupWaitlistQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListGroupWaitlistEntries } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/:groupId/waitlist', validate.query(GroupWaitlistQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const query = c.req.valid('query') as GroupWaitlistQuery;
|
||||
const useCase = new ListGroupWaitlistEntries();
|
||||
const result = await useCase.execute(groupId, user.id, query);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { GroupWaitlistList, GroupWaitlistQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser, type GroupWaitlistEntryRecord, toGroupWaitlistEntryDto } from '../../lib/helpers';
|
||||
|
||||
type ListGroupWaitlistEntriesDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupWaitlistEntry'>;
|
||||
};
|
||||
|
||||
export class ListGroupWaitlistEntries {
|
||||
constructor(private readonly deps: ListGroupWaitlistEntriesDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
userId: string,
|
||||
query: GroupWaitlistQuery,
|
||||
): Promise<Result<GroupWaitlistList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupForUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const where = { groupId, status: 'PENDING' as const };
|
||||
const [records, total] = await Promise.all([
|
||||
db.groupWaitlistEntry.findMany({
|
||||
where,
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
db.groupWaitlistEntry.count({ where }),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: records.map((record) => toGroupWaitlistEntryDto(record as unknown as GroupWaitlistEntryRecord)),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { PromoteGroupWaitlistEntry } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/waitlist/:entryId/promote', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const useCase = new PromoteGroupWaitlistEntry();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, PromoteGroupWaitlistEntryResult, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
} from '../../lib/helpers';
|
||||
import { promoteWaitlistEntryRecord } from '../../lib/promote';
|
||||
|
||||
type PromoteGroupWaitlistEntryDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
export class PromoteGroupWaitlistEntry {
|
||||
constructor(private readonly deps: PromoteGroupWaitlistEntryDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<PromoteGroupWaitlistEntryResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const entry = await db.groupWaitlistEntry.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!entry) {
|
||||
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
|
||||
}
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const promoteResult = await promoteWaitlistEntryRecord(
|
||||
tx,
|
||||
groupResult.value,
|
||||
entry as unknown as GroupWaitlistEntryRecord,
|
||||
);
|
||||
if (!promoteResult.ok) {
|
||||
return promoteResult;
|
||||
}
|
||||
|
||||
await tx.groupWaitlistEntry.delete({ where: { id: entry.id } });
|
||||
return ok({ attendee: promoteResult.value });
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { RemoveGroupWaitlistEntry } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.delete('/:groupId/waitlist/:entryId', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
}
|
||||
const groupId = c.req.param('groupId');
|
||||
const entryId = c.req.param('entryId');
|
||||
const useCase = new RemoveGroupWaitlistEntry();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, RemoveGroupWaitlistEntryResult, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '../../lib/helpers';
|
||||
|
||||
type RemoveGroupWaitlistEntryDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupWaitlistEntry'>;
|
||||
};
|
||||
|
||||
export class RemoveGroupWaitlistEntry {
|
||||
constructor(private readonly deps: RemoveGroupWaitlistEntryDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<RemoveGroupWaitlistEntryResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const existing = await db.groupWaitlistEntry.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!existing) {
|
||||
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
|
||||
}
|
||||
|
||||
await db.groupWaitlistEntry.delete({ where: { id: entryId } });
|
||||
return ok({ deleted: true });
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/group-waitlist/index.ts
Normal file
1
apps/backend/src/modules/group-waitlist/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as groupWaitlistRoutes } from './routes';
|
||||
65
apps/backend/src/modules/group-waitlist/lib/helpers.ts
Normal file
65
apps/backend/src/modules/group-waitlist/lib/helpers.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import type { Group, PrismaClient } from '@generated/prisma/client';
|
||||
import type { GroupWaitlistEntryDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
|
||||
export type GroupWaitlistEntryRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
notes: string | null;
|
||||
status: GroupWaitlistEntryDto['status'];
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export function toGroupWaitlistEntryDto(record: GroupWaitlistEntryRecord): GroupWaitlistEntryDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
notes: record.notes,
|
||||
status: record.status,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function findGroupForUser(
|
||||
db: Pick<PrismaClient, 'group'>,
|
||||
groupId: string,
|
||||
userId: string,
|
||||
): Promise<Result<Group, ProblemDetails>> {
|
||||
const group = await db.group.findUnique({
|
||||
where: { id: groupId },
|
||||
include: { members: { where: { userId } } },
|
||||
});
|
||||
if (!group) {
|
||||
return err(notFoundResourceProblem('Group', groupId));
|
||||
}
|
||||
const isOwner = group.createdById === userId;
|
||||
const isMember = group.members.length > 0;
|
||||
if (!isOwner && !isMember) {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
return ok(group);
|
||||
}
|
||||
|
||||
export async function findGroupOwnedByUser(
|
||||
db: Pick<PrismaClient, 'group'>,
|
||||
groupId: string,
|
||||
userId: string,
|
||||
): Promise<Result<Group, ProblemDetails>> {
|
||||
const group = await db.group.findUnique({ where: { id: groupId } });
|
||||
if (!group) {
|
||||
return err(notFoundResourceProblem('Group', groupId));
|
||||
}
|
||||
if (group.createdById !== userId) {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
return ok(group);
|
||||
}
|
||||
83
apps/backend/src/modules/group-waitlist/lib/promote.ts
Normal file
83
apps/backend/src/modules/group-waitlist/lib/promote.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { capacityReachedProblem, conflictProblem } from '@/http/problem-builders';
|
||||
import { type AttendeeRecord, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { type GroupWaitlistEntryRecord } from './helpers';
|
||||
|
||||
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry'>;
|
||||
|
||||
type PromoteGroup = {
|
||||
id: string;
|
||||
capacity: number | null;
|
||||
};
|
||||
|
||||
export async function findFirstPendingWaitlistEntry(
|
||||
db: PromoteDb,
|
||||
groupId: string,
|
||||
): Promise<GroupWaitlistEntryRecord | null> {
|
||||
const record = await db.groupWaitlistEntry.findFirst({
|
||||
where: { groupId, status: 'PENDING' },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return record as GroupWaitlistEntryRecord | null;
|
||||
}
|
||||
|
||||
export async function promoteWaitlistEntryRecord(
|
||||
db: PromoteDb,
|
||||
group: PromoteGroup,
|
||||
entry: GroupWaitlistEntryRecord,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({ where: { groupId: group.id } });
|
||||
if (currentCount >= group.capacity) {
|
||||
return err(capacityReachedProblem(group.capacity));
|
||||
}
|
||||
}
|
||||
|
||||
const existing = await db.attendee.findFirst({
|
||||
where: { groupId: group.id, phone: entry.phone },
|
||||
});
|
||||
if (existing) {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
|
||||
code: 'attendee_already_registered',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName: entry.fullName,
|
||||
phone: entry.phone,
|
||||
email: entry.email,
|
||||
notes: entry.notes,
|
||||
},
|
||||
});
|
||||
|
||||
return ok(toAttendeeDto(attendee as unknown as AttendeeRecord));
|
||||
}
|
||||
|
||||
export type PromoteFirstResult = {
|
||||
attendee: AttendeeDto;
|
||||
entry: GroupWaitlistEntryRecord;
|
||||
};
|
||||
|
||||
export async function promoteFirstPendingWaitlistEntry(
|
||||
db: PromoteDb,
|
||||
group: PromoteGroup,
|
||||
): Promise<Result<PromoteFirstResult | null, ProblemDetails>> {
|
||||
const entry = await findFirstPendingWaitlistEntry(db, group.id);
|
||||
if (!entry) {
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
const result = await promoteWaitlistEntryRecord(db, group, entry);
|
||||
if (!result.ok) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return ok({ attendee: result.value, entry });
|
||||
}
|
||||
12
apps/backend/src/modules/group-waitlist/routes.ts
Normal file
12
apps/backend/src/modules/group-waitlist/routes.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import promoteRoute from './features/promote/route';
|
||||
import removeRoute from './features/remove/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getAllRoute);
|
||||
routes.route('/', promoteRoute);
|
||||
routes.route('/', removeRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -2,6 +2,8 @@ import { Hono } from 'hono';
|
||||
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
|
||||
import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
|
||||
import createAttendeeRoute from '../attendees/features/create/route';
|
||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||
import createFromOrganizationRoute from './features/create-from-organization/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import getByIdRoute from './features/get-by-id/route';
|
||||
@@ -18,5 +20,7 @@ routes.route('/', createAttendeeRoute);
|
||||
routes.route('/', bulkCreateAttendeesRoute);
|
||||
routes.route('/', getByIdRoute);
|
||||
routes.route('/', addToGroupWaitlistRoute);
|
||||
routes.route('/', groupWaitlistRoutes);
|
||||
routes.route('/', removeAttendeeRoute);
|
||||
|
||||
export default routes;
|
||||
352
apps/backend/test/waitlist-management.test.ts
Normal file
352
apps/backend/test/waitlist-management.test.ts
Normal file
@@ -0,0 +1,352 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
group: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
attendee: {
|
||||
findFirst: mock(),
|
||||
findMany: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
delete: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
findMany: mock(),
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
delete: mock(),
|
||||
},
|
||||
payment: {
|
||||
count: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
default: db,
|
||||
getPrismaClient: mock(),
|
||||
UnitOfWork: class {
|
||||
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
|
||||
},
|
||||
}));
|
||||
|
||||
import prisma from '@/lib/prisma';
|
||||
import { groupsRoutes } from '@/modules/groups';
|
||||
|
||||
const teacherId = 'teacher-1';
|
||||
const mockGroup = {
|
||||
id: 'group-1',
|
||||
name: 'Taller de Pintura',
|
||||
description: null,
|
||||
createdById: teacherId,
|
||||
inviteToken: null,
|
||||
createdAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-01T10:00:00.000Z'),
|
||||
days: ['MONDAY'],
|
||||
time: '18:00',
|
||||
capacity: 20,
|
||||
price: 1500,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 10,
|
||||
members: [],
|
||||
};
|
||||
|
||||
const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'wl-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
createdAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-10T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const attendee = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'att-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
function makeApp(userValue: unknown) {
|
||||
const app = new Hono();
|
||||
app.use('*', async (c, next) => {
|
||||
c.set('user', userValue as never);
|
||||
await next();
|
||||
});
|
||||
app.route('/groups', groupsRoutes);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('group waitlist management', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('GET /groups/:groupId/waitlist', () => {
|
||||
it('lists pending entries in FIFO order with pagination', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupWaitlistEntry.findMany.mockResolvedValue([
|
||||
waitlistEntry({ id: 'wl-1', fullName: 'Ana García', createdAt: new Date('2026-09-08T10:00:00.000Z') }),
|
||||
waitlistEntry({ id: 'wl-2', fullName: 'Pedro López', createdAt: new Date('2026-09-09T10:00:00.000Z') }),
|
||||
] as never);
|
||||
prisma.groupWaitlistEntry.count.mockResolvedValue(2);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.data).toHaveLength(2);
|
||||
expect(data.data[0].fullName).toBe('Ana García');
|
||||
expect(data.pagination).toEqual({ page: 1, pageSize: 10, total: 2, totalPages: 1 });
|
||||
expect(prisma.groupWaitlistEntry.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'PENDING' },
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects user without access to the group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/waitlist');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupWaitlistEntry.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /groups/:groupId/waitlist/:entryId/promote', () => {
|
||||
it('creates an attendee from the entry and removes it from the waitlist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.attendee.fullName).toBe('Martín Gómez');
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ groupId: 'group-1', fullName: 'Martín Gómez', phone: '+5491133445566' }),
|
||||
});
|
||||
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
|
||||
});
|
||||
|
||||
it('rejects with 409 when the group reached its capacity', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue({ ...mockGroup, capacity: 5 } as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('group_capacity_reached');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects with 409 when the phone already belongs to an attendee', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the entry does not exist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-missing/promote', {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('rejects a non-owner user', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/waitlist/wl-1/promote', {
|
||||
method: 'POST',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /groups/:groupId/waitlist/:entryId', () => {
|
||||
it('removes a waitlist entry', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const data = await res.json();
|
||||
expect(data.deleted).toBe(true);
|
||||
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
|
||||
});
|
||||
|
||||
it('returns 404 when the entry does not exist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-missing', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a non-owner user', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/waitlist/wl-1', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /groups/:groupId/attendees/:attendeeId', () => {
|
||||
it('removes an attendee without promotion', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
prisma.payment.count.mockResolvedValue(0);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/attendees/att-1', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.removedAttendeeId).toBe('att-1');
|
||||
expect(body.promoted).toBeNull();
|
||||
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
|
||||
});
|
||||
|
||||
it('removes an attendee and promotes the first pending waitlist entry atomically', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockImplementation(async ({ where }: { where?: { id?: string } }) => {
|
||||
if (where?.id) return attendee() as never;
|
||||
return null;
|
||||
});
|
||||
prisma.payment.count.mockResolvedValue(0);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(
|
||||
waitlistEntry({ id: 'wl-1', fullName: 'Sofía Ruiz', phone: '+5491133778899' }) as never,
|
||||
);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.create.mockResolvedValue(
|
||||
attendee({ id: 'att-2', fullName: 'Sofía Ruiz', phone: '+5491133778899' }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/attendees/att-1?promoteFromWaitlist=true',
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.removedAttendeeId).toBe('att-1');
|
||||
expect(body.promoted).toMatchObject({ id: 'wl-1', fullName: 'Sofía Ruiz' });
|
||||
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
|
||||
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ fullName: 'Sofía Ruiz', phone: '+5491133778899' }),
|
||||
});
|
||||
});
|
||||
|
||||
it('removes the attendee when promote requested but waitlist is empty', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
prisma.payment.count.mockResolvedValue(0);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/attendees/att-1?promoteFromWaitlist=true',
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.removedAttendeeId).toBe('att-1');
|
||||
expect(body.promoted).toBeNull();
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('blocks removal when the attendee has payments', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
prisma.payment.count.mockResolvedValue(2);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/attendees/att-1', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('attendee_has_payments');
|
||||
expect(prisma.attendee.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the attendee does not belong to the group', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/attendees/att-missing', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
expect(prisma.attendee.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a non-owner user', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request('/groups/group-1/attendees/att-1', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.attendee.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user