feat: implement group pre-registration feature with approval and rejection workflows
- Add API endpoints for managing group pre-registrations, including approval and rejection. - Create database migration for `group_pre_registrations` table and associated enum for status. - Implement use cases for listing, approving, and rejecting pre-registrations. - Add frontend components for displaying pre-registration details and managing approvals/rejections. - Update shared schemas to include pre-registration data structures and validation. - Remove obsolete `WaitlistNoticeCard` component and replace with `PreRegistrationNoticeCard`.
This commit is contained in:
@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||
- `src/logger.ts` — pino + pino-pretty.
|
||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`).
|
||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza.
|
||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PreRegistrationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "group_pre_registrations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"groupId" TEXT NOT NULL,
|
||||
"fullName" TEXT NOT NULL,
|
||||
"phone" TEXT NOT NULL,
|
||||
"email" TEXT,
|
||||
"status" "PreRegistrationStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"reviewedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "group_pre_registrations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "group_pre_registrations_groupId_idx" ON "group_pre_registrations"("groupId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "group_pre_registrations_groupId_phone_key" ON "group_pre_registrations"("groupId", "phone");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "group_pre_registrations" ADD CONSTRAINT "group_pre_registrations_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -20,6 +20,7 @@ model Group {
|
||||
attendees Attendee[]
|
||||
payments Payment[]
|
||||
waitlist GroupWaitlistEntry[]
|
||||
preRegistrations GroupPreRegistration[]
|
||||
classSessions ClassSession[]
|
||||
|
||||
@@map("groups")
|
||||
@@ -157,6 +158,30 @@ enum WaitlistStatus {
|
||||
DECLINED
|
||||
}
|
||||
|
||||
enum PreRegistrationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
model GroupPreRegistration {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
phone String
|
||||
email String?
|
||||
status PreRegistrationStatus @default(PENDING)
|
||||
reviewedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([groupId, phone])
|
||||
@@index([groupId])
|
||||
@@map("group_pre_registrations")
|
||||
}
|
||||
|
||||
enum PaymentProvider {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { ApproveGroupPreRegistration } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/preregistrations/:entryId/approve', 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 ApproveGroupPreRegistration();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
ApproveGroupPreRegistrationResult,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
toGroupWaitlistEntryDto,
|
||||
} from '../../../group-waitlist/lib/helpers';
|
||||
import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote';
|
||||
import { type GroupPreRegistrationRecord } from '../../lib/helpers';
|
||||
|
||||
type ApproveGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
export class ApproveGroupPreRegistration {
|
||||
constructor(private readonly deps: ApproveGroupPreRegistrationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<ApproveGroupPreRegistrationResult, 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.groupPreRegistration.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!entry) {
|
||||
return err(notFoundResourceProblem('GroupPreRegistration', entryId));
|
||||
}
|
||||
if (entry.status !== 'PENDING') {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Esta pre-inscripción ya fue revisada.',
|
||||
code: 'pre_registration_already_reviewed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const record = entry as unknown as GroupPreRegistrationRecord;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx): Promise<Result<ApproveGroupPreRegistrationResult, ProblemDetails>> => {
|
||||
const promoteResult = await promoteWaitlistEntryRecord(
|
||||
tx,
|
||||
groupResult.value,
|
||||
{
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
},
|
||||
);
|
||||
|
||||
if (promoteResult.ok) {
|
||||
await tx.groupPreRegistration.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'APPROVED', reviewedAt: new Date() },
|
||||
});
|
||||
return ok({
|
||||
outcome: 'added',
|
||||
attendee: promoteResult.value,
|
||||
waitlistEntry: null,
|
||||
});
|
||||
}
|
||||
|
||||
if (promoteResult.error.code !== 'group_capacity_reached') {
|
||||
return promoteResult;
|
||||
}
|
||||
|
||||
const existingWaitlistEntry = await tx.groupWaitlistEntry.findFirst({
|
||||
where: { groupId: record.groupId, phone: record.phone },
|
||||
});
|
||||
const waitlistEntryRecord = existingWaitlistEntry
|
||||
? (existingWaitlistEntry as unknown as GroupWaitlistEntryRecord)
|
||||
: ((await tx.groupWaitlistEntry.create({
|
||||
data: {
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
},
|
||||
})) as unknown as GroupWaitlistEntryRecord);
|
||||
|
||||
await tx.groupPreRegistration.update({
|
||||
where: { id: record.id },
|
||||
data: { status: 'APPROVED', reviewedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({
|
||||
outcome: 'waitlisted',
|
||||
attendee: null,
|
||||
waitlistEntry: toGroupWaitlistEntryDto(waitlistEntryRecord),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
type GroupPreRegistrationQuery,
|
||||
GroupPreRegistrationQuerySchema,
|
||||
} from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { ListGroupPreRegistrations } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/:groupId/preregistrations', validate.query(GroupPreRegistrationQuerySchema), 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 GroupPreRegistrationQuery;
|
||||
const useCase = new ListGroupPreRegistrations();
|
||||
const result = await useCase.execute(groupId, user.id, query);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
GroupPreRegistrationList,
|
||||
GroupPreRegistrationQuery,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '../../../group-waitlist/lib/helpers';
|
||||
import {
|
||||
type GroupPreRegistrationRecord,
|
||||
toGroupPreRegistrationDto,
|
||||
} from '../../lib/helpers';
|
||||
|
||||
type ListGroupPreRegistrationsDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export class ListGroupPreRegistrations {
|
||||
constructor(private readonly deps: ListGroupPreRegistrationsDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
userId: string,
|
||||
query: GroupPreRegistrationQuery,
|
||||
): Promise<Result<GroupPreRegistrationList, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupForUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const where = { groupId, status: query.status ?? ('PENDING' as const) };
|
||||
const [records, total] = await Promise.all([
|
||||
db.groupPreRegistration.findMany({
|
||||
where,
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
db.groupPreRegistration.count({ where }),
|
||||
]);
|
||||
|
||||
return ok({
|
||||
data: records.map(
|
||||
(record) => toGroupPreRegistrationDto(record as unknown as GroupPreRegistrationRecord),
|
||||
),
|
||||
pagination: getPaginationMetadata(query, total),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { RejectGroupPreRegistration } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/:groupId/preregistrations/:entryId/reject', 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 RejectGroupPreRegistration();
|
||||
const result = await useCase.execute(groupId, entryId, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
ProblemDetails,
|
||||
RejectGroupPreRegistrationResult,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupOwnedByUser } from '../../../group-waitlist/lib/helpers';
|
||||
import { type GroupPreRegistrationRecord, toGroupPreRegistrationDto } from '../../lib/helpers';
|
||||
|
||||
type RejectGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export class RejectGroupPreRegistration {
|
||||
constructor(private readonly deps: RejectGroupPreRegistrationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
groupId: string,
|
||||
entryId: string,
|
||||
userId: string,
|
||||
): Promise<Result<RejectGroupPreRegistrationResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const groupResult = await findGroupOwnedByUser(db, groupId, userId);
|
||||
if (!groupResult.ok) {
|
||||
return groupResult;
|
||||
}
|
||||
|
||||
const entry = await db.groupPreRegistration.findFirst({
|
||||
where: { id: entryId, groupId },
|
||||
});
|
||||
if (!entry) {
|
||||
return err(notFoundResourceProblem('GroupPreRegistration', entryId));
|
||||
}
|
||||
if (entry.status !== 'PENDING') {
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: 'Esta pre-inscripción ya fue revisada.',
|
||||
code: 'pre_registration_already_reviewed',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const updated = await db.groupPreRegistration.update({
|
||||
where: { id: entry.id },
|
||||
data: { status: 'REJECTED', reviewedAt: new Date() },
|
||||
});
|
||||
|
||||
return ok({
|
||||
entry: toGroupPreRegistrationDto(updated as unknown as GroupPreRegistrationRecord),
|
||||
});
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/group-preregistrations/index.ts
Normal file
1
apps/backend/src/modules/group-preregistrations/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as groupPreRegistrationRoutes } from './routes';
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { GroupPreRegistrationDto } from '@gruperly/shared';
|
||||
|
||||
export type GroupPreRegistrationRecord = {
|
||||
id: string;
|
||||
groupId: string;
|
||||
fullName: string;
|
||||
phone: string;
|
||||
email: string | null;
|
||||
status: GroupPreRegistrationDto['status'];
|
||||
reviewedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export function toGroupPreRegistrationDto(
|
||||
record: GroupPreRegistrationRecord,
|
||||
): GroupPreRegistrationDto {
|
||||
return {
|
||||
id: record.id,
|
||||
groupId: record.groupId,
|
||||
fullName: record.fullName,
|
||||
phone: record.phone,
|
||||
email: record.email,
|
||||
status: record.status,
|
||||
reviewedAt: record.reviewedAt ? record.reviewedAt.toISOString() : null,
|
||||
createdAt: record.createdAt.toISOString(),
|
||||
updatedAt: record.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
12
apps/backend/src/modules/group-preregistrations/routes.ts
Normal file
12
apps/backend/src/modules/group-preregistrations/routes.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from 'hono';
|
||||
import approveRoute from './features/approve/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
import rejectRoute from './features/reject/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/', getAllRoute);
|
||||
routes.route('/', approveRoute);
|
||||
routes.route('/', rejectRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -6,6 +6,7 @@ import createAttendeeRoute from '../attendees/features/create/route';
|
||||
import getAttendeeRoute from '../attendees/features/get-by-id/route';
|
||||
import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||
import createGroupRoute from './features/create/route';
|
||||
import getAllRoute from './features/get-all/route';
|
||||
@@ -24,6 +25,7 @@ routes.route('/', bulkCreateAttendeesRoute);
|
||||
routes.route('/', getByIdRoute);
|
||||
routes.route('/', addToGroupWaitlistRoute);
|
||||
routes.route('/', groupWaitlistRoutes);
|
||||
routes.route('/', groupPreRegistrationRoutes);
|
||||
routes.route('/', analyticsRoutes);
|
||||
routes.route('/', getAttendeeRoute);
|
||||
routes.route('/', getAttendeeStatsRoute);
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import type { JoinGroupViaInvite, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '@/modules/attendees/lib/helpers';
|
||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||
|
||||
type JoinViaInviteDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
|
||||
};
|
||||
|
||||
export type JoinViaInviteResult = {
|
||||
status: 'registered' | 'waitlisted';
|
||||
status: 'pre_registered';
|
||||
message: string;
|
||||
attendee: AttendeeDto | null;
|
||||
attendee: null;
|
||||
};
|
||||
|
||||
export class JoinViaInvite {
|
||||
@@ -53,50 +53,63 @@ export class JoinViaInvite {
|
||||
}
|
||||
|
||||
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||
const email = payload.email?.trim() || null;
|
||||
|
||||
if (group.capacity !== null) {
|
||||
const currentCount = await db.attendee.count({
|
||||
where: { groupId: group.id, status: 'ACTIVE' },
|
||||
const existingPreRegistration = await db.groupPreRegistration.findFirst({
|
||||
where: {
|
||||
groupId: group.id,
|
||||
OR: [
|
||||
{ phone },
|
||||
{ phone: payload.phone.trim() },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (existingPreRegistration?.status === 'REJECTED') {
|
||||
await db.groupPreRegistration.update({
|
||||
where: { id: existingPreRegistration.id },
|
||||
data: { status: 'PENDING', fullName, email, reviewedAt: null },
|
||||
});
|
||||
|
||||
if (currentCount >= group.capacity) {
|
||||
const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
|
||||
where: { groupId: group.id, phone },
|
||||
});
|
||||
|
||||
if (!existingWaitlistEntry) {
|
||||
await db.groupWaitlistEntry.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return ok({
|
||||
status: 'waitlisted',
|
||||
message:
|
||||
'El grupo está completo. Fuiste agregado a la lista de espera. Te contactaremos cuando haya un lugar disponible.',
|
||||
attendee: null,
|
||||
});
|
||||
}
|
||||
return ok({
|
||||
status: 'pre_registered',
|
||||
attendee: null,
|
||||
message:
|
||||
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||
});
|
||||
}
|
||||
|
||||
const created = await db.attendee.create({
|
||||
if (existingPreRegistration) {
|
||||
const message =
|
||||
existingPreRegistration.status === 'APPROVED'
|
||||
? 'Tu inscripción para este grupo ya fue aprobada.'
|
||||
: 'Ya enviaste una solicitud de inscripción para este grupo. Está pendiente de revisión por el profesor.';
|
||||
|
||||
return err(
|
||||
conflictProblem({
|
||||
detail: message,
|
||||
code:
|
||||
existingPreRegistration.status === 'APPROVED'
|
||||
? 'pre_registration_already_approved'
|
||||
: 'pre_registration_already_pending',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
await db.groupPreRegistration.create({
|
||||
data: {
|
||||
groupId: group.id,
|
||||
fullName,
|
||||
phone,
|
||||
email: payload.email?.trim() || null,
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
status: 'registered',
|
||||
attendee: toAttendeeDto(created as unknown as AttendeeRecord),
|
||||
message: 'Inscripción realizada con éxito',
|
||||
status: 'pre_registered',
|
||||
attendee: null,
|
||||
message:
|
||||
'Recibimos tu solicitud de inscripción. El profesor revisará tus datos y te confirmará el lugar.',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,10 @@ const db = {
|
||||
create: mock(),
|
||||
count: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
groupPreRegistration: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -83,18 +84,18 @@ describe('public invitations routes', () => {
|
||||
});
|
||||
|
||||
describe('POST /invitations/:token/join', () => {
|
||||
it('registers a new attendee successfully', async () => {
|
||||
it('creates a pending pre-registration instead of an attendee', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue({
|
||||
id: 'att-1',
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.create.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
email: 'lucia@test.com',
|
||||
phone: '+5491122334455',
|
||||
guardianName: null,
|
||||
guardianPhone: null,
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
reviewedAt: null,
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
} as never);
|
||||
@@ -112,9 +113,11 @@ describe('public invitations routes', () => {
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.message).toBe('Inscripción realizada con éxito');
|
||||
expect(body.attendee.fullName).toBe('Lucía Méndez');
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
expect(body.status).toBe('pre_registered');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(body.message).toContain('solicitud de inscripción');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
@@ -141,7 +144,7 @@ describe('public invitations routes', () => {
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('attendee_already_registered');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid inputs (missing required name/phone)', async () => {
|
||||
@@ -157,21 +160,67 @@ describe('public invitations routes', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('adds to the waitlist when the group is full', async () => {
|
||||
it('returns 409 when a pre-registration is already pending', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.count.mockResolvedValue(15); // capacity full
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
prisma.groupWaitlistEntry.create.mockResolvedValue({
|
||||
id: 'wl-1',
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
status: 'PENDING',
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: 'Lucía',
|
||||
lastName: 'Méndez',
|
||||
phone: '+54 9 11 2233-4455',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_pending');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already approved', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
status: 'APPROVED',
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
firstName: 'Lucía',
|
||||
lastName: 'Méndez',
|
||||
phone: '+54 9 11 2233-4455',
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_approved');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reactivates a rejected pre-registration back to pending', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Lucía Méndez',
|
||||
phone: '+5491122334455',
|
||||
email: 'lucia@test.com',
|
||||
notes: null,
|
||||
status: 'PENDING',
|
||||
status: 'REJECTED',
|
||||
reviewedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-19T10:00:00.000Z'),
|
||||
} as never);
|
||||
|
||||
const res = await app.request('/invitations/valid-token-123/join', {
|
||||
@@ -187,15 +236,15 @@ describe('public invitations routes', () => {
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
const body = await res.json();
|
||||
expect(body.status).toBe('waitlisted');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
||||
expect(body.status).toBe('pre_registered');
|
||||
expect(prisma.groupPreRegistration.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
status: 'PENDING',
|
||||
fullName: 'Lucía Méndez',
|
||||
phone: '+5491122334455',
|
||||
email: 'lucia@test.com',
|
||||
reviewedAt: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
365
apps/backend/test/preregistrations.test.ts
Normal file
365
apps/backend/test/preregistrations.test.ts
Normal file
@@ -0,0 +1,365 @@
|
||||
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const db = {
|
||||
group: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
attendee: {
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
},
|
||||
groupWaitlistEntry: {
|
||||
findFirst: mock(),
|
||||
create: mock(),
|
||||
},
|
||||
groupPreRegistration: {
|
||||
findMany: mock(),
|
||||
findFirst: mock(),
|
||||
count: mock(),
|
||||
create: mock(),
|
||||
update: 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: 'valid-token-123',
|
||||
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 preRegistration = (overrides: Record<string, unknown> = {}) => ({
|
||||
id: 'pre-1',
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
status: 'PENDING',
|
||||
reviewedAt: null,
|
||||
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,
|
||||
notifyToken: 'notify-1',
|
||||
createdAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
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 pre-registrations', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('GET /groups/:groupId/preregistrations', () => {
|
||||
it('lists pending pre-registrations in FIFO order with pagination', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findMany.mockResolvedValue([
|
||||
preRegistration({ id: 'pre-1', fullName: 'Ana García', createdAt: new Date('2026-09-08T10:00:00.000Z') }),
|
||||
preRegistration({ id: 'pre-2', fullName: 'Pedro López', createdAt: new Date('2026-09-09T10:00:00.000Z') }),
|
||||
] as never);
|
||||
prisma.groupPreRegistration.count.mockResolvedValue(2);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request('/groups/group-1/preregistrations');
|
||||
|
||||
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.data[0].status).toBe('PENDING');
|
||||
expect(data.pagination).toEqual({ page: 1, pageSize: 10, total: 2, totalPages: 1 });
|
||||
expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'PENDING' },
|
||||
skip: 0,
|
||||
take: 10,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
});
|
||||
|
||||
it('filters by status when provided', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findMany.mockResolvedValue([] as never);
|
||||
prisma.groupPreRegistration.count.mockResolvedValue(0);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations?status=REJECTED',
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.groupPreRegistration.findMany).toHaveBeenCalledWith({
|
||||
where: { groupId: 'group-1', status: 'REJECTED' },
|
||||
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/preregistrations');
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /groups/:groupId/preregistrations/:entryId/approve', () => {
|
||||
it('adds the person to the group when there is free capacity', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(null);
|
||||
prisma.attendee.create.mockResolvedValue(attendee() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.outcome).toBe('added');
|
||||
expect(body.attendee.fullName).toBe('Martín Gómez');
|
||||
expect(body.waitlistEntry).toBeNull();
|
||||
expect(prisma.attendee.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
notes: null,
|
||||
},
|
||||
});
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'APPROVED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('moves the person to the waitlist when the group is full', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(20); // capacity full
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(null);
|
||||
prisma.groupWaitlistEntry.create.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.outcome).toBe('waitlisted');
|
||||
expect(body.attendee).toBeNull();
|
||||
expect(body.waitlistEntry.fullName).toBe('Martín Gómez');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
expect(prisma.groupWaitlistEntry.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
groupId: 'group-1',
|
||||
fullName: 'Martín Gómez',
|
||||
phone: '+5491133445566',
|
||||
email: null,
|
||||
},
|
||||
});
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'APPROVED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('reuses an existing waitlist entry instead of duplicating it', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(20);
|
||||
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.groupWaitlistEntry.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the phone already belongs to a member', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.attendee.count.mockResolvedValue(5);
|
||||
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ 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();
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already reviewed', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(
|
||||
preRegistration({ status: 'APPROVED' }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_reviewed');
|
||||
expect(prisma.attendee.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns 404 when the pre-registration does not exist', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/missing/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it('rejects approval from a user who is not the owner', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/approve',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /groups/:groupId/preregistrations/:entryId/reject', () => {
|
||||
it('marks the pre-registration as rejected', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
|
||||
prisma.groupPreRegistration.update.mockResolvedValue(
|
||||
preRegistration({ status: 'REJECTED', reviewedAt: new Date('2026-09-20T10:00:00.000Z') }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.entry.status).toBe('REJECTED');
|
||||
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
|
||||
where: { id: 'pre-1' },
|
||||
data: { status: 'REJECTED', reviewedAt: expect.any(Date) },
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 409 when the pre-registration was already reviewed', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
prisma.groupPreRegistration.findFirst.mockResolvedValue(
|
||||
preRegistration({ status: 'REJECTED' }) as never,
|
||||
);
|
||||
|
||||
const res = await makeApp({ id: teacherId }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
const body = await res.json();
|
||||
expect(body.code).toBe('pre_registration_already_reviewed');
|
||||
expect(prisma.groupPreRegistration.update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects rejection from a user who is not the owner', async () => {
|
||||
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
|
||||
|
||||
const res = await makeApp({ id: 'other-user' }).request(
|
||||
'/groups/group-1/preregistrations/pre-1/reject',
|
||||
{ method: 'POST' },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(prisma.groupPreRegistration.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,23 +4,27 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type {
|
||||
AttendeeDto,
|
||||
GroupDto,
|
||||
GroupPreRegistrationDto,
|
||||
GroupWaitlistEntryDto,
|
||||
GroupRiskLevel,
|
||||
} from '@gruperly/shared'
|
||||
import { useToast } from '../../../components/ui'
|
||||
import {
|
||||
ApiError,
|
||||
approveGroupPreRegistration,
|
||||
getGroup,
|
||||
getGroupAttendees,
|
||||
getGroupPreRegistrations,
|
||||
getGroupsRiskOverview,
|
||||
getGroupWaitlist,
|
||||
getInviteToken,
|
||||
promoteGroupWaitlistEntry,
|
||||
rejectGroupPreRegistration,
|
||||
removeGroupWaitlistEntry,
|
||||
} from '../../../lib/api'
|
||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||
|
||||
export type ListSection = 'members' | 'waitlist'
|
||||
export type ListSection = 'members' | 'preregistrations' | 'waitlist'
|
||||
|
||||
type GroupDetailContextValue = {
|
||||
groupId: string
|
||||
@@ -34,6 +38,9 @@ type GroupDetailContextValue = {
|
||||
waitlistTotal: number
|
||||
waitlistPending: boolean
|
||||
firstWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
preRegistrations: GroupPreRegistrationDto[]
|
||||
preRegistrationsTotal: number
|
||||
preRegistrationsPending: boolean
|
||||
hasFreeCapacity: boolean
|
||||
inviteUrl: string | undefined
|
||||
invitePending: boolean
|
||||
@@ -51,12 +58,18 @@ type GroupDetailContextValue = {
|
||||
confirmRemoveAttendee: (promoteFromWaitlist: boolean) => void
|
||||
selectedWaitlistEntry: GroupWaitlistEntryDto | null
|
||||
setSelectedWaitlistEntry: (entry: GroupWaitlistEntryDto | null) => void
|
||||
selectedPreRegistration: GroupPreRegistrationDto | null
|
||||
setSelectedPreRegistration: (entry: GroupPreRegistrationDto | null) => void
|
||||
isSubmittingRemoval: boolean
|
||||
isSubmittingPromotion: boolean
|
||||
isSubmittingWaitlistRemoval: boolean
|
||||
isSubmittingApproval: boolean
|
||||
isSubmittingRejection: boolean
|
||||
isRegeneratingInvite: boolean
|
||||
promoteEntry: (entry: GroupWaitlistEntryDto) => void
|
||||
removeEntry: (entry: GroupWaitlistEntryDto) => void
|
||||
approvePreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||
rejectPreRegistration: (entry: GroupPreRegistrationDto) => void
|
||||
regenerateInvite: () => void
|
||||
copyInviteLink: () => Promise<void>
|
||||
copyWhatsappMessage: () => Promise<void>
|
||||
@@ -73,6 +86,7 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
const [listSection, setListSection] = useState<ListSection>('members')
|
||||
const [attendeeToRemove, setAttendeeToRemove] = useState<AttendeeDto | null>(null)
|
||||
const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState<GroupWaitlistEntryDto | null>(null)
|
||||
const [selectedPreRegistration, setSelectedPreRegistration] = useState<GroupPreRegistrationDto | null>(null)
|
||||
const [searchFilter, setSearchFilter] = useState('')
|
||||
|
||||
const groupQuery = useQuery({
|
||||
@@ -105,17 +119,30 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
enabled: Boolean(groupId),
|
||||
})
|
||||
|
||||
const preRegistrationsQuery = useQuery({
|
||||
queryKey: ['group-preregistrations', groupId],
|
||||
queryFn: () => getGroupPreRegistrations(groupId, 1, 100),
|
||||
enabled: Boolean(groupId),
|
||||
})
|
||||
|
||||
const group = groupQuery.data
|
||||
const attendees = useMemo(() => attendeesQuery.data?.data ?? [], [attendeesQuery.data])
|
||||
const attendeesTotal = attendeesQuery.data?.pagination?.total ?? attendees.length
|
||||
const waitlistEntries = useMemo(() => waitlistQuery.data?.data ?? [], [waitlistQuery.data])
|
||||
const waitlistTotal = waitlistQuery.data?.pagination?.total ?? waitlistEntries.length
|
||||
const preRegistrations = useMemo(
|
||||
() => preRegistrationsQuery.data?.data ?? [],
|
||||
[preRegistrationsQuery.data],
|
||||
)
|
||||
const preRegistrationsTotal =
|
||||
preRegistrationsQuery.data?.pagination?.total ?? preRegistrations.length
|
||||
const firstWaitlistEntry = waitlistEntries[0] ?? null
|
||||
const hasFreeCapacity = group?.capacity == null || attendeesTotal < group.capacity
|
||||
|
||||
const invalidateGroupQueries = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-attendees', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-waitlist', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group-preregistrations', groupId] })
|
||||
void queryClient.invalidateQueries({ queryKey: ['group', groupId] })
|
||||
}
|
||||
|
||||
@@ -161,10 +188,56 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
},
|
||||
})
|
||||
|
||||
const approvePreRegistrationMutation = useMutation({
|
||||
mutationFn: (entry: GroupPreRegistrationDto) =>
|
||||
approveGroupPreRegistration(groupId, entry.id),
|
||||
onSuccess: (result, entry) => {
|
||||
setSelectedPreRegistration(null)
|
||||
toast.success(
|
||||
result.outcome === 'added'
|
||||
? `${entry.fullName} ahora es miembro del grupo.`
|
||||
: `${entry.fullName} fue agregado a la lista de espera: el grupo está completo.`,
|
||||
)
|
||||
invalidateGroupQueries()
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
if (err instanceof ApiError) {
|
||||
if (err.problem?.code === 'attendee_already_registered') {
|
||||
toast.error('Ya hay un miembro con ese teléfono en el grupo. Puedes rechazar la pre-inscripción.')
|
||||
return
|
||||
}
|
||||
if (err.problem?.code === 'pre_registration_already_reviewed') {
|
||||
toast.error('Esta pre-inscripción ya fue revisada.')
|
||||
invalidateGroupQueries()
|
||||
return
|
||||
}
|
||||
}
|
||||
toast.error(err.message || 'No se pudo aprobar la pre-inscripción.')
|
||||
},
|
||||
})
|
||||
|
||||
const rejectPreRegistrationMutation = useMutation({
|
||||
mutationFn: (entry: GroupPreRegistrationDto) =>
|
||||
rejectGroupPreRegistration(groupId, entry.id),
|
||||
onSuccess: (_result, entry) => {
|
||||
setSelectedPreRegistration(null)
|
||||
toast.success(`La pre-inscripción de ${entry.fullName} fue rechazada.`)
|
||||
invalidateGroupQueries()
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
if (err instanceof ApiError && err.problem?.code === 'pre_registration_already_reviewed') {
|
||||
toast.error('Esta pre-inscripción ya fue revisada.')
|
||||
invalidateGroupQueries()
|
||||
return
|
||||
}
|
||||
toast.error(err.message || 'No se pudo rechazar la pre-inscripción.')
|
||||
},
|
||||
})
|
||||
|
||||
const inviteUrl = inviteTokenQuery.data?.inviteUrl
|
||||
const whatsappMessage =
|
||||
group && inviteUrl
|
||||
? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tus datos de inscripción en el siguiente enlace:\n${inviteUrl}`
|
||||
? `¡Hola! 👋 Te invito a unirte al grupo *${group.name}*.\n\nCompleta tu pre-inscripción en el siguiente enlace. El profesor revisará tu solicitud:\n${inviteUrl}`
|
||||
: ''
|
||||
const whatsappShareUrl = whatsappMessage
|
||||
? `https://wa.me/?text=${encodeURIComponent(whatsappMessage)}`
|
||||
@@ -215,6 +288,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
waitlistTotal,
|
||||
waitlistPending: waitlistQuery.isPending,
|
||||
firstWaitlistEntry,
|
||||
preRegistrations,
|
||||
preRegistrationsTotal,
|
||||
preRegistrationsPending: preRegistrationsQuery.isPending,
|
||||
hasFreeCapacity,
|
||||
inviteUrl,
|
||||
invitePending: inviteTokenQuery.isPending,
|
||||
@@ -235,9 +311,13 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
},
|
||||
selectedWaitlistEntry,
|
||||
setSelectedWaitlistEntry,
|
||||
selectedPreRegistration,
|
||||
setSelectedPreRegistration,
|
||||
isSubmittingRemoval: removeAttendeeMutation.isRemovingAttendee,
|
||||
isSubmittingPromotion: promoteWaitlistMutation.isPending,
|
||||
isSubmittingWaitlistRemoval: removeWaitlistEntryMutation.isPending,
|
||||
isSubmittingApproval: approvePreRegistrationMutation.isPending,
|
||||
isSubmittingRejection: rejectPreRegistrationMutation.isPending,
|
||||
isRegeneratingInvite: regenerateTokenMutation.isPending,
|
||||
promoteEntry: (entry) => {
|
||||
setSelectedWaitlistEntry(null)
|
||||
@@ -247,6 +327,12 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
setSelectedWaitlistEntry(null)
|
||||
removeWaitlistEntryMutation.mutate(entry)
|
||||
},
|
||||
approvePreRegistration: (entry) => {
|
||||
approvePreRegistrationMutation.mutate(entry)
|
||||
},
|
||||
rejectPreRegistration: (entry) => {
|
||||
rejectPreRegistrationMutation.mutate(entry)
|
||||
},
|
||||
regenerateInvite: () => regenerateTokenMutation.mutate(),
|
||||
copyInviteLink,
|
||||
copyWhatsappMessage,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { GroupHeader } from './GroupHeader'
|
||||
import { GroupInfoCard } from './GroupInfoCard'
|
||||
import { InviteLinkModal } from './InviteLinkModal'
|
||||
import { MembersWaitlistSection } from './MembersWaitlistSection'
|
||||
import { PreRegistrationDetailModal } from './PreRegistrationDetailModal'
|
||||
import { RemoveAttendeeModal } from './RemoveAttendeeModal'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
import { WaitlistEntryDetailModal } from './WaitlistEntryDetailModal'
|
||||
@@ -60,6 +61,7 @@ export function GroupDetailView() {
|
||||
onConfirm={confirmRemoveAttendee}
|
||||
/>
|
||||
<WaitlistEntryDetailModal />
|
||||
<PreRegistrationDetailModal />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -74,7 +74,7 @@ export function InviteLinkModal() {
|
||||
{`¡Hola! 👋 Te invito a unirte al grupo `}
|
||||
<strong>{group?.name}</strong>.
|
||||
{'\n\n'}
|
||||
Completa tus datos de inscripción en el siguiente enlace:
|
||||
Completa tu pre-inscripción en el siguiente enlace. El profesor revisará tu solicitud:
|
||||
{'\n'}
|
||||
<span className="break-all text-accent underline">{inviteUrl}</span>
|
||||
</div>
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Clock, Loader2, Plus, Search, Share2, Users } from 'lucide-react'
|
||||
import { Clock, Loader2, Plus, Search, Share2, UserCheck, Users } from 'lucide-react'
|
||||
import { Button, Input } from '../../../components/ui'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
import { MembersTable } from './MembersTable'
|
||||
import { PreRegistrationsTable } from './PreRegistrationsTable'
|
||||
import { WaitlistTable } from './WaitlistTable'
|
||||
|
||||
const TAB_CLASS =
|
||||
'flex min-h-10 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-xs font-semibold transition-[color,background-color,box-shadow] duration-150'
|
||||
|
||||
export function MembersWaitlistSection() {
|
||||
const {
|
||||
groupId, attendees, attendeesTotal, attendeesPending,
|
||||
waitlistEntries, waitlistTotal, waitlistPending,
|
||||
preRegistrations, preRegistrationsTotal, preRegistrationsPending,
|
||||
listSection, setListSection, searchFilter, setSearchFilter, openInviteModal,
|
||||
} = useGroupDetail()
|
||||
const navigate = useNavigate()
|
||||
@@ -21,6 +26,14 @@ export function MembersWaitlistSection() {
|
||||
(a.phone && a.phone.includes(query)) ||
|
||||
(a.email && a.email.toLowerCase().includes(query)),
|
||||
)
|
||||
const filteredPreRegistrations = preRegistrations.filter(
|
||||
(p) =>
|
||||
p.fullName.toLowerCase().includes(query) ||
|
||||
p.phone.includes(query) ||
|
||||
(p.email && p.email.toLowerCase().includes(query)),
|
||||
)
|
||||
|
||||
const showSearch = listSection === 'members' || listSection === 'preregistrations'
|
||||
|
||||
return (
|
||||
// Radios concéntricos: `rounded-2xl` (16px) con `p-2` (8px) deja a las
|
||||
@@ -32,7 +45,7 @@ export function MembersWaitlistSection() {
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label="Listado del grupo"
|
||||
className="flex w-full items-center gap-1 rounded-lg bg-surface p-0.5 shadow-xs sm:w-[26rem]"
|
||||
className="flex w-full items-center gap-1 rounded-lg bg-surface p-0.5 shadow-xs sm:w-[36rem]"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -40,7 +53,7 @@ export function MembersWaitlistSection() {
|
||||
aria-selected={listSection === 'members'}
|
||||
onClick={() => setListSection('members')}
|
||||
className={cn(
|
||||
'flex min-h-10 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-xs font-semibold transition-[color,background-color,box-shadow] duration-150',
|
||||
TAB_CLASS,
|
||||
listSection === 'members'
|
||||
? 'bg-accent text-on-accent shadow-xs'
|
||||
: 'text-foreground/80 hover:bg-primary-soft hover:text-primary',
|
||||
@@ -51,13 +64,30 @@ export function MembersWaitlistSection() {
|
||||
Miembros ({attendeesTotal})
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={listSection === 'preregistrations'}
|
||||
onClick={() => setListSection('preregistrations')}
|
||||
className={cn(
|
||||
TAB_CLASS,
|
||||
listSection === 'preregistrations'
|
||||
? 'bg-accent text-on-accent shadow-xs'
|
||||
: 'text-foreground/80 hover:bg-primary-soft hover:text-primary',
|
||||
)}
|
||||
>
|
||||
<UserCheck className="size-4 shrink-0" />
|
||||
<span className="whitespace-nowrap">
|
||||
Pre-inscripciones ({preRegistrationsTotal})
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={listSection === 'waitlist'}
|
||||
onClick={() => setListSection('waitlist')}
|
||||
className={cn(
|
||||
'flex min-h-10 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-xs font-semibold transition-[color,background-color,box-shadow] duration-150',
|
||||
TAB_CLASS,
|
||||
listSection === 'waitlist'
|
||||
? 'bg-accent text-on-accent shadow-xs'
|
||||
: 'text-foreground/80 hover:bg-primary-soft hover:text-primary',
|
||||
@@ -68,14 +98,14 @@ export function MembersWaitlistSection() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{listSection === 'members' ? (
|
||||
{showSearch ? (
|
||||
<div className="relative w-full sm:w-64">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground/70" />
|
||||
<Input
|
||||
placeholder="Buscar por nombre o teléfono..."
|
||||
value={searchFilter}
|
||||
onChange={(e) => setSearchFilter(e.target.value)}
|
||||
aria-label="Buscar miembros"
|
||||
aria-label="Buscar en el listado"
|
||||
className="h-10 rounded-lg border-transparent pl-9 shadow-xs placeholder:text-foreground/80"
|
||||
/>
|
||||
</div>
|
||||
@@ -85,7 +115,9 @@ export function MembersWaitlistSection() {
|
||||
<p className="text-xs leading-relaxed text-foreground/80">
|
||||
{listSection === 'members'
|
||||
? 'Listado de todos los miembros incorporados al grupo.'
|
||||
: 'Personas que esperan un cupo libre en el grupo. Al pasar a alguien al grupo, se crea automáticamente su registro como miembro.'}
|
||||
: listSection === 'preregistrations'
|
||||
? 'Personas que se inscribieron a través del enlace compartido. Al aprobar, entran al grupo; si el grupo está lleno, pasan a la lista de espera.'
|
||||
: 'Personas que esperan un cupo libre en el grupo. Al pasar a alguien al grupo, se crea automáticamente su registro como miembro.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -135,7 +167,48 @@ export function MembersWaitlistSection() {
|
||||
|
||||
{filteredAttendees.length > 0 ? <MembersTable attendees={filteredAttendees} /> : null}
|
||||
</>
|
||||
) : (
|
||||
) : null}
|
||||
|
||||
{listSection === 'preregistrations' ? (
|
||||
<div className="space-y-4">
|
||||
{preRegistrationsPending ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="size-6 animate-spin text-accent" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!preRegistrationsPending && preRegistrations.length === 0 ? (
|
||||
<div className="rounded-lg bg-primary-soft/50 px-4 py-10 text-center">
|
||||
<UserCheck className="mx-auto mb-2 size-10 text-foreground/40" />
|
||||
<p className="text-sm font-semibold text-primary">
|
||||
No hay pre-inscripciones pendientes
|
||||
</p>
|
||||
<p className="mx-auto mt-1 max-w-sm text-sm text-foreground/80">
|
||||
Cuando alguien se inscriba a través del enlace compartido, aparecerá aquí para que
|
||||
revises y apruebes su lugar.
|
||||
</p>
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button variant="outline" onClick={openInviteModal} className="w-full sm:w-auto">
|
||||
<Share2 className="size-4" />
|
||||
Compartir Enlace
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{preRegistrations.length > 0 && filteredPreRegistrations.length === 0 ? (
|
||||
<div className="py-8 text-center text-sm text-foreground/80">
|
||||
No se encontraron pre-inscripciones que coincidan con la búsqueda.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{filteredPreRegistrations.length > 0 ? (
|
||||
<PreRegistrationsTable entries={filteredPreRegistrations} />
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{listSection === 'waitlist' ? (
|
||||
<div className="space-y-4">
|
||||
{waitlistPending ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
@@ -156,7 +229,7 @@ export function MembersWaitlistSection() {
|
||||
|
||||
{waitlistEntries.length > 0 ? <WaitlistTable entries={waitlistEntries} /> : null}
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Ban, Loader2, Mail, MessageCircle, Phone, UserCheck } from 'lucide-react'
|
||||
import { Button, Modal } from '../../../components/ui'
|
||||
import { DetailRow } from './DetailRow'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function PreRegistrationDetailModal() {
|
||||
const {
|
||||
selectedPreRegistration,
|
||||
setSelectedPreRegistration,
|
||||
hasFreeCapacity,
|
||||
approvePreRegistration,
|
||||
rejectPreRegistration,
|
||||
isSubmittingApproval,
|
||||
isSubmittingRejection,
|
||||
} = useGroupDetail()
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={selectedPreRegistration !== null}
|
||||
onClose={() => setSelectedPreRegistration(null)}
|
||||
title="Detalle de la pre-inscripción"
|
||||
maxWidth="sm"
|
||||
>
|
||||
{selectedPreRegistration ? (
|
||||
<div className="space-y-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex size-12 items-center justify-center rounded-full bg-accent/10 text-lg font-bold text-accent">
|
||||
{selectedPreRegistration.fullName.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-lg font-semibold text-primary">
|
||||
{selectedPreRegistration.fullName}
|
||||
</p>
|
||||
<p className="text-xs text-foreground/50">
|
||||
Solicitado el{' '}
|
||||
{new Date(selectedPreRegistration.createdAt).toLocaleDateString('es-ES', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 divide-y divide-border rounded-xl border border-border bg-primary-soft/30">
|
||||
<DetailRow icon={<Phone className="size-4 text-accent" />} label="Teléfono">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-primary">{selectedPreRegistration.phone}</span>
|
||||
<a
|
||||
href={`https://wa.me/${selectedPreRegistration.phone.replace(/\D/g, '')}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs font-medium text-success transition-colors hover:text-success/80"
|
||||
>
|
||||
<MessageCircle className="size-3.5" />
|
||||
<span>WhatsApp</span>
|
||||
</a>
|
||||
</div>
|
||||
</DetailRow>
|
||||
|
||||
{selectedPreRegistration.email ? (
|
||||
<DetailRow icon={<Mail className="size-4 text-accent" />} label="Email">
|
||||
<a
|
||||
href={`mailto:${selectedPreRegistration.email}`}
|
||||
className="text-primary transition-colors hover:text-accent"
|
||||
>
|
||||
{selectedPreRegistration.email}
|
||||
</a>
|
||||
</DetailRow>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{!hasFreeCapacity ? (
|
||||
<p className="rounded-xl border border-border bg-primary-soft/30 px-4 py-3 text-xs text-foreground/70">
|
||||
El grupo alcanzó su cupo de miembros. Si aprobás, esta persona quedará en la lista de
|
||||
espera hasta que se libere un lugar.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-1 gap-2.5 border-t border-border pt-2">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => approvePreRegistration(selectedPreRegistration)}
|
||||
disabled={isSubmittingApproval || isSubmittingRejection}
|
||||
className="gap-2"
|
||||
>
|
||||
{isSubmittingApproval ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<UserCheck className="size-4" />
|
||||
)}
|
||||
<span>Aprobar</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => rejectPreRegistration(selectedPreRegistration)}
|
||||
disabled={isSubmittingApproval || isSubmittingRejection}
|
||||
className="gap-2 border border-danger/20 text-danger hover:bg-danger/10 hover:text-danger"
|
||||
>
|
||||
{isSubmittingRejection ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Ban className="size-4" />
|
||||
)}
|
||||
Rechazar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { GroupPreRegistrationDto } from '@gruperly/shared'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function PreRegistrationsTable({ entries }: { entries: GroupPreRegistrationDto[] }) {
|
||||
const { setSelectedPreRegistration } = useGroupDetail()
|
||||
|
||||
return (
|
||||
<table className="w-full table-fixed text-left text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border/70 text-xs font-semibold text-foreground/80">
|
||||
<th scope="col" className="w-[46%] px-3 pb-2">Nombre</th>
|
||||
<th scope="col" className="px-3 pb-2">Teléfono</th>
|
||||
<th scope="col" className="px-3 pb-2">Solicitado</th>
|
||||
<th scope="col" className="w-9 px-1 pb-2">
|
||||
<span className="sr-only">Detalle</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((entry) => (
|
||||
<tr
|
||||
key={entry.id}
|
||||
className="group cursor-pointer border-b border-border/70 transition-colors last:border-b-0 hover:bg-primary-soft/60"
|
||||
onClick={() => setSelectedPreRegistration(entry)}
|
||||
>
|
||||
<td className="px-3 py-2.5">
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-semibold text-accent">
|
||||
{entry.fullName.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium text-primary" title={entry.fullName}>
|
||||
{entry.fullName}
|
||||
</p>
|
||||
{entry.email ? (
|
||||
<p className="truncate text-xs text-foreground/70" title={entry.email}>
|
||||
{entry.email}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="min-w-0 px-3 py-2.5 text-foreground/80">
|
||||
<span className="block truncate tabular-nums" title={entry.phone}>
|
||||
{entry.phone}
|
||||
</span>
|
||||
</td>
|
||||
<td className="min-w-0 px-3 py-2.5 text-xs text-foreground/70">
|
||||
{new Date(entry.createdAt).toLocaleDateString('es-ES', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
})}
|
||||
</td>
|
||||
<td className="w-9 px-1 py-2.5 text-foreground/50">
|
||||
<ChevronRight className="ml-auto size-4 transition-colors group-hover:text-accent" />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
@@ -43,6 +43,11 @@ export function GroupInviteSummary() {
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<p className="mt-3 text-xs leading-relaxed text-foreground/60">
|
||||
Al completar el formulario envías una solicitud de pre-inscripción. El profesor revisará tus
|
||||
datos y te confirmará el lugar.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -104,7 +104,7 @@ export function JoinForm() {
|
||||
className="w-full gap-2 py-2.5 text-sm font-semibold"
|
||||
>
|
||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
<span>Completar Inscripción</span>
|
||||
<span>Enviar Solicitud</span>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -4,11 +4,6 @@ import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import type { GroupInviteInfoDto } from '@gruperly/shared'
|
||||
import { ApiError, getInviteInfo, joinViaInvite } from '../../lib/api'
|
||||
|
||||
type RegisteredAttendee = {
|
||||
fullName: string
|
||||
phone: string | null
|
||||
}
|
||||
|
||||
type JoinGroupContextValue = {
|
||||
token: string
|
||||
group: GroupInviteInfoDto | undefined
|
||||
@@ -23,8 +18,7 @@ type JoinGroupContextValue = {
|
||||
email: string
|
||||
setEmail: (value: string) => void
|
||||
errorMessage: string | null
|
||||
registeredAttendee: RegisteredAttendee | null
|
||||
waitlistMessage: string | null
|
||||
preRegistrationMessage: string | null
|
||||
submit: () => void
|
||||
isSubmitting: boolean
|
||||
}
|
||||
@@ -37,8 +31,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
const [phone, setPhone] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const [registeredAttendee, setRegisteredAttendee] = useState<RegisteredAttendee | null>(null)
|
||||
const [waitlistMessage, setWaitlistMessage] = useState<string | null>(null)
|
||||
const [preRegistrationMessage, setPreRegistrationMessage] = useState<string | null>(null)
|
||||
|
||||
const inviteQuery = useQuery({
|
||||
queryKey: ['public-invite', token],
|
||||
@@ -57,16 +50,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
}),
|
||||
onSuccess: (data) => {
|
||||
setErrorMessage(null)
|
||||
if (data.status === 'waitlisted') {
|
||||
setRegisteredAttendee(null)
|
||||
setWaitlistMessage(data.message)
|
||||
return
|
||||
}
|
||||
setWaitlistMessage(null)
|
||||
setRegisteredAttendee({
|
||||
fullName: data.attendee?.fullName ?? `${firstName.trim()} ${lastName.trim()}`.trim(),
|
||||
phone: data.attendee?.phone ?? null,
|
||||
})
|
||||
setPreRegistrationMessage(data.message)
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
if (error instanceof ApiError) {
|
||||
@@ -76,6 +60,16 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
)
|
||||
return
|
||||
}
|
||||
if (error.problem?.code === 'pre_registration_already_pending') {
|
||||
setErrorMessage(
|
||||
'Ya enviaste una solicitud de inscripción para este grupo y está pendiente de revisión. Pronto recibirás novedades.',
|
||||
)
|
||||
return
|
||||
}
|
||||
if (error.problem?.code === 'pre_registration_already_approved') {
|
||||
setErrorMessage('Tu inscripción para este grupo ya fue aprobada.')
|
||||
return
|
||||
}
|
||||
setErrorMessage(error.message || 'Error al procesar la inscripción.')
|
||||
return
|
||||
}
|
||||
@@ -110,8 +104,7 @@ export function JoinGroupProvider({ token, children }: { token: string; children
|
||||
email,
|
||||
setEmail,
|
||||
errorMessage,
|
||||
registeredAttendee,
|
||||
waitlistMessage,
|
||||
preRegistrationMessage,
|
||||
submit,
|
||||
isSubmitting: joinMutation.isPending,
|
||||
}
|
||||
|
||||
@@ -3,12 +3,11 @@ import { PublicFooter, PublicHeader } from '../../components/layout'
|
||||
import { GroupInviteSummary } from './GroupInviteSummary'
|
||||
import { InvalidInviteCard } from './InvalidInviteCard'
|
||||
import { JoinForm } from './JoinForm'
|
||||
import { JoinSuccessCard } from './JoinSuccessCard'
|
||||
import { useJoinGroup } from './JoinGroupProvider'
|
||||
import { WaitlistNoticeCard } from './WaitlistNoticeCard'
|
||||
import { PreRegistrationNoticeCard } from './PreRegistrationNoticeCard'
|
||||
|
||||
export function JoinGroupView() {
|
||||
const { group, invitePending, inviteFailed, registeredAttendee, waitlistMessage } = useJoinGroup()
|
||||
const { group, invitePending, inviteFailed, preRegistrationMessage } = useJoinGroup()
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen flex-col justify-between bg-background text-primary selection:bg-accent selection:text-white">
|
||||
@@ -25,10 +24,9 @@ export function JoinGroupView() {
|
||||
|
||||
{inviteFailed || (!group && !invitePending) ? <InvalidInviteCard /> : null}
|
||||
|
||||
{registeredAttendee ? <JoinSuccessCard /> : null}
|
||||
{waitlistMessage ? <WaitlistNoticeCard /> : null}
|
||||
{preRegistrationMessage ? <PreRegistrationNoticeCard /> : null}
|
||||
|
||||
{!registeredAttendee && !waitlistMessage && group ? (
|
||||
{!preRegistrationMessage && group ? (
|
||||
<div className="space-y-6 rounded-2xl border border-border bg-surface p-6 shadow-xl sm:p-8">
|
||||
<GroupInviteSummary />
|
||||
<JoinForm />
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { CheckCircle2 } from 'lucide-react'
|
||||
import { Badge } from '../../components/ui'
|
||||
import { useJoinGroup } from './JoinGroupProvider'
|
||||
|
||||
export function JoinSuccessCard() {
|
||||
const { group, registeredAttendee } = useJoinGroup()
|
||||
if (!group || !registeredAttendee) return null
|
||||
|
||||
return (
|
||||
<div className="animate-step-enter space-y-5 rounded-2xl border border-success/30 bg-surface p-6 text-center shadow-xl sm:p-8">
|
||||
<div className="mx-auto flex size-16 items-center justify-center rounded-full bg-success-soft text-success">
|
||||
<CheckCircle2 className="size-10" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Badge variant="success" className="mb-2">
|
||||
Registro Confirmado
|
||||
</Badge>
|
||||
<h1 className="text-2xl font-bold text-primary">¡Inscripción Exitosa!</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-foreground/70">
|
||||
Tus datos han sido registrados con éxito en el grupo{' '}
|
||||
<strong className="font-semibold text-primary">{group.name}</strong>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-xl border border-border bg-primary-soft/50 p-4 text-left text-xs">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Profesor:</span>
|
||||
<span className="font-semibold text-primary">{group.teacherName}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Alumno:</span>
|
||||
<span className="font-semibold text-primary">{registeredAttendee.fullName}</span>
|
||||
</div>
|
||||
{registeredAttendee.phone ? (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-foreground/60">Teléfono registrado:</span>
|
||||
<span className="font-semibold text-primary">{registeredAttendee.phone}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-foreground/60">
|
||||
El profesor se pondrá en contacto contigo a la brevedad por WhatsApp para darte la bienvenida y
|
||||
coordinar los detalles de la clase.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,9 +2,9 @@ import { Clock } from 'lucide-react'
|
||||
import { Badge } from '../../components/ui'
|
||||
import { useJoinGroup } from './JoinGroupProvider'
|
||||
|
||||
export function WaitlistNoticeCard() {
|
||||
const { group, waitlistMessage } = useJoinGroup()
|
||||
if (!group || !waitlistMessage) return null
|
||||
export function PreRegistrationNoticeCard() {
|
||||
const { group, preRegistrationMessage } = useJoinGroup()
|
||||
if (!group || !preRegistrationMessage) return null
|
||||
|
||||
return (
|
||||
<div className="animate-step-enter space-y-5 rounded-2xl border border-accent/30 bg-surface p-6 text-center shadow-xl sm:p-8">
|
||||
@@ -14,15 +14,16 @@ export function WaitlistNoticeCard() {
|
||||
|
||||
<div>
|
||||
<Badge variant="neutral" className="mb-2">
|
||||
Lista de Espera
|
||||
Pre-inscripción
|
||||
</Badge>
|
||||
<h1 className="text-2xl font-bold text-primary">Cupo completo</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-foreground/70">{waitlistMessage}</p>
|
||||
<h1 className="text-2xl font-bold text-primary">Solicitud enviada</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-foreground/70">{preRegistrationMessage}</p>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-foreground/60">
|
||||
El profesor se pondrá en contacto contigo cuando haya un lugar disponible en{' '}
|
||||
<strong className="font-semibold text-primary">{group.name}</strong>.
|
||||
El profesor revisará tu solicitud para el grupo{' '}
|
||||
<strong className="font-semibold text-primary">{group.name}</strong> y se pondrá en contacto
|
||||
contigo por WhatsApp para confirmarte el lugar.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
AbsenceDetails,
|
||||
ApproveGroupPreRegistrationResult,
|
||||
AttendeeDto,
|
||||
AttendeeHistory,
|
||||
AttendeeList,
|
||||
@@ -20,6 +21,7 @@ import type {
|
||||
GroupDto,
|
||||
GroupInviteInfoDto,
|
||||
GroupList,
|
||||
GroupPreRegistrationList,
|
||||
GroupRiskSummary,
|
||||
GroupsRiskOverview,
|
||||
GroupWaitlistEntryDto,
|
||||
@@ -36,6 +38,7 @@ import type {
|
||||
ProblemDetails,
|
||||
PromoteGroupWaitlistEntryResult,
|
||||
PublicNotifyAbsence,
|
||||
RejectGroupPreRegistrationResult,
|
||||
RemoveAttendeeResult,
|
||||
RemoveGroupWaitlistEntryResult,
|
||||
SessionStudents,
|
||||
@@ -180,6 +183,23 @@ export const removeGroupWaitlistEntry = (groupId: string, entryId: string) =>
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
export const getGroupPreRegistrations = (groupId: string, page = 1, pageSize = 100) =>
|
||||
apiFetch<GroupPreRegistrationList>(
|
||||
`/api/v1/groups/${groupId}/preregistrations?page=${page}&pageSize=${pageSize}`,
|
||||
)
|
||||
|
||||
export const approveGroupPreRegistration = (groupId: string, entryId: string) =>
|
||||
apiFetch<ApproveGroupPreRegistrationResult>(
|
||||
`/api/v1/groups/${groupId}/preregistrations/${entryId}/approve`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
|
||||
export const rejectGroupPreRegistration = (groupId: string, entryId: string) =>
|
||||
apiFetch<RejectGroupPreRegistrationResult>(
|
||||
`/api/v1/groups/${groupId}/preregistrations/${entryId}/reject`,
|
||||
{ method: 'POST' },
|
||||
)
|
||||
|
||||
export const removeGroupAttendee = (
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
|
||||
@@ -10,5 +10,6 @@ export * from './schemas/home.js';
|
||||
export * from './schemas/onboarding.js';
|
||||
export * from './schemas/pagination.js';
|
||||
export * from './schemas/payments.js';
|
||||
export * from './schemas/preregistrations.js';
|
||||
export * from './schemas/problem-details.js';
|
||||
export * from './schemas/waitlist.js';
|
||||
@@ -77,7 +77,7 @@ export const JoinGroupViaInviteSchema = z.object({
|
||||
export type JoinGroupViaInvite = z.output<typeof JoinGroupViaInviteSchema>;
|
||||
|
||||
export const JoinGroupViaInviteResultSchema = z.object({
|
||||
status: z.enum(['registered', 'waitlisted']),
|
||||
status: z.literal('pre_registered'),
|
||||
message: z.string(),
|
||||
attendee: AttendeeDtoSchema.nullable(),
|
||||
});
|
||||
|
||||
54
packages/shared/src/schemas/preregistrations.ts
Normal file
54
packages/shared/src/schemas/preregistrations.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { z } from 'zod';
|
||||
import { AttendeeDtoSchema } from './attendees.js';
|
||||
import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js';
|
||||
import { GroupWaitlistEntryDtoSchema } from './waitlist.js';
|
||||
|
||||
const isoDateTimeSchema = z.string().datetime();
|
||||
const pageSchema = createPageSchema();
|
||||
const pageSizeSchema = createPageSizeSchema(10);
|
||||
const paginationSchema = createPaginationSchema();
|
||||
|
||||
export const preRegistrationStatusSchema = z.enum(['PENDING', 'APPROVED', 'REJECTED']);
|
||||
export type PreRegistrationStatus = z.output<typeof preRegistrationStatusSchema>;
|
||||
|
||||
export const GroupPreRegistrationDtoSchema = z.object({
|
||||
id: z.string(),
|
||||
groupId: z.string(),
|
||||
fullName: z.string(),
|
||||
phone: z.string(),
|
||||
email: z.string().nullable(),
|
||||
status: preRegistrationStatusSchema,
|
||||
reviewedAt: isoDateTimeSchema.nullable(),
|
||||
createdAt: isoDateTimeSchema,
|
||||
updatedAt: isoDateTimeSchema,
|
||||
});
|
||||
export type GroupPreRegistrationDto = z.output<typeof GroupPreRegistrationDtoSchema>;
|
||||
|
||||
export const GroupPreRegistrationQuerySchema = z.object({
|
||||
page: pageSchema,
|
||||
pageSize: pageSizeSchema,
|
||||
status: preRegistrationStatusSchema.optional(),
|
||||
});
|
||||
export type GroupPreRegistrationQuery = z.output<typeof GroupPreRegistrationQuerySchema>;
|
||||
|
||||
export const GroupPreRegistrationListSchema = z.object({
|
||||
data: z.array(GroupPreRegistrationDtoSchema),
|
||||
pagination: paginationSchema,
|
||||
});
|
||||
export type GroupPreRegistrationList = z.output<typeof GroupPreRegistrationListSchema>;
|
||||
|
||||
export const ApproveGroupPreRegistrationResultSchema = z.object({
|
||||
outcome: z.enum(['added', 'waitlisted']),
|
||||
attendee: AttendeeDtoSchema.nullable(),
|
||||
waitlistEntry: GroupWaitlistEntryDtoSchema.nullable(),
|
||||
});
|
||||
export type ApproveGroupPreRegistrationResult = z.output<
|
||||
typeof ApproveGroupPreRegistrationResultSchema
|
||||
>;
|
||||
|
||||
export const RejectGroupPreRegistrationResultSchema = z.object({
|
||||
entry: GroupPreRegistrationDtoSchema,
|
||||
});
|
||||
export type RejectGroupPreRegistrationResult = z.output<
|
||||
typeof RejectGroupPreRegistrationResultSchema
|
||||
>;
|
||||
Reference in New Issue
Block a user