From 45a1f502319a5f7dab5e316b2c6da5380ddf961c Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 29 Sep 2026 15:25:24 -0300 Subject: [PATCH 1/6] 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`. --- AGENTS.md | 2 +- .../migration.sql | 26 ++ apps/backend/prisma/models/domain.prisma | 25 ++ .../features/approve/route.ts | 19 + .../features/approve/use-case.ts | 117 ++++++ .../features/get-all/route.ts | 24 ++ .../features/get-all/use-case.ts | 54 +++ .../features/reject/route.ts | 19 + .../features/reject/use-case.ts | 56 +++ .../modules/group-preregistrations/index.ts | 1 + .../group-preregistrations/lib/helpers.ts | 29 ++ .../modules/group-preregistrations/routes.ts | 12 + apps/backend/src/modules/groups/routes.ts | 2 + .../features/join-via-invite/use-case.ts | 87 +++-- apps/backend/test/invitations.test.ts | 101 +++-- apps/backend/test/preregistrations.test.ts | 365 ++++++++++++++++++ .../groups/detail/GroupDetailProvider.tsx | 90 ++++- .../groups/detail/GroupDetailView.tsx | 2 + .../groups/detail/InviteLinkModal.tsx | 2 +- .../groups/detail/MembersWaitlistSection.tsx | 91 ++++- .../detail/PreRegistrationDetailModal.tsx | 112 ++++++ .../groups/detail/PreRegistrationsTable.tsx | 63 +++ .../src/features/join/GroupInviteSummary.tsx | 5 + apps/web/src/features/join/JoinForm.tsx | 2 +- .../src/features/join/JoinGroupProvider.tsx | 37 +- apps/web/src/features/join/JoinGroupView.tsx | 12 +- .../web/src/features/join/JoinSuccessCard.tsx | 49 --- ...Card.tsx => PreRegistrationNoticeCard.tsx} | 19 +- apps/web/src/lib/api.ts | 20 + packages/shared/src/index.ts | 1 + packages/shared/src/schemas/attendees.ts | 2 +- .../shared/src/schemas/preregistrations.ts | 54 +++ 32 files changed, 1335 insertions(+), 165 deletions(-) create mode 100644 apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql create mode 100644 apps/backend/src/modules/group-preregistrations/features/approve/route.ts create mode 100644 apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts create mode 100644 apps/backend/src/modules/group-preregistrations/features/get-all/route.ts create mode 100644 apps/backend/src/modules/group-preregistrations/features/get-all/use-case.ts create mode 100644 apps/backend/src/modules/group-preregistrations/features/reject/route.ts create mode 100644 apps/backend/src/modules/group-preregistrations/features/reject/use-case.ts create mode 100644 apps/backend/src/modules/group-preregistrations/index.ts create mode 100644 apps/backend/src/modules/group-preregistrations/lib/helpers.ts create mode 100644 apps/backend/src/modules/group-preregistrations/routes.ts create mode 100644 apps/backend/test/preregistrations.test.ts create mode 100644 apps/web/src/features/groups/detail/PreRegistrationDetailModal.tsx create mode 100644 apps/web/src/features/groups/detail/PreRegistrationsTable.tsx delete mode 100644 apps/web/src/features/join/JoinSuccessCard.tsx rename apps/web/src/features/join/{WaitlistNoticeCard.tsx => PreRegistrationNoticeCard.tsx} (61%) create mode 100644 packages/shared/src/schemas/preregistrations.ts diff --git a/AGENTS.md b/AGENTS.md index 363e497..9b42227 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`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). diff --git a/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql b/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql new file mode 100644 index 0000000..1c25d68 --- /dev/null +++ b/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql @@ -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; diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma index 713fa71..54b59e5 100644 --- a/apps/backend/prisma/models/domain.prisma +++ b/apps/backend/prisma/models/domain.prisma @@ -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 diff --git a/apps/backend/src/modules/group-preregistrations/features/approve/route.ts b/apps/backend/src/modules/group-preregistrations/features/approve/route.ts new file mode 100644 index 0000000..c4d5e74 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/approve/route.ts @@ -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; diff --git a/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts new file mode 100644 index 0000000..00acb92 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/approve/use-case.ts @@ -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; + unitOfWork?: UnitOfWork; +}; + +export class ApproveGroupPreRegistration { + constructor(private readonly deps: ApproveGroupPreRegistrationDeps = {}) {} + + async execute( + groupId: string, + entryId: string, + userId: string, + ): Promise> { + 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> => { + 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), + }); + }, + ); + } +} diff --git a/apps/backend/src/modules/group-preregistrations/features/get-all/route.ts b/apps/backend/src/modules/group-preregistrations/features/get-all/route.ts new file mode 100644 index 0000000..18c84d6 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/get-all/route.ts @@ -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; diff --git a/apps/backend/src/modules/group-preregistrations/features/get-all/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/get-all/use-case.ts new file mode 100644 index 0000000..3be4276 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/get-all/use-case.ts @@ -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; +}; + +export class ListGroupPreRegistrations { + constructor(private readonly deps: ListGroupPreRegistrationsDeps = {}) {} + + async execute( + groupId: string, + userId: string, + query: GroupPreRegistrationQuery, + ): Promise> { + 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), + }); + } +} diff --git a/apps/backend/src/modules/group-preregistrations/features/reject/route.ts b/apps/backend/src/modules/group-preregistrations/features/reject/route.ts new file mode 100644 index 0000000..472b03c --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/reject/route.ts @@ -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; diff --git a/apps/backend/src/modules/group-preregistrations/features/reject/use-case.ts b/apps/backend/src/modules/group-preregistrations/features/reject/use-case.ts new file mode 100644 index 0000000..368dff9 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/features/reject/use-case.ts @@ -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; +}; + +export class RejectGroupPreRegistration { + constructor(private readonly deps: RejectGroupPreRegistrationDeps = {}) {} + + async execute( + groupId: string, + entryId: string, + userId: string, + ): Promise> { + 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), + }); + } +} diff --git a/apps/backend/src/modules/group-preregistrations/index.ts b/apps/backend/src/modules/group-preregistrations/index.ts new file mode 100644 index 0000000..f63b27a --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/index.ts @@ -0,0 +1 @@ +export { default as groupPreRegistrationRoutes } from './routes'; diff --git a/apps/backend/src/modules/group-preregistrations/lib/helpers.ts b/apps/backend/src/modules/group-preregistrations/lib/helpers.ts new file mode 100644 index 0000000..8a1c337 --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/lib/helpers.ts @@ -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(), + }; +} diff --git a/apps/backend/src/modules/group-preregistrations/routes.ts b/apps/backend/src/modules/group-preregistrations/routes.ts new file mode 100644 index 0000000..31f5a2c --- /dev/null +++ b/apps/backend/src/modules/group-preregistrations/routes.ts @@ -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; diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts index 0b1197b..603ca8b 100644 --- a/apps/backend/src/modules/groups/routes.ts +++ b/apps/backend/src/modules/groups/routes.ts @@ -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); diff --git a/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts index f07fe86..8bbe0a5 100644 --- a/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts +++ b/apps/backend/src/modules/invitations/features/join-via-invite/use-case.ts @@ -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; + db?: Pick; }; 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.', }); } -} \ No newline at end of file +} diff --git a/apps/backend/test/invitations.test.ts b/apps/backend/test/invitations.test.ts index 407963b..bb41613 100644 --- a/apps/backend/test/invitations.test.ts +++ b/apps/backend/test/invitations.test.ts @@ -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, }, }); }); diff --git a/apps/backend/test/preregistrations.test.ts b/apps/backend/test/preregistrations.test.ts new file mode 100644 index 0000000..c4627a5 --- /dev/null +++ b/apps/backend/test/preregistrations.test.ts @@ -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) => cb(db)); + execute = mock(async (cb: (tx: unknown) => Promise) => 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 = {}) => ({ + 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 = {}) => ({ + 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 = {}) => ({ + 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(); + }); + }); +}); diff --git a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx index 5cf476e..c6cae7c 100644 --- a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx @@ -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 copyWhatsappMessage: () => Promise @@ -73,6 +86,7 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch const [listSection, setListSection] = useState('members') const [attendeeToRemove, setAttendeeToRemove] = useState(null) const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState(null) + const [selectedPreRegistration, setSelectedPreRegistration] = useState(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, diff --git a/apps/web/src/features/groups/detail/GroupDetailView.tsx b/apps/web/src/features/groups/detail/GroupDetailView.tsx index c3b0eb5..0443279 100644 --- a/apps/web/src/features/groups/detail/GroupDetailView.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailView.tsx @@ -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} /> + ) } \ No newline at end of file diff --git a/apps/web/src/features/groups/detail/InviteLinkModal.tsx b/apps/web/src/features/groups/detail/InviteLinkModal.tsx index 2a29b80..ac26162 100644 --- a/apps/web/src/features/groups/detail/InviteLinkModal.tsx +++ b/apps/web/src/features/groups/detail/InviteLinkModal.tsx @@ -74,7 +74,7 @@ export function InviteLinkModal() { {`¡Hola! 👋 Te invito a unirte al grupo `} {group?.name}. {'\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'} {inviteUrl} diff --git a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx index 9994d47..ac09031 100644 --- a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx +++ b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx @@ -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() {
+
- {listSection === 'members' ? ( + {showSearch ? (
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" />
@@ -85,7 +115,9 @@ export function MembersWaitlistSection() {

{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.'}

@@ -135,7 +167,48 @@ export function MembersWaitlistSection() { {filteredAttendees.length > 0 ? : null} - ) : ( + ) : null} + + {listSection === 'preregistrations' ? ( +
+ {preRegistrationsPending ? ( +
+ +
+ ) : null} + + {!preRegistrationsPending && preRegistrations.length === 0 ? ( +
+ +

+ No hay pre-inscripciones pendientes +

+

+ Cuando alguien se inscriba a través del enlace compartido, aparecerá aquí para que + revises y apruebes su lugar. +

+
+ +
+
+ ) : null} + + {preRegistrations.length > 0 && filteredPreRegistrations.length === 0 ? ( +
+ No se encontraron pre-inscripciones que coincidan con la búsqueda. +
+ ) : null} + + {filteredPreRegistrations.length > 0 ? ( + + ) : null} +
+ ) : null} + + {listSection === 'waitlist' ? (
{waitlistPending ? (
@@ -156,7 +229,7 @@ export function MembersWaitlistSection() { {waitlistEntries.length > 0 ? : null}
- )} + ) : null}
) diff --git a/apps/web/src/features/groups/detail/PreRegistrationDetailModal.tsx b/apps/web/src/features/groups/detail/PreRegistrationDetailModal.tsx new file mode 100644 index 0000000..7118723 --- /dev/null +++ b/apps/web/src/features/groups/detail/PreRegistrationDetailModal.tsx @@ -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 ( + setSelectedPreRegistration(null)} + title="Detalle de la pre-inscripción" + maxWidth="sm" + > + {selectedPreRegistration ? ( +
+
+
+ {selectedPreRegistration.fullName.charAt(0).toUpperCase()} +
+
+

+ {selectedPreRegistration.fullName} +

+

+ Solicitado el{' '} + {new Date(selectedPreRegistration.createdAt).toLocaleDateString('es-ES', { + day: 'numeric', + month: 'long', + year: 'numeric', + })} +

+
+
+ +
+ } label="Teléfono"> +
+ {selectedPreRegistration.phone} + + + WhatsApp + +
+
+ + {selectedPreRegistration.email ? ( + } label="Email"> + + {selectedPreRegistration.email} + + + ) : null} +
+ + {!hasFreeCapacity ? ( +

+ El grupo alcanzó su cupo de miembros. Si aprobás, esta persona quedará en la lista de + espera hasta que se libere un lugar. +

+ ) : null} + +
+ + +
+
+ ) : null} +
+ ) +} diff --git a/apps/web/src/features/groups/detail/PreRegistrationsTable.tsx b/apps/web/src/features/groups/detail/PreRegistrationsTable.tsx new file mode 100644 index 0000000..073e35a --- /dev/null +++ b/apps/web/src/features/groups/detail/PreRegistrationsTable.tsx @@ -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 ( + + + + + + + + + + + {entries.map((entry) => ( + setSelectedPreRegistration(entry)} + > + + + + + + ))} + +
NombreTeléfonoSolicitado + Detalle +
+
+
+ {entry.fullName.charAt(0).toUpperCase()} +
+
+

+ {entry.fullName} +

+ {entry.email ? ( +

+ {entry.email} +

+ ) : null} +
+
+
+ + {entry.phone} + + + {new Date(entry.createdAt).toLocaleDateString('es-ES', { + day: 'numeric', + month: 'short', + })} + + +
+ ) +} diff --git a/apps/web/src/features/join/GroupInviteSummary.tsx b/apps/web/src/features/join/GroupInviteSummary.tsx index 35a9c33..cdb9440 100644 --- a/apps/web/src/features/join/GroupInviteSummary.tsx +++ b/apps/web/src/features/join/GroupInviteSummary.tsx @@ -43,6 +43,11 @@ export function GroupInviteSummary() { ) : null} + +

+ Al completar el formulario envías una solicitud de pre-inscripción. El profesor revisará tus + datos y te confirmará el lugar. +

) } \ No newline at end of file diff --git a/apps/web/src/features/join/JoinForm.tsx b/apps/web/src/features/join/JoinForm.tsx index f37c5c3..c12f3e1 100644 --- a/apps/web/src/features/join/JoinForm.tsx +++ b/apps/web/src/features/join/JoinForm.tsx @@ -104,7 +104,7 @@ export function JoinForm() { className="w-full gap-2 py-2.5 text-sm font-semibold" > {isSubmitting ? : null} - Completar Inscripción + Enviar Solicitud diff --git a/apps/web/src/features/join/JoinGroupProvider.tsx b/apps/web/src/features/join/JoinGroupProvider.tsx index 33cdb2b..4fa6d11 100644 --- a/apps/web/src/features/join/JoinGroupProvider.tsx +++ b/apps/web/src/features/join/JoinGroupProvider.tsx @@ -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(null) - const [registeredAttendee, setRegisteredAttendee] = useState(null) - const [waitlistMessage, setWaitlistMessage] = useState(null) + const [preRegistrationMessage, setPreRegistrationMessage] = useState(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, } @@ -125,4 +118,4 @@ export function useJoinGroup() { throw new Error('useJoinGroup debe usarse dentro de ') } return context -} \ No newline at end of file +} diff --git a/apps/web/src/features/join/JoinGroupView.tsx b/apps/web/src/features/join/JoinGroupView.tsx index 0ab1c6c..2a32bb3 100644 --- a/apps/web/src/features/join/JoinGroupView.tsx +++ b/apps/web/src/features/join/JoinGroupView.tsx @@ -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 (
@@ -25,10 +24,9 @@ export function JoinGroupView() { {inviteFailed || (!group && !invitePending) ? : null} - {registeredAttendee ? : null} - {waitlistMessage ? : null} + {preRegistrationMessage ? : null} - {!registeredAttendee && !waitlistMessage && group ? ( + {!preRegistrationMessage && group ? (
@@ -40,4 +38,4 @@ export function JoinGroupView() {
) -} \ No newline at end of file +} diff --git a/apps/web/src/features/join/JoinSuccessCard.tsx b/apps/web/src/features/join/JoinSuccessCard.tsx deleted file mode 100644 index ccb451a..0000000 --- a/apps/web/src/features/join/JoinSuccessCard.tsx +++ /dev/null @@ -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 ( -
-
- -
- -
- - Registro Confirmado - -

¡Inscripción Exitosa!

-

- Tus datos han sido registrados con éxito en el grupo{' '} - {group.name}. -

-
- -
-
- Profesor: - {group.teacherName} -
-
- Alumno: - {registeredAttendee.fullName} -
- {registeredAttendee.phone ? ( -
- Teléfono registrado: - {registeredAttendee.phone} -
- ) : null} -
- -

- El profesor se pondrá en contacto contigo a la brevedad por WhatsApp para darte la bienvenida y - coordinar los detalles de la clase. -

-
- ) -} \ No newline at end of file diff --git a/apps/web/src/features/join/WaitlistNoticeCard.tsx b/apps/web/src/features/join/PreRegistrationNoticeCard.tsx similarity index 61% rename from apps/web/src/features/join/WaitlistNoticeCard.tsx rename to apps/web/src/features/join/PreRegistrationNoticeCard.tsx index b84435a..686285c 100644 --- a/apps/web/src/features/join/WaitlistNoticeCard.tsx +++ b/apps/web/src/features/join/PreRegistrationNoticeCard.tsx @@ -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 (
@@ -14,16 +14,17 @@ export function WaitlistNoticeCard() {
- Lista de Espera + Pre-inscripción -

Cupo completo

-

{waitlistMessage}

+

Solicitud enviada

+

{preRegistrationMessage}

- El profesor se pondrá en contacto contigo cuando haya un lugar disponible en{' '} - {group.name}. + El profesor revisará tu solicitud para el grupo{' '} + {group.name} y se pondrá en contacto + contigo por WhatsApp para confirmarte el lugar.

) -} \ No newline at end of file +} diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index d7a979d..cacf885 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -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( + `/api/v1/groups/${groupId}/preregistrations?page=${page}&pageSize=${pageSize}`, + ) + +export const approveGroupPreRegistration = (groupId: string, entryId: string) => + apiFetch( + `/api/v1/groups/${groupId}/preregistrations/${entryId}/approve`, + { method: 'POST' }, + ) + +export const rejectGroupPreRegistration = (groupId: string, entryId: string) => + apiFetch( + `/api/v1/groups/${groupId}/preregistrations/${entryId}/reject`, + { method: 'POST' }, + ) + export const removeGroupAttendee = ( groupId: string, attendeeId: string, diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 5573f7a..a0f8125 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -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'; \ No newline at end of file diff --git a/packages/shared/src/schemas/attendees.ts b/packages/shared/src/schemas/attendees.ts index be77c15..7833e50 100644 --- a/packages/shared/src/schemas/attendees.ts +++ b/packages/shared/src/schemas/attendees.ts @@ -77,7 +77,7 @@ export const JoinGroupViaInviteSchema = z.object({ export type JoinGroupViaInvite = z.output; export const JoinGroupViaInviteResultSchema = z.object({ - status: z.enum(['registered', 'waitlisted']), + status: z.literal('pre_registered'), message: z.string(), attendee: AttendeeDtoSchema.nullable(), }); diff --git a/packages/shared/src/schemas/preregistrations.ts b/packages/shared/src/schemas/preregistrations.ts new file mode 100644 index 0000000..656aebf --- /dev/null +++ b/packages/shared/src/schemas/preregistrations.ts @@ -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; + +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; + +export const GroupPreRegistrationQuerySchema = z.object({ + page: pageSchema, + pageSize: pageSizeSchema, + status: preRegistrationStatusSchema.optional(), +}); +export type GroupPreRegistrationQuery = z.output; + +export const GroupPreRegistrationListSchema = z.object({ + data: z.array(GroupPreRegistrationDtoSchema), + pagination: paginationSchema, +}); +export type GroupPreRegistrationList = z.output; + +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 +>; -- 2.49.1 From 5ef393fa648cce3e9367abd55c1c935f8469062d Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 29 Sep 2026 15:41:13 -0300 Subject: [PATCH 2/6] feat: add SectionChips component for improved navigation between members, pre-registrations, and waitlist --- .../groups/detail/MembersWaitlistSection.tsx | 71 ++---------------- .../features/groups/detail/SectionChips.tsx | 73 +++++++++++++++++++ 2 files changed, 80 insertions(+), 64 deletions(-) create mode 100644 apps/web/src/features/groups/detail/SectionChips.tsx diff --git a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx index ac09031..c25b16c 100644 --- a/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx +++ b/apps/web/src/features/groups/detail/MembersWaitlistSection.tsx @@ -1,20 +1,17 @@ import { useNavigate } from '@tanstack/react-router' 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 { SectionChips } from './SectionChips' 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, + groupId, attendees, attendeesPending, + waitlistEntries, waitlistPending, + preRegistrations, preRegistrationsPending, listSection, setListSection, searchFilter, setSearchFilter, openInviteModal, } = useGroupDetail() const navigate = useNavigate() @@ -41,65 +38,11 @@ export function MembersWaitlistSection() { // Sin bordes: el lavado `bg-primary-soft` separa la sección del fondo.
-
-
- - - -
+
+ {showSearch ? ( -
+
+ +export function SectionChips() { + const { listSection, setListSection, attendeesTotal, preRegistrationsTotal, waitlistTotal } = + useGroupDetail() + + const counts: Record = { + members: attendeesTotal, + preregistrations: preRegistrationsTotal, + waitlist: waitlistTotal, + } + + return ( +
+ {SECTIONS.map((section) => { + const isActive = listSection === section.id + const count = counts[section.id] + const Icon = section.icon + + return ( + + ) + })} +
+ ) +} -- 2.49.1 From 9520763ec3aa7742b01de1edcec9c115e92f98e8 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 29 Sep 2026 16:29:38 -0300 Subject: [PATCH 3/6] feat: refactor group detail components for improved member and pending views --- .interface-design/system.md | 97 ++++++++++ .../groups/detail/GroupDetailProvider.tsx | 11 +- .../features/groups/detail/GroupHeader.tsx | 7 +- .../features/groups/detail/GroupInfoCard.tsx | 104 ++++++++--- .../features/groups/detail/MembersTable.tsx | 2 +- .../features/groups/detail/MembersView.tsx | 69 +++++++ .../groups/detail/MembersWaitlistSection.tsx | 169 ++---------------- .../features/groups/detail/PendingView.tsx | 125 +++++++++++++ .../groups/detail/PreRegistrationsTable.tsx | 5 +- .../features/groups/detail/SectionChips.tsx | 24 +-- .../features/groups/detail/WaitlistTable.tsx | 2 +- apps/web/src/lib/format.ts | 13 ++ 12 files changed, 432 insertions(+), 196 deletions(-) create mode 100644 .interface-design/system.md create mode 100644 apps/web/src/features/groups/detail/MembersView.tsx create mode 100644 apps/web/src/features/groups/detail/PendingView.tsx diff --git a/.interface-design/system.md b/.interface-design/system.md new file mode 100644 index 0000000..4e1fe9b --- /dev/null +++ b/.interface-design/system.md @@ -0,0 +1,97 @@ +# Gruperly — sistema de interfaz (apps/web) + +Aplicado en el rediseño de `/groups/$groupId` (sept 2026). Fuente de verdad de tokens: +`apps/web/src/index.css` (`@theme`). Ojo: `stack.md` trae tokens viejos (accent `#1e90ff`); +el accent real es **`#2544ea`**. + +## Dirección y sensación + +Herramienta diaria de un profesor/organizador que abre la pantalla para responder tres +preguntas: ¿quién está? ¿quién falta? ¿qué cobro?. Sensación: **calma operativa** — densa +pero escaneable, nada grita salvo lo que requiere decisión. Tema oscuro slate + un solo +accent azul; copy en español, verbos en infinitivo. + +## Profundidad y espaciado + +- **Estrategia de depth**: cambios de superficie + bordes de baja opacidad. Sombras solo + `shadow-xs` en tarjetas/paneles. Nada de drop shadows marcados. +- **Unidad base 4px.** Densidad: padding de componente 8–16px, separación entre bloques + `space-y-5 sm:space-y-6` (20/24px). +- **Radius**: default `rounded-xl` (0.75rem). Concéntrico: contenedor `rounded-2xl` (16px) + + padding 8px → interior `rounded-lg` (8px). Chips y pills: `rounded-full`. + +## Jerarquía tipográfica (ratio ~1.25) + +| nivel | valor | uso | +| --- | --- | --- | +| label | 11px semibold uppercase `tracking-wide` `text-foreground/70` | títulos de celda/sección | +| body | 14px (`text-sm`) `text-foreground/80` | descripciones, filas | +| value | 16px semibold `text-primary` (`text-base`) | dato principal de una celda | +| hero | 24px semibold `tracking-tight` `tabular-nums` | **solo uno por bloque** (hoy: el cupo `1/4`) | +| micro | 10–12px | pills de conteo (`text-[10px] font-bold`), captions | + +- Cuatro niveles de color de texto: `text-primary` → `text-foreground` → `/70` → `/50`. +- **Todo dato numérico lleva `tabular-nums`** (contadores, teléfonos, precios, fechas). + +## Patrón focal + +**Un punto focal por bloque y por estado.** La tarjeta de info manda con el cupo; el header +de grupo no tiene ningún `primary` (las tres acciones son `outline`) y el `primary` vive en +el empty state de la vista que lo explica. Así nunca hay dos elementos azules compitiendo. + +## Componentes (valores exactos) + +### Chip de sección — `detail/SectionChips.tsx` +- Contenedor: `flex w-full flex-wrap items-center gap-2` + `role="group"` (no tablist). +- Chip: `min-h-10 rounded-full border px-3 text-xs font-semibold gap-1.5`, + activo `border-transparent bg-accent text-on-accent shadow-xs`, + inactivo `border-border bg-surface text-foreground/80 hover:border-accent/40 hover:bg-primary-soft hover:text-primary`, + focus `ring-2 ring-accent ring-offset-2 ring-offset-primary-soft`. +- Pill de conteo: `px-1.5 py-0.5 text-[10px] font-bold leading-none tabular-nums`; + **oculto si el conteo es 0**; atención `bg-warning-soft text-warning`; + neutro `bg-primary-soft text-foreground/60`; sobre chip activo `bg-on-accent/25 text-on-accent`. +- `aria-pressed` en cada chip. Envuelve en 1–3 filas según ancho: nunca recorta. + +### Acciones de cabecera — `detail/GroupHeader.tsx` +- `variant="outline"` con icono `text-accent`; `md` (`h-10 px-4`). `primary` solo en empty states. +- Móvil: `grid grid-cols-2 gap-2.5` (tercera acción `col-span-2`); `sm+`: `flex justify-end`. +- Badges de estado: `rounded-full px-2.5 py-0.5 text-[11px]` + punto `size-1.5`. + +### Tarjeta de info — `detail/GroupInfoCard.tsx` +- Contenedor: `rounded-2xl bg-primary-soft p-4 sm:p-5` + `divide-y divide-border/70` en móvil, + `md:grid md:grid-cols-3 md:divide-x md:divide-y-0`. +- Celda: `flex items-start gap-3 py-3 first:pt-0 last:pb-0 md:py-0` + `md:pr-6` / `md:px-6` / `md:pl-6`. +- Barra de cupo: `h-1.5 max-w-[9rem] rounded-full bg-accent/15`, fill `bg-accent` + (o `bg-warning` si `total >= capacity`), `transition-[width] duration-300 ease-out`, + con `role="progressbar"` + `aria-valuetext`. + +### Sección de listados — `detail/MembersWaitlistSection.tsx` +- Externo `rounded-2xl bg-primary-soft p-2`; interno `space-y-2 p-2 sm:p-3`. +- Panel de contenido: `rounded-lg bg-surface p-1 shadow-xs sm:p-2`. +- Fila header: chips + buscador (`sm:w-72 lg:shrink-0`), apilados hasta `lg`. +- Sub-encabezado de sección apilada (`PendingView.tsx`): + `flex items-center gap-2 border-b border-border/70 px-3 pb-2 pt-3`, + título label 11px, pill a la derecha con `ml-auto`; tabla envuelta en `pt-1`. + +### Empty state +`rounded-lg bg-primary-soft/50 px-4 py-10 text-center` · icono `size-10 text-foreground/40` · +título `text-sm font-semibold text-primary` · cuerpo `max-w-sm text-sm text-foreground/80` · +acciones: **una** `primary` + el resto `outline`. + +### Tablas — `detail/*Table.tsx` +`table-fixed text-sm` · nombre `w-[48%]` · chevron `w-9` · filas `px-3 py-2.5` +con `border-b border-border/70 last:border-b-0 hover:bg-primary-soft/60` · +avatar `size-9 rounded-full bg-accent/10 text-xs font-semibold text-accent` · +columnas secundarias con `hidden sm:table-cell` (en móvil manda el teléfono). + +### Botón — `components/ui/button.tsx` +`rounded-xl font-medium h-10 px-4 text-sm` · `active:scale-[0.96] motion-reduce:active:scale-100` · +focus `ring-2 ring-accent` · variantes `primary` (`bg-accent`/`hover:bg-accent-strong`), +`outline`, `ghost`. + +## Convenciones que sostienen el sistema + +- Sin Radix/shadcn instalado: primitivos propios en `components/ui/` + `cn()` (clsx + tailwind-merge). +- Sin botón "volver" en mobile: `hidden lg:inline-flex`. +- Elementos fijos abajo: `env(safe-area-inset-bottom)` en el padding. +- Los controles nuevos deben pasar el squint test: si dos cosas brillan, sobra una. diff --git a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx index c6cae7c..0e6befe 100644 --- a/apps/web/src/features/groups/detail/GroupDetailProvider.tsx +++ b/apps/web/src/features/groups/detail/GroupDetailProvider.tsx @@ -24,7 +24,7 @@ import { } from '../../../lib/api' import { useRemoveAttendee } from './useRemoveAttendee' -export type ListSection = 'members' | 'preregistrations' | 'waitlist' +export type ListSection = 'members' | 'pending' type GroupDetailContextValue = { groupId: string @@ -83,12 +83,19 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch const toast = useToast() const [isInviteModalOpen, setIsInviteModalOpen] = useState(false) - const [listSection, setListSection] = useState('members') + const [listSection, setListSectionState] = useState('members') const [attendeeToRemove, setAttendeeToRemove] = useState(null) const [selectedWaitlistEntry, setSelectedWaitlistEntry] = useState(null) const [selectedPreRegistration, setSelectedPreRegistration] = useState(null) const [searchFilter, setSearchFilter] = useState('') + // La búsqueda pertenece a la vista que la abrió: al cambiar de pestaña se + // limpia para no heredar un filtro sin coincidencias. + const setListSection = (value: ListSection) => { + setListSectionState(value) + setSearchFilter('') + } + const groupQuery = useQuery({ queryKey: ['group', groupId], queryFn: () => getGroup(groupId), diff --git a/apps/web/src/features/groups/detail/GroupHeader.tsx b/apps/web/src/features/groups/detail/GroupHeader.tsx index 2ba2242..96a8a4a 100644 --- a/apps/web/src/features/groups/detail/GroupHeader.tsx +++ b/apps/web/src/features/groups/detail/GroupHeader.tsx @@ -71,14 +71,17 @@ export function GroupHeader() { Compartir Link + {/* Acciones de nivel secundario: con miembros en el grupo el foco es el + listado, no el botón. El `primary` de "Agregar" vive en el empty + state, que es donde la acción necesita explicarse. */}