diff --git a/.interface-design/group-detail-redesign.html b/.interface-design/group-detail-redesign.html new file mode 100644 index 0000000..96e49b5 --- /dev/null +++ b/.interface-design/group-detail-redesign.html @@ -0,0 +1,954 @@ + + + + + + Gruperly — Rediseño detalle de grupo (2 estados) + + + + + + + + + +
+
+

+ Gruperly · /groups/$groupId +

+

Rediseño del detalle de grupo

+

+ Dos pestañas (Miembros · + Pendientes), tarjeta de info con lectura + Horario → Cupo → Cobro, un solo foco primario por estado y objetivos táctiles de 44px. + Tema oscuro, tokens reales de apps/web/src/index.css. +

+
+ +
+ +
+

+ 1 · Con miembros + pre-inscripciones — pestaña “Miembros” +

+
+
+ +
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+ + +
+ + + +
+
+ + +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 3/4 +

+
+
+
+

1 lugar libre · 1 en espera

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ + +
+
+
+
+ + +
+
+ + +
+
+

+ Listado de todos los miembros incorporados al grupo. +

+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
NombreTeléfonoDetalle
+
+
A
+ Ana López +
+
+ 55 1234 5678 + + +
+
+
C
+ Carlos Mendoza +
+
+ 55 2345 6789 + + +
+
+
L
+ Lucía Hernández +
+
+ 55 3456 7890 + + +
+
+
+
+
+

+ Un solo tono activo: el chip “Miembros”. “Agregar Miembros” es + ghost — disponible, no dominante. Cupo + escaneable como 3/4 + barra. +

+
+ + +
+

+ 1 · Con miembros + pre-inscripciones — pestaña “Pendientes” +

+
+
+
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+
+ + + +
+
+ +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 3/4 +

+
+
+
+

1 lugar libre · 1 en espera

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+

+ Pre-inscripciones que esperan tu aprobación y personas en lista de espera por + un cupo libre. +

+
+ +
+ +
+
+ +

+ Pre-inscripciones +

+ 2 +
+
+ + + + + + + + + + + + + + + + + + + + +
NombreTeléfono
+
+
J
+
+

Jorge Ramírez

+

+ jorge.r@correo.mx +

+
+
+
+ 55 4567 8901 + + +
+
+
S
+
+

Sofía Torres

+

+ sofia.t@correo.mx +

+
+
+
+ 55 5678 9012 + + +
+
+
+ + +
+
+ +

+ Lista de espera +

+ 1 +
+
+ + + + + + + + + + + + + + + +
NombreTeléfonoDetalle
+
+
D
+
+

Diego Peña

+

+ Prefiere horario de 19:00 +

+
+
+
+ 55 6789 0123 + + +
+
+
+
+
+
+
+

+ “Pendientes” agrupa Pre-inscripciones (pill ámbar = requiere decisión) y Lista de + espera como secciones apiladas — sin una tercera pestaña. +

+
+ + +
+

+ 2 · Estado vacío — pestaña “Miembros” (sin miembros ni pre-inscripciones) +

+
+
+
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+ +
+ +
+
+ + +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 0/4 +

+
+
+
+

4 lugares libres

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+

+ Listado de todos los miembros incorporados al grupo. +

+
+ +
+
+ +

+ Todavía no hay miembros en este grupo +

+

+ Puedes compartir el enlace de invitación único o agregar miembros de forma + manual o masiva. +

+
+ + +
+
+
+
+
+
+

+ Exactamente un primario: “Agregar Miembros” en el + empty state. El header no repite Compartir/Agregar —solo queda Estadísticas—, así que + no compiten dos CTA idénticos. +

+
+ + +
+

+ 2 · Estado vacío — pestaña “Pendientes” +

+
+
+
+
+
+

Tai Chi Martes

+

+ Tai chi para principiantes. Trae ropa cómoda. +

+
+
+ + Activo + + + Riesgo moderado + +
+
+ +
+ +
+
+ +
+
+ +
+

Horario

+

Martes

+

18:00 - 19:30

+
+
+
+ +
+

Miembros & Cupo

+

+ 0/4 +

+
+
+
+

4 lugares libres

+
+
+
+
+ $ +
+
+

Cobro

+

$450.00

+

Vence el día 10 de cada mes

+
+
+
+ +
+
+
+
+ + +
+
+ + +
+
+

+ Pre-inscripciones que esperan tu aprobación y personas en lista de espera por + un cupo libre. +

+
+ +
+
+ +

No hay pendientes

+

+ Las pre-inscripciones que lleguen por el enlace compartido y las personas en + lista de espera aparecerán aquí para que las revises. +

+
+ +
+
+
+
+
+
+

+ Cada pestaña vacía explica qué aparecerá ahí y ofrece + una acción primaria concreta. +

+
+
+ + +
+ + + + diff --git a/.interface-design/group-detail-redesign.png b/.interface-design/group-detail-redesign.png new file mode 100644 index 0000000..8a515ba Binary files /dev/null and b/.interface-design/group-detail-redesign.png differ diff --git a/.interface-design/system.md b/.interface-design/system.md new file mode 100644 index 0000000..c84ae4a --- /dev/null +++ b/.interface-design/system.md @@ -0,0 +1,136 @@ +# 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` (Estadísticas y Compartir son `outline` y **Agregar es +`ghost`**: con miembros en el grupo deja de competir con el listado) y el `primary` vive en +el empty state de la vista que lo explica. Así nunca hay dos elementos azules compitiendo. + +**Objetivos táctiles ≥ 44px** en esta pantalla: chips (`min-h-11`), botones del header y del +empty state (`h-11`), buscador (`h-11`). Filas de tabla ~56px. + +Preview visual de los dos estados (con miembros + vacío): +`group-detail-redesign.html` / `.png` (mismo directorio). + +## 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-11 rounded-full border px-3.5 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. + +### Encabezado de pantalla — `components/layout/LargeTitle.tsx` +- Patrón iOS: título grande que al scrollear se desliza debajo de una barra de + navegación que se opaca y recibe el título en versión chica. +- Caja de la barra: `h-14` (56px) `sticky top-0 z-40` + `bg-background/80 backdrop-blur-md` + y `border-b`, con opacidad ligada al progreso. `h-14` tiene que coincidir con + `BAR_HEIGHT` de `hooks/useLargeTitleCollapse.ts`. +- Título grande: `text-[2.125rem] leading-[1.1] tracking-tight`, `sm:text-[2.5rem]`, + con `text-balance` para nombres largos. +- Título de la barra: `text-base font-semibold`, `truncate`, `aria-hidden` (es + duplicado visual del `h1`). +- El progreso sale de la posición del título en cada frame (`rAF` agrupa los + eventos de scroll), no de una transición: por eso se siente pegado al dedo. El + estado vive dentro de `LargeTitle` para que `children` no se re-renderice en + cada frame. +- La barra se monta en una caja que el layout pone arriba de `
` + (`ImmersiveBarHost`): un `sticky` está limitado a la caja de su padre, y el + padre natural (el bloque del feature) es corto. +- Sólo en tres rutas: `isImmersiveRoute` (`lib/immersive-routes.ts`): ficha de + grupo, sus estadísticas y la asistencia. Ahí no se renderiza el header global + y el sidebar pasa a `top-0 h-dvh`. +- El link "volver" vive en la barra como `leading` y sigue `hidden lg:inline-flex`. +- En las pantallas de un grupo (ficha y estadísticas) el título grande es **el + nombre del grupo**, no el de la sección: la barra colapsada tiene que decir + sobre qué se está mirando. "Estadísticas" va como subtítulo (label 11px + uppercase + body), no como título. + +### Acciones de cabecera — `detail/GroupHeader.tsx` +- Título, badges y descripción los dibuja `LargeTitle`; las acciones quedan + debajo, en el flujo normal. +- Estadísticas y Compartir: `variant="outline"` con icono `text-accent`; **Agregar Miembros: + `variant="ghost"`** (disponible, no dominante). Todas `h-11` (44px). +- **Grupo vacío** (0 miembros + 0 pendientes): el header muestra **solo Estadísticas** — + Compartir y Agregar los ofrecen los empty states, que ya llevan su primario explicado. +- 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`, + en su propia fila bajo el título grande (`mt-3`) y se van al colapsar la barra. + +### 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`, todas `h-11`. + +### 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/AGENTS.md b/AGENTS.md index 363e497..2cca495 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). @@ -54,6 +54,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con ``). - **Vistas en `apps/web/src/features//`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use()` y las forms locales mantienen su propio estado. - Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista. +- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `
`, `
` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `
`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar ``; nada más. En las tres pantallas el `

` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos. - **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos. - Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`. - **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `
` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa. 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/package.json b/apps/web/package.json index f023180..0ef034c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,7 +8,8 @@ "build": "vite build", "preview": "vite preview", "icons": "bun run scripts/generate-icons.ts", - "typecheck": "tsc --noEmit" + "typecheck": "tsc --noEmit", + "test": "bun test" }, "dependencies": { "@better-auth/passkey": "^1.7.2", diff --git a/apps/web/src/components/layout/LargeTitle.tsx b/apps/web/src/components/layout/LargeTitle.tsx new file mode 100644 index 0000000..1ffceba --- /dev/null +++ b/apps/web/src/components/layout/LargeTitle.tsx @@ -0,0 +1,82 @@ +import type { ReactNode } from 'react' +import { createPortal } from 'react-dom' +import { useImmersiveBarHost } from '../../context/ImmersiveBarProvider' +import { useLargeTitleCollapse } from '../../hooks/useLargeTitleCollapse' + +type LargeTitleProps = { + /** Texto del título. Es el mismo en el grande y en el de la barra: el `h1` + * real es el grande, el de la barra es un duplicado visual. */ + title: string + /** Acción a la izquierda de la barra. En desktop es el link "volver" que + * antes vivía en el cuerpo de la pantalla; en mobile se oculta. */ + leading?: ReactNode + /** Contexto que no puede desaparecer al scrollear (ej. el contador de + * presentes). Viaja a la barra y se funde con el título. */ + barTrailing?: ReactNode + /** Metadatos bajo el título grande: badges, descripción. Se van al colapsar. */ + children?: ReactNode +} + +/** + * Encabezado de pantalla con Large Title (patrón de iOS): el título arranca + * grande y al scrollear se desliza debajo de la barra, que se opaca y recibe + * el título en versión chica. + * + * El título grande es un bloque normal en el flujo; la barra vive en una caja + * sticky que el layout monta arriba de `
` (ver `ImmersiveBarHost`), así + * el contenido se desliza por debajo sin márgenes negativos ni `fixed` que + * haya que compensar en desktop. + * + * El estado del scroll vive acá adentro a propósito: `children` llega como prop + * ya construido, así React reutiliza los elementos y el subtree de abajo no se + * re-renderiza en cada frame de scroll. + */ +export function LargeTitle({ title, leading, barTrailing, children }: LargeTitleProps) { + const { titleRef, progress } = useLargeTitleCollapse() + const barHost = useImmersiveBarHost() + + return ( + <> + {barHost + ? createPortal( +
+ {/* El fondo va en una capa propia: se opaca con el scroll mientras + el título entra, y `leading` (el link "volver") no puede + fundirse con él porque existe siempre. */} +
+ {leading} + + {barTrailing ? ( + + ) : null} +
, + barHost, + ) + : null} + +

+ {title} +

+ + {children} + + ) +} diff --git a/apps/web/src/components/layout/RootLayout.tsx b/apps/web/src/components/layout/RootLayout.tsx index 7d08b52..6f0432e 100644 --- a/apps/web/src/components/layout/RootLayout.tsx +++ b/apps/web/src/components/layout/RootLayout.tsx @@ -1,21 +1,39 @@ +import { useLocation } from '@tanstack/react-router' import type { ReactNode } from 'react' +import { ImmersiveBarHost, ImmersiveBarProvider } from '../../context/ImmersiveBarProvider' +import { isImmersiveRoute } from '../../lib/immersive-routes' +import { cn } from '../../lib/utils' import { Header } from './Header' import { Sidebar } from './Sidebar' import { BottomNav } from './BottomNav' export function RootLayout({ children }: { children: ReactNode }) { + const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) }) + return (
-
+ {/* En las rutas immersive la pantalla trae su propia barra (LargeTitle), + con el logo y el nombre del grupo: el header global con logo + tema + + avatar sería una segunda barra compitiendo por los mismos píxeles. */} + {immersive ? null :
}
- + - {/* pb-24 deja lugar para la BottomNav; en iOS standalone hay que sumar - el inset del home indicator o el contenido queda debajo. */} -
- {children} -
+ + {/* pt-0 en immersive: el padding superior lo aporta la caja de la + barra, y si no el título grande arrancaría 16px más abajo de la + base de la barra y el colapso se mediría corrido. */} +
+ {immersive ? : null} + {children} +
+
diff --git a/apps/web/src/components/layout/Sidebar.tsx b/apps/web/src/components/layout/Sidebar.tsx index e6e3f2e..f8c971d 100644 --- a/apps/web/src/components/layout/Sidebar.tsx +++ b/apps/web/src/components/layout/Sidebar.tsx @@ -3,11 +3,19 @@ import { cn } from '../../lib/utils' import { Logo } from '../brand' import { isNavItemActive, NAV_ITEMS } from './nav-items' -export function Sidebar() { +export function Sidebar({ immersive = false }: { immersive?: boolean }) { const location = useLocation() return ( -