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:
Jose Selesan
2026-09-22 17:04:41 -03:00
parent 785d54df7e
commit fc30927b8b
19 changed files with 1417 additions and 103 deletions

View File

@@ -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',
});
}

View 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;

View File

@@ -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),
});
},
);
}
}

View File

@@ -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;

View File

@@ -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),
});
}
}

View File

@@ -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;

View File

@@ -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 });
},
);
}
}

View File

@@ -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;

View File

@@ -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 });
}
}

View File

@@ -0,0 +1 @@
export { default as groupWaitlistRoutes } from './routes';

View 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);
}

View 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 });
}

View 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;

View File

@@ -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;