31 Commits

Author SHA1 Message Date
bd7712b28e Merge pull request 'development' (#14) from development into main
Reviewed-on: #14
2026-11-07 13:21:41 +00:00
Jose Selesan
2d80af082f feat(web): redesign onboarding and home after design critique
Onboarding:
- Keep the current step in ?step= so the device back gesture moves one
  step back; effectiveStep guards skipping the plan and re-opening the
  group form after the group exists. Show Back on mobile.
- Format prices with the chosen country's currency (form prefix and
  confirmation).
- Welcome describes the real flow and previews the WhatsApp payment
  reminder; the last step shares the group's invite link instead of
  listing settings chores.
- Accessibility: named stepper steps with aria-current, focus moves to
  the new step heading, alerts on errors, reduced-motion and
  direction-aware step animation, 48px primary actions.
- Group form split into "classes" and "billing", due day hidden for
  per-class billing; Stripe skips the empty Pro confirmation; Free
  features read "in Pro" instead of struck through.

Home:
- Payments section follows the plan: Free gets a locked preview with
  an upgrade link and is never asked to link Mercado Pago.
- Secondary text meets 4.5:1 contrast; accent-fg for links in dark.
- Class times use a 24h clock in Spanish and Portuguese.
- Drop the summary tiles; one hero for the current or next class, the
  rest of the day as compact rows; two columns on desktop.
- "Para atender" reads the shared ['attention'] query, so resolved
  alerts match "Requiere atención", with WhatsApp shortcuts and a link
  to the full list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 09:58:08 -03:00
Jose Selesan
70ef049f34 docs: require English commit messages in AGENTS.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:27:16 -03:00
Jose Selesan
f0bb02ab73 chore: ignorar .DS_Store y los intermedios de archify
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:24:32 -03:00
Jose Selesan
925f1a256d docs: AGENTS.md con el estado final del multi idioma
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:07:42 -03:00
Jose Selesan
70702ba852 feat(i18n): traducir el backoffice
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:07:03 -03:00
Jose Selesan
4d50b46399 feat(i18n): traducir la app de alumnos (con selector de idioma en Perfil)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:05:21 -03:00
Jose Selesan
486fbaf2ca feat(i18n): traducir el acceso de alumnos (links, passkey, recuperación)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:02:56 -03:00
Jose Selesan
b615c17a16 feat(i18n): traducir inscripción por link y aviso de ausencia público
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:02:02 -03:00
Jose Selesan
243530fab2 feat(i18n): traducir perfil y seguridad
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:00:14 -03:00
Jose Selesan
dfb6951d7c feat(i18n): traducir el onboarding (nombres de país desde Intl)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:59:41 -03:00
Jose Selesan
e2d9ddf569 feat(i18n): traducir WhatsApp
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:57:44 -03:00
Jose Selesan
700b9fb91d feat(i18n): traducir Mercado Pago
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:56:08 -03:00
Jose Selesan
e3dca305a4 feat(i18n): traducir el plan (billing)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:55:20 -03:00
Jose Selesan
7db9414f12 feat(i18n): traducir Cobros
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:53:40 -03:00
Jose Selesan
13723d5bb9 feat(i18n): traducir la toma de asistencia
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:30:52 -03:00
Jose Selesan
8a5768e0c0 feat(i18n): traducir la ficha del alumno
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:30:11 -03:00
Jose Selesan
ecdbbbbca6 feat(i18n): traducir Requiere atención y redactar las alertas en cada idioma
Las alertas de shared suman razon + valores para que la web las redacte;
etiqueta/detalle se mantienen en español para el backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:27:17 -03:00
Jose Selesan
96661fb807 feat(i18n): traducir Grupos (lista, ficha, alta de miembros y estadísticas)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:25:21 -03:00
Jose Selesan
09647672b8 feat(i18n): traducir Inicio
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:16:16 -03:00
Jose Selesan
cb872eb8bc feat: soporte multi idioma en la web (infraestructura)
i18next + react-i18next con es-AR (fuente), es-419, pt-BR y en; el idioma
sale del dispositivo (fallback a inglés) y se puede cambiar en Ajustes.
La elección se guarda en localStorage y, para el profe, en users.locale.
Las validaciones de shared pasan a claves y los errores de la API se
traducen por code (con params para límites de plan y cupo).
Migrados: layout, Ajustes, auth, PWA y lib/format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:14:59 -03:00
Jose Selesan
ff885bddfc docs: diagramas de arquitectura y de personas/membresías
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:33:59 -03:00
Jose Selesan
d21e1c3730 feat: un miembro puede pertenecer a más de un grupo
- Nuevo modelo `Person` (`people`): contacto y notas por profe, con
  teléfono único (índice parcial `people_owner_phone_key`). `Attendee`
  pasa a ser la membresía (`group_id` + `person_id`, único por grupo).
- La cuenta de la app de alumnos se vincula a la persona
  (`student_account_people`): una sola cuenta ve todos sus grupos.
- Migración unifica attendees del mismo profe y teléfono, y fusiona sus
  cuentas de alumno (conserva la usada más recientemente).
- `POST /groups/:gid/attendees/:aid/add-to-group` y
  `GET /people/lookup` para detectar personas existentes al cargar;
  el alta responde `409 person_exists` y acepta `personId`. Bulk, lista
  de espera y preinscripciones vinculan solas.
- El límite del plan cuenta personas con al menos un grupo activo.
- Web: "Agregar a otro grupo", sección "También está en" en la ficha y
  aviso "Ya tenés a esta persona" en el alta individual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 09:46:37 -03:00
Jose Selesan
f1829fb5a9 feat: cambiar a un miembro de grupo
- `POST /groups/:gid/attendees/:aid/move` mueve al mismo attendee a otro
  grupo del profesor: conserva historial, cuotas (siguen del grupo anterior)
  y acceso a la app de alumnos. Cancela las faltas avisadas y libera lo
  reservado en clases futuras del grupo anterior.
- Cupo y teléfono duplicado se validan con `checkCanJoinGroup`, compartido
  con el paso desde la lista de espera.
- Ficha del miembro: "Cambiar de grupo" abre un diálogo con el selector de
  grupo destino y navega a la ficha en el grupo nuevo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 16:21:32 -03:00
Jose Selesan
fc12ec3ae0 feat: pasar de la lista de espera a otro grupo del profesor
- `POST /groups/:gid/waitlist/:entryId/promote` acepta `targetGroupId`
  opcional (por defecto, el grupo en el que se anotó). El destino tiene que
  ser del mismo profesor; cupo y teléfono duplicado se validan ahí.
- Detalle de la lista de espera: selector "Asignar a" con los grupos llenos
  deshabilitados.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:39:55 -03:00
Jose Selesan
d397e9663c feat: filtro de grupo en cobros con cuotas pendientes por grupo
- El listado de grupos devuelve `unpaidPaymentsCount` (PENDING y OVERDUE).
- Cobros: nuevo selector de grupo (GroupFilter) junto a los filtros de estado;
  con un grupo filtrado no se repite su nombre en cada card.
- Sheet: entra deslizando desde abajo en mobile (salvo reduced motion).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:59:33 -03:00
Jose Selesan
b6f22ae67d feat: add payment report notes 2026-10-28 16:45:55 -03:00
b22b6da2e1 Merge pull request 'feat: add payment options on student portal' (#13) from feat/student-payment-management into development
Reviewed-on: #13
2026-10-28 19:35:13 +00:00
Jose Selesan
9e4d34b5d8 feat: add payment options on student portal 2026-10-28 16:34:28 -03:00
Jose Selesan
bc5f676cea refactor(web): rutas de la app de alumnos en inglés
/acceso → /access, /alumno/* → /student/* (welcome, classes, payments,
profile, notify-absence, report-payment). El link del mail de confirmación
pasa a /access/email/:token. AGENTS.md documenta que los paths van en inglés.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:50:55 -03:00
f6a7b7344e Merge pull request 'feat/improve-ui' (#11) from feat/improve-ui into development
Reviewed-on: #11
2026-10-28 18:40:21 +00:00
461 changed files with 45917 additions and 2896 deletions

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,448 @@
{
"schema_version": 1,
"diagram_type": "architecture",
"meta": {
"title": "Arquitectura de Gruperly",
"locale": "es",
"output": ".archify/architecture-gruperly-20261103-121500/arquitectura-gruperly.html",
"quality_profile": "showcase",
"repository": {
"url": "https://git.2pidev.com/jselesan/gruperly.git",
"link_mode": "local-only",
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
},
"views": [
{
"id": "request",
"label": "Pedido del profe",
"focus": [
"teacher",
"web",
"nginx",
"guards",
"api",
"db"
],
"note": "Mismo dominio: nginx sirve el bundle y hace proxy de /api al contenedor api."
},
{
"id": "students",
"label": "App de alumnos",
"focus": [
"student",
"web",
"guards",
"storage"
],
"note": "Sin Better Auth: cookie y middleware propios; comprobantes en S3 privado."
},
{
"id": "integrations",
"label": "Integraciones",
"focus": [
"api",
"mp",
"stripe",
"whatsapp",
"smtp",
"storage"
],
"note": "Cada proveedor detrás de un puerto; sin credenciales responde 503 y el resto sigue andando."
}
]
},
"components": [
{
"id": "teacher",
"type": "external",
"label": "Profesor",
"sublabel": "navegador / PWA",
"icon": "person",
"pos": [
40,
60
],
"size": [
120,
60
],
"sources": [
{
"path": "apps/web/src/routes/_authenticated.tsx",
"line": 1
}
]
},
{
"id": "web",
"type": "frontend",
"label": "Web PWA",
"sublabel": "React 19 · Vite",
"pos": [
230,
56
],
"size": [
140,
68
],
"sources": [
{
"path": "apps/web/vite.config.ts",
"line": 12,
"label": "VitePWA"
}
]
},
{
"id": "student",
"type": "external",
"label": "Alumno / tutor",
"sublabel": "/i/:token · /student",
"icon": "person",
"pos": [
230,
240
],
"size": [
140,
60
],
"sources": [
{
"path": "apps/web/src/routes/i.$token.tsx",
"line": 1
},
{
"path": "apps/web/src/routes/_student.tsx",
"line": 1
}
]
},
{
"id": "nginx",
"type": "cloud",
"label": "nginx",
"sublabel": "bundle + proxy /api",
"pos": [
450,
60
],
"size": [
140,
60
],
"sources": [
{
"path": "apps/web/nginx.conf",
"line": 14,
"end_line": 26
},
{
"path": "docker-compose.yml",
"line": 1,
"end_line": 8
}
]
},
{
"id": "guards",
"type": "security",
"label": "Guards de sesión",
"sublabel": "Better Auth · alumno",
"pos": [
680,
56
],
"size": [
150,
68
],
"sources": [
{
"path": "apps/backend/src/http/session-auth.ts",
"line": 23,
"end_line": 48
},
{
"path": "apps/backend/src/modules/student-portal/middleware.ts",
"line": 50
}
]
},
{
"id": "api",
"type": "backend",
"label": "API Hono + jobs",
"sublabel": "Bun.serve :4000 · cron",
"pos": [
880,
56
],
"size": [
150,
68
],
"sources": [
{
"path": "apps/backend/src/server.ts",
"line": 14,
"end_line": 23
},
{
"path": "apps/backend/src/app.ts",
"line": 44,
"end_line": 73
}
]
},
{
"id": "db",
"type": "database",
"label": "PostgreSQL",
"sublabel": "Prisma 7 · adapter-pg",
"pos": [
1090,
60
],
"size": [
140,
60
],
"sources": [
{
"path": "apps/backend/src/lib/prisma.ts",
"line": 14,
"end_line": 18
}
]
},
{
"id": "mp",
"type": "external",
"label": "Mercado Pago",
"sublabel": "OAuth · Checkout Pro",
"pos": [
610,
320
],
"size": [
130,
60
],
"sources": [
{
"path": "apps/backend/src/modules/mp/lib/mp-oauth.ts",
"line": 3,
"end_line": 4
},
{
"path": "apps/backend/src/modules/mp/lib/mp-http.ts",
"line": 4
}
]
},
{
"id": "stripe",
"type": "external",
"label": "Stripe",
"sublabel": "Pro fuera de AR",
"pos": [
760,
320
],
"size": [
110,
60
],
"sources": [
{
"path": "apps/backend/src/modules/billing/providers/index.ts",
"line": 24,
"end_line": 31
}
]
},
{
"id": "whatsapp",
"type": "external",
"label": "WhatsApp",
"sublabel": "OpenWA / Kapso",
"pos": [
890,
320
],
"size": [
130,
60
],
"sources": [
{
"path": "apps/backend/src/modules/whatsapp/providers/index.ts",
"line": 26,
"end_line": 40
}
]
},
{
"id": "smtp",
"type": "external",
"label": "SMTP",
"sublabel": "mails",
"pos": [
1040,
320
],
"size": [
100,
60
],
"sources": [
{
"path": "apps/backend/src/lib/email.ts",
"line": 181,
"end_line": 187
}
]
},
{
"id": "storage",
"type": "cloud",
"label": "S3 (RustFS)",
"sublabel": "comprobantes",
"pos": [
1160,
320
],
"size": [
130,
60
],
"sources": [
{
"path": "apps/backend/src/lib/storage.ts",
"line": 38,
"end_line": 54
}
]
}
],
"boundaries": [
{
"kind": "region",
"label": "Dokploy",
"wraps": [
"nginx",
"guards",
"api",
"db"
]
},
{
"kind": "security-group",
"label": "contenedor api",
"wraps": [
"guards",
"api"
]
}
],
"connections": [
{
"id": "teacher-web",
"from": "teacher",
"to": "web",
"label": "HTTPS",
"variant": "emphasis"
},
{
"id": "student-web",
"from": "student",
"to": "web",
"label": "link de WhatsApp"
},
{
"id": "web-nginx",
"from": "web",
"to": "nginx",
"label": "/api/v1",
"variant": "emphasis"
},
{
"id": "nginx-guards",
"from": "nginx",
"to": "guards",
"label": "proxy_pass",
"variant": "emphasis"
},
{
"id": "guards-api",
"from": "guards",
"to": "api",
"variant": "security"
},
{
"id": "api-db",
"from": "api",
"to": "db",
"label": "SQL"
},
{
"id": "api-mp",
"from": "api",
"to": "mp",
"label": "cobros"
},
{
"id": "api-stripe",
"from": "api",
"to": "stripe",
"label": "Pro"
},
{
"id": "api-whatsapp",
"from": "api",
"to": "whatsapp",
"label": "mensajes"
},
{
"id": "api-smtp",
"from": "api",
"to": "smtp",
"label": "mails"
},
{
"id": "api-storage",
"from": "api",
"to": "storage",
"label": "URLs firmadas"
}
],
"cards": [
{
"dot": "cyan",
"title": "Entrada",
"items": [
"Un solo dominio público en el contenedor web: nginx sirve la PWA y hace proxy de /api a api:4000, así la cookie de sesión es first-party.",
"Los alumnos entran por un link de invitación de un solo uso; no tienen contraseña."
]
},
{
"dot": "rose",
"title": "Seguridad",
"items": [
"sessionAuthMiddleware exige sesión de Better Auth salvo la whitelist pública (isPublicApiRequest).",
"/student-portal usa cookie y middleware propios (studentSession); una sesión de alumno no llega a rutas del profe.",
"Los webhooks de MP, Stripe y WhatsApp son públicos y se autentican por firma."
]
},
{
"dot": "emerald",
"title": "Jobs en el mismo proceso",
"items": [
"server.ts arranca los crons de MP, pagos, WhatsApp, billing y app de alumnos junto a Bun.serve.",
"La conciliación de pagos es por polling a Mercado Pago, sin webhook."
]
}
]
}

View File

@@ -0,0 +1,515 @@
{
"schema_version": 1,
"diagram_type": "erd",
"meta": {
"title": "Personas y membresías",
"locale": "es",
"output": ".archify/erd-personas-membresias-20261103-120000/personas-membresias.html",
"quality_profile": "standard",
"repository": {
"url": "https://git.2pidev.com/jselesan/gruperly.git",
"link_mode": "local-only",
"revision": "d21e1c37302d8d3f2ff8b0af05f4df21284bffe3"
},
"views": [
{
"id": "membership",
"label": "Persona y membresía",
"focus": [
"people",
"attendees",
"groups"
],
"note": "Una persona del profe, una fila de attendees por cada grupo en el que está."
},
{
"id": "owner",
"label": "Todo cuelga del profe",
"focus": [
"users",
"groups",
"people",
"student_accounts"
],
"note": "Grupos, personas y cuentas de alumno tienen created_by_id al profe."
},
{
"id": "student_app",
"label": "Una cuenta por persona",
"focus": [
"student_accounts",
"student_account_people",
"people"
],
"note": "La cuenta se vincula a la persona, así ve todos sus grupos."
}
]
},
"layout": {
"mode": "grid",
"gapX": 72,
"gapY": 40
},
"entities": [
{
"id": "groups",
"label": "groups",
"tag": "grupos",
"row": 0,
"col": 0,
"width": 256,
"sources": [
{
"path": "apps/backend/prisma/models/domain.prisma",
"line": 3,
"end_line": 32
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "name",
"type": "text"
},
{
"name": "description",
"type": "text?"
},
{
"name": "days",
"type": "WeekDay[]"
},
{
"name": "time",
"type": "text?"
},
{
"name": "capacity",
"type": "int?"
},
{
"name": "price",
"type": "numeric(10,2)?"
},
{
"name": "billing_type",
"type": "BillingType?"
},
{
"name": "due_day",
"type": "int?"
},
{
"name": "auto_payment_reminders",
"type": "boolean"
},
{
"name": "auto_reengagement",
"type": "boolean"
},
{
"name": "invite_token",
"type": "text?",
"key": "uk"
},
{
"name": "created_by_id",
"type": "text",
"key": "fk",
"references": "users.id"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "attendees",
"label": "attendees",
"sublabel": "membresía",
"tag": "membresías",
"row": 0,
"col": 1,
"width": 250,
"sources": [
{
"path": "apps/backend/prisma/models/domain.prisma",
"line": 100,
"end_line": 125
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "group_id",
"type": "text",
"key": [
"fk",
"uk"
],
"references": "groups.id"
},
{
"name": "person_id",
"type": "text",
"key": [
"fk",
"uk"
],
"references": "people.id"
},
{
"name": "notify_token",
"type": "text?",
"key": "uk"
},
{
"name": "status",
"type": "AttendeeStatus"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "people",
"label": "people",
"sublabel": "persona del profe",
"tag": "personas",
"row": 0,
"col": 2,
"width": 250,
"sources": [
{
"path": "apps/backend/prisma/models/domain.prisma",
"line": 75,
"end_line": 98
},
{
"path": "apps/backend/prisma/migrations/20261102180000_add_people/migration.sql",
"line": 155,
"label": "índice parcial"
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "created_by_id",
"type": "text",
"key": [
"fk",
"uk"
],
"references": "users.id"
},
{
"name": "full_name",
"type": "text"
},
{
"name": "email",
"type": "text?"
},
{
"name": "phone",
"type": "text?",
"key": "uk"
},
{
"name": "guardian_name",
"type": "text?"
},
{
"name": "guardian_phone",
"type": "text?"
},
{
"name": "notes",
"type": "text?"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "users",
"label": "users",
"sublabel": "profesor",
"tag": "profesor",
"row": 1,
"col": 2,
"width": 250,
"sources": [
{
"path": "apps/backend/prisma/models/auth.prisma",
"line": 3,
"end_line": 34
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "name",
"type": "text"
},
{
"name": "email",
"type": "text",
"key": "uk"
},
{
"name": "email_verified",
"type": "boolean"
},
{
"name": "image",
"type": "text?"
},
{
"name": "onboarding_completed",
"type": "boolean"
},
{
"name": "country_code",
"type": "text?"
},
{
"name": "plan_selected_at",
"type": "timestamp?"
},
{
"name": "transfer_alias",
"type": "text?"
},
{
"name": "transfer_holder",
"type": "text?"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
},
{
"id": "student_account_people",
"label": "student_account_people",
"tag": "app de alumnos",
"row": 0,
"col": 3,
"width": 300,
"sources": [
{
"path": "apps/backend/prisma/models/student-access.prisma",
"line": 40,
"end_line": 54
}
],
"attributes": [
{
"name": "account_id",
"type": "text",
"key": [
"pk",
"fk"
],
"references": "student_accounts.id"
},
{
"name": "person_id",
"type": "text",
"key": [
"pk",
"fk"
],
"references": "people.id"
},
{
"name": "created_at",
"type": "timestamp"
}
]
},
{
"id": "student_accounts",
"label": "student_accounts",
"tag": "app de alumnos",
"row": 1,
"col": 3,
"width": 300,
"sources": [
{
"path": "apps/backend/prisma/models/student-access.prisma",
"line": 10,
"end_line": 38
}
],
"attributes": [
{
"name": "id",
"type": "text",
"key": "pk"
},
{
"name": "name",
"type": "text"
},
{
"name": "recovery_email",
"type": "text?"
},
{
"name": "recovery_email_verified_at",
"type": "timestamp?"
},
{
"name": "pending_recovery_email",
"type": "text?"
},
{
"name": "welcomed_at",
"type": "timestamp?"
},
{
"name": "created_by_id",
"type": "text",
"key": "fk",
"references": "users.id"
},
{
"name": "created_at",
"type": "timestamp"
},
{
"name": "updated_at",
"type": "timestamp"
}
]
}
],
"relationships": [
{
"id": "attendee_group",
"from": "attendees",
"to": "groups",
"label": "en el grupo",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "attendee_person",
"from": "attendees",
"to": "people",
"label": "membresía de",
"fromCardinality": "many",
"toCardinality": "one"
},
{
"id": "person_owner",
"from": "people",
"to": "users",
"label": "del profe",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "group_owner",
"from": "groups",
"to": "users",
"label": "dueño",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "link_person",
"from": "student_account_people",
"to": "people",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
},
{
"id": "link_account",
"from": "student_account_people",
"to": "student_accounts",
"fromCardinality": "many",
"toCardinality": "one"
},
{
"id": "account_owner",
"from": "student_accounts",
"to": "users",
"label": "creada por",
"fromCardinality": "many",
"fromOptional": true,
"toCardinality": "one"
}
],
"cards": [
{
"dot": "cyan",
"title": "Unicidad",
"items": [
"attendees: @@unique(group_id, person_id), una persona está una sola vez en cada grupo.",
"people_owner_phone_key: (created_by_id, phone) WHERE phone IS NOT NULL, índice parcial escrito a mano (Prisma no lo modela; el choque llega como P2002)."
]
},
{
"dot": "amber",
"title": "Qué es de quién",
"items": [
"people: contacto y notas; editarlos cambia en todos los grupos.",
"attendees: status y notify_token por grupo; asistencia, cuotas, alertas y mensajes cuelgan de esta fila (no dibujados).",
"El límite del plan cuenta personas con al menos una membresía ACTIVE."
]
},
{
"dot": "emerald",
"title": "Borrados",
"items": [
"Todas las FK son ON DELETE CASCADE.",
"Quitar la última membresía borra también la persona, y con ella el vínculo a la cuenta de alumno."
]
}
]
}

File diff suppressed because one or more lines are too long

11
.gitignore vendored
View File

@@ -149,3 +149,14 @@ apps/backend/generated/
# env # env
apps/backend/.env apps/backend/.env
# macOS
.DS_Store
# archify: solo se versionan el HTML final y el candidate.json; lo intermedio no
.archify/**/*.browser-check.json
.archify/**/*.delivery.json
.archify/**/*.finalize.json
.archify/**/*.finalize-summary.json
.archify/**/candidate.before-review.json
.archify/**/review-*/

View File

@@ -61,26 +61,46 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`). 3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback. 4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`. 5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. 6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. El paso vive en `?step=` (el back del dispositivo retrocede un paso) y lo que pide la URL pasa por `effectiveStep`: sin plan no se pasa de Plan y con el grupo ya creado no se vuelve al formulario. Los callbacks (`?mp=`, `?wa=`, `?sub=`) navegan con `replace` al paso que corresponde.
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema. - **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación. - **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari). - **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
- **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/acceso`, `/alumno/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto: - **App de alumnos (`modules/student-portal`, `modules/student-access`, web `/i/$token`, `/access`, `/student/*`)**: acceso sin contraseña y sin datos obligatorios nuevos. Ojo con esto:
1. **No pasa por Better Auth**: tablas propias (`student_*`), cookie propia (`gruperly_student`, `__Host-` con HTTPS, 90 días deslizante, se reescribe como mucho cada 1 h) y middleware propio (`studentSession`). Todo `/api/v1/student-portal` está en `isPublicApiRequest` del profe; cada ruta privada declara `studentSession`. Así una sesión de alumno no llega a endpoints del profe y al revés. Nunca montes rutas del profe bajo `/student-portal`. 1. **No pasa por Better Auth**: tablas propias (`student_*`), cookie propia (`gruperly_student`, `__Host-` con HTTPS, 90 días deslizante, se reescribe como mucho cada 1 h) y middleware propio (`studentSession`). Todo `/api/v1/student-portal` está en `isPublicApiRequest` del profe; cada ruta privada declara `studentSession`. Así una sesión de alumno no llega a endpoints del profe y al revés. Nunca montes rutas del profe bajo `/student-portal`.
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410. 2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`. 3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`. 4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
5. Autorización: todo pasa por `findLinkedAttendee` (attendee vinculado a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. Vincular tutores a varios hijos (N:N en `student_account_attendees`) es solo del lado profe y **todavía no tiene UI**. 5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). Vincular tutores a varios hijos (N:N) es solo del lado profe y **todavía no tiene UI**.
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo. 6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires). 7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado. 8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.
9. Comprobantes: tipo real por magic bytes (`lib/file-type.ts`: JPG, PNG, WEBP, HEIC, PDF; 10 MB), storage S3 privado detrás de `FileStorage` (`lib/storage.ts`, `Bun.S3Client`, path-style para RustFS), URLs firmadas de 5 min. En los tests se inyecta `storage` por deps. Retención: `RECEIPT_RETENTION_DAYS` (job diario `startStudentAccessJobs`). 9. Comprobantes: tipo real por magic bytes (`lib/file-type.ts`: JPG, PNG, WEBP, HEIC, PDF; 10 MB), storage S3 privado detrás de `FileStorage` (`lib/storage.ts`, `Bun.S3Client`, path-style para RustFS), URLs firmadas de 5 min. En los tests se inyecta `storage` por deps. Retención: `RECEIPT_RETENTION_DAYS` (job diario `startStudentAccessJobs`).
10. Tests: los de `test/db/` van contra Postgres real (concurrencia del link, IDOR, revisión) y solo corren con `bun --filter @gruperly/backend test:db`; en `bun test` aparecen como `skip`. 10. Tests: los de `test/db/` van contra Postgres real (concurrencia del link, IDOR, revisión) y solo corren con `bun --filter @gruperly/backend test:db`; en `bun test` aparecen como `skip`.
- **Personas y membresías (`Person` / `Attendee`)**: una persona puede estar en varios grupos del mismo profe. Ojo con esto:
1. `Person` (`people`, del profe vía `created_by_id`) tiene los datos de contacto y las notas; `Attendee` es la **membresía** (`group_id` + `person_id` + `status` + `notify_token`), con `@@unique([groupId, personId])`. Asistencia, cuotas, alertas y mensajes siguen siendo por attendee (por grupo). (`Member` ya existe: es la organización de Better Auth.)
2. El teléfono es único por profe con un índice **parcial** a mano (`people_owner_phone_key`, `WHERE phone IS NOT NULL`): Prisma no lo modela y un choque llega como `P2002` (`isUniqueViolation` en `modules/people/lib/people.ts`). Los teléfonos se guardan normalizados (`normalizePhone`, también al editar); `phoneVariants` cubre filas viejas.
3. Las altas resuelven a la persona por teléfono: el alta individual sin `personId` con un teléfono existente responde `409 person_exists` (la web lo detecta antes con `GET /people/lookup?groupId=&phone=` y manda `personId`); bulk, lista de espera y preinscripciones vinculan solas (`findOrCreatePerson`). Ya estar en el grupo es `attendee_already_registered`; una membresía `DROPPED` se reactiva.
4. `POST /groups/:gid/attendees/:aid/add-to-group` ("Agregar a otro grupo") crea otra membresía de la misma persona; `move` sigue cambiando el `groupId` de la misma membresía. Ambas validan con `checkCanJoinGroup(db, group, personId)`.
5. Editar contacto/notas escribe en la persona (cambia en todos sus grupos; choque de teléfono → `409 person_phone_taken`). Quitar la última membresía borra también a la persona.
6. El límite del plan cuenta **personas** con al menos una membresía `ACTIVE`; `canAddAttendees(owner, n)` recibe las personas nuevas (`countsAsNewStudent`).
7. Los DTOs de attendee siguen planos (`toAttendeeDto` aplana `person` y suma `personId`); para selects sueltos usá `attendeeWithPerson` / `flattenPerson` de `attendees/lib/helpers.ts`. El detalle trae `otherGroups`.
- **Multi idioma (`apps/web/src/i18n/`)**: i18next + react-i18next. Idiomas: `es-AR` (rioplatense, voseo; AR y UY), `es-419` (tuteo), `pt-BR` y `en`; la lista vive en `SUPPORTED_LOCALES` (`packages/shared/src/schemas/locale.ts`) y `resolveLocale` mapea los idiomas del dispositivo (cualquier otro `es-*` → `es-419`, cualquier `pt-*` → `pt-BR`, lo no soportado → `en`). Ojo con esto:
1. **`es-AR` es la fuente**: `i18next.d.ts` tipa las claves con sus JSON, así que una clave que no exista ahí rompe el typecheck. `test/i18n-keys.test.ts` exige las mismas claves (salvo sufijos de plural) y variables en los 4 idiomas. Un namespace nuevo = un JSON por idioma + `NAMESPACES` (`instance.ts`) + `i18next.d.ts`.
2. La preferencia es `'system' | AppLocale` en `localStorage['locale']`; para el profe también en `users.locale` (Better Auth `additionalFields`, validado con `appLocaleSchema`; `null` = idioma del dispositivo). `LocaleProfileSync` aplica el del perfil al iniciar sesión; `LanguageCard` lo guarda con `authClient.updateUser`. La app de alumnos solo usa `localStorage`.
3. `main.tsx` carga el idioma (más `en` de fallback) **antes** del primer render; los JSON se cargan lazy por `import.meta.glob` (solo existe en Vite: en `bun test` el preload `test/setup.ts` carga `es-AR` del disco, por eso los tests asertan el copy rioplatense).
4. Un componente que pinta texto traducido llama `useTranslation`, aunque el texto salga de un helper (`weekDayLabel`, `paymentStatusLabel`, `copy.ts` con `i18n.t`): es lo que lo re-renderiza al cambiar de idioma.
5. Fechas y nombres de días/meses van en el idioma de la UI (`useIntlLocale()` / `i18n.language`), **nunca** con `'es-AR'` fijo. Montos y teléfonos **no**: `formatPrice`/`formatPhoneDisplay` siguen al **país** (`lib/region.ts`).
6. Validación: los esquemas (shared y web) llevan **claves** (`'group.nameMin'`) en vez de texto; se pintan con `<FieldError message={errors.x?.message} />` (traduce contra el namespace `validation`). `installZodErrorMap` cubre los mensajes por defecto de Zod.
7. Errores de la API: `errorMessage(error, fallback)` traduce el `code` del Problem Details (namespace `errors`, `codes.*`; los de Better Auth en `auth.*`); los `params` del problema (`limit`, `feature`, `max`, `capacity`) eligen variante y plural. Con la UI en español cae al `detail` del backend; si no, al `fallback`. Un error nuevo del backend que la UI muestre tiene que llevar `code` y su traducción.
8. Lo que arma el backend en español y la UI muestra se redacta en la web a partir de datos estructurados: las alertas de `computeStudentAlerts` traen `razon` + `valores` (la web usa `alertLabel`/`alertDetail` de `features/attention/attention.ts`; `etiqueta`/`detalle` quedan para el backend), y los `message` de la API (importación masiva, preinscripción) se ignoran y se arman con los contadores. Nombres de país: `countryName` (`Intl.DisplayNames`), no `COUNTRY_LABELS`.
9. Pendiente: mails, WhatsApp y el manifest de la PWA (`vite.config.ts`) siguen solo en español (etapa 2: usar `users.locale`).
- `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia). - `.env`, `dist/`, `dev-dist/`, `.turbo/`, `apps/backend/generated/`, `node_modules/` están gitignoreados (que no te extrañe su ausencia).
## Convenciones repo-específicas ## Convenciones repo-específicas
- **Frontend en español**: copy de UI, comentarios y textos en español. - **Commits en inglés**: los mensajes de commit (título y cuerpo) van siempre en inglés, con prefijo Conventional Commits (`feat(i18n): …`, `fix: …`, `chore: …`). Los commits anteriores en español quedan como están.
- **Copy de UI traducido**: ningún texto visible va literal en JSX; va en `apps/web/src/i18n/locales/es-AR/<namespace>.json` (fuente, en rioplatense) y en el mismo cambio en `es-419`, `pt-BR` y `en` (ver gotcha **Multi idioma**). Los comentarios del frontend siguen en español.
- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`).
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client. - **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio. - **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.
- **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`). - **Tailwind v4** con tokens en `@theme` dentro de `apps/web/src/index.css` (p. ej. `--color-accent: #1e90ff`). Se usan como clases auto-generadas: `text-accent`, `bg-success-soft`, etc. Radius por defecto `0.75rem` (`rounded-xl`).

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "reported_payments" ADD COLUMN "note" TEXT;

View File

@@ -0,0 +1,182 @@
-- A person (contact data, per teacher) can now be in several groups: `attendees`
-- becomes the membership and points to `people`. Existing attendees of the same
-- teacher with the same phone (digits only) are merged into one person, and
-- their student-app accounts into one account.
-- All or nothing: a half-applied data migration cannot be retried.
BEGIN;
-- CreateTable
CREATE TABLE "people" (
"id" TEXT NOT NULL,
"created_by_id" TEXT NOT NULL,
"full_name" TEXT NOT NULL,
"email" TEXT,
"phone" TEXT,
"guardian_name" TEXT,
"guardian_phone" TEXT,
"notes" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "people_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "student_account_people" (
"account_id" TEXT NOT NULL,
"person_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "student_account_people_pkey" PRIMARY KEY ("account_id","person_id")
);
-- Grouping: same teacher + same phone digits. `group_rank` splits the (rare)
-- rows that already shared a phone inside one group, which the per-group unique
-- membership would reject: the extra ones become their own person.
CREATE TEMP TABLE "_attendee_keys" AS
SELECT
a."id" AS attendee_id,
a."group_id",
a."created_at",
g."created_by_id",
NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '') AS phone_digits,
ROW_NUMBER() OVER (
PARTITION BY g."created_by_id", a."group_id", NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '')
ORDER BY a."created_at", a."id"
) AS group_rank
FROM "attendees" a
JOIN "groups" g ON g."id" = a."group_id";
CREATE TEMP TABLE "_attendee_person" AS
SELECT
k.attendee_id,
k.created_by_id,
-- The person reuses the id of its oldest attendee.
FIRST_VALUE(k.attendee_id) OVER (
PARTITION BY k.created_by_id,
CASE WHEN k.phone_digits IS NULL THEN k.attendee_id ELSE k.phone_digits || '#' || k.group_rank END
ORDER BY k.created_at, k.attendee_id
) AS person_id,
(k.phone_digits IS NOT NULL AND k.group_rank > 1) AS phone_clash
FROM "_attendee_keys" k;
INSERT INTO "people" ("id", "created_by_id", "full_name", "email", "phone", "guardian_name", "guardian_phone", "notes", "created_at", "updated_at")
SELECT
p.person_id,
MIN(p.created_by_id),
MIN(rep."full_name"),
(ARRAY_AGG(a."email" ORDER BY a."created_at") FILTER (WHERE a."email" IS NOT NULL))[1],
CASE WHEN BOOL_OR(p.phone_clash) THEN NULL ELSE NULLIF(TRIM(MIN(rep."phone")), '') END,
(ARRAY_AGG(a."guardian_name" ORDER BY a."created_at") FILTER (WHERE a."guardian_name" IS NOT NULL))[1],
(ARRAY_AGG(a."guardian_phone" ORDER BY a."created_at") FILTER (WHERE a."guardian_phone" IS NOT NULL))[1],
NULLIF(CONCAT_WS(E'\n\n',
STRING_AGG(DISTINCT NULLIF(TRIM(a."notes"), ''), E'\n\n'),
CASE WHEN BOOL_OR(p.phone_clash) THEN 'Teléfono: ' || MIN(rep."phone") END
), ''),
MIN(a."created_at"),
CURRENT_TIMESTAMP
FROM "_attendee_person" p
JOIN "attendees" a ON a."id" = p.attendee_id
JOIN "attendees" rep ON rep."id" = p.person_id
GROUP BY p.person_id;
-- AlterTable: attendees -> membership
ALTER TABLE "attendees" ADD COLUMN "person_id" TEXT;
UPDATE "attendees" a SET "person_id" = p.person_id FROM "_attendee_person" p WHERE p.attendee_id = a."id";
ALTER TABLE "attendees" ALTER COLUMN "person_id" SET NOT NULL;
-- Student accounts: link them to the person instead of the membership.
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
SELECT sa."account_id", p.person_id, MIN(sa."created_at")
FROM "student_account_attendees" sa
JOIN "_attendee_person" p ON p.attendee_id = sa."attendee_id"
GROUP BY sa."account_id", p.person_id;
-- A merged person may end up with several accounts: keep the one used most
-- recently (else the oldest) and fold the others into it.
CREATE TEMP TABLE "_account_merge" AS
WITH ranked AS (
SELECT
sap."person_id",
sap."account_id",
ROW_NUMBER() OVER (
PARTITION BY sap."person_id"
ORDER BY (
SELECT MAX(s."last_used_at") FROM "student_sessions" s
WHERE s."account_id" = sap."account_id" AND s."revoked_at" IS NULL
) DESC NULLS LAST, acc."created_at", acc."id"
) AS rn
FROM "student_account_people" sap
JOIN "student_accounts" acc ON acc."id" = sap."account_id"
)
SELECT DISTINCT ON (d."account_id") d."account_id" AS old_id, k."account_id" AS keep_id
FROM ranked d
JOIN ranked k ON k."person_id" = d."person_id" AND k.rn = 1
WHERE d.rn > 1 AND d."account_id" <> k."account_id"
ORDER BY d."account_id";
INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
SELECT m.keep_id, sap."person_id", sap."created_at"
FROM "student_account_people" sap
JOIN "_account_merge" m ON m.old_id = sap."account_id"
ON CONFLICT DO NOTHING;
UPDATE "absence_notices" n SET "account_id" = m.keep_id FROM "_account_merge" m WHERE n."account_id" = m.old_id;
UPDATE "reported_payments" r SET "account_id" = m.keep_id FROM "_account_merge" m WHERE r."account_id" = m.old_id;
UPDATE "student_accounts" k
SET "recovery_email" = o."recovery_email", "recovery_email_verified_at" = o."recovery_email_verified_at"
FROM "_account_merge" m
JOIN "student_accounts" o ON o."id" = m.old_id
WHERE k."id" = m.keep_id AND k."recovery_email" IS NULL AND o."recovery_email" IS NOT NULL;
-- Sessions, tokens and passkeys of the folded accounts go with them (cascade);
-- their links are removed by hand because that FK is created further down.
DELETE FROM "student_account_people" WHERE "account_id" IN (SELECT old_id FROM "_account_merge");
DELETE FROM "student_accounts" WHERE "id" IN (SELECT old_id FROM "_account_merge");
-- DropTable
DROP TABLE "student_account_attendees";
-- AlterTable
ALTER TABLE "attendees"
DROP COLUMN "full_name",
DROP COLUMN "email",
DROP COLUMN "phone",
DROP COLUMN "guardian_name",
DROP COLUMN "guardian_phone",
DROP COLUMN "notes";
-- CreateIndex
CREATE INDEX "people_created_by_id_idx" ON "people"("created_by_id");
-- One person per phone and teacher. Partial: Prisma does not model it.
CREATE UNIQUE INDEX "people_owner_phone_key" ON "people"("created_by_id", "phone") WHERE "phone" IS NOT NULL;
-- CreateIndex
CREATE INDEX "student_account_people_person_id_idx" ON "student_account_people"("person_id");
-- CreateIndex
CREATE INDEX "attendees_person_id_idx" ON "attendees"("person_id");
-- CreateIndex
CREATE UNIQUE INDEX "attendees_group_id_person_id_key" ON "attendees"("group_id", "person_id");
-- AddForeignKey
ALTER TABLE "people" ADD CONSTRAINT "people_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "attendees" ADD CONSTRAINT "attendees_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
DROP TABLE "_account_merge";
DROP TABLE "_attendee_person";
DROP TABLE "_attendee_keys";
COMMIT;

View File

@@ -0,0 +1 @@
ALTER TABLE "users" ADD COLUMN "locale" TEXT;

View File

@@ -8,6 +8,8 @@ model User {
image String? image String?
onboardingCompleted Boolean @default(false) @map("onboarding_completed") onboardingCompleted Boolean @default(false) @map("onboarding_completed")
country String? @map("country_code") country String? @map("country_code")
// UI language the person chose (es-AR, es-419, pt-BR, en); null follows the device.
locale String? @map("locale")
// When the professor chose Free or Pro in the onboarding (mandatory step). // When the professor chose Free or Pro in the onboarding (mandatory step).
planSelectedAt DateTime? @map("plan_selected_at") planSelectedAt DateTime? @map("plan_selected_at")
// Bank transfer details shown to students when they report a payment. // Bank transfer details shown to students when they report a payment.
@@ -28,6 +30,7 @@ model User {
whatsappAccount WhatsappAccount? whatsappAccount WhatsappAccount?
subscription BillingSubscription? subscription BillingSubscription?
studentAccounts StudentAccount[] @relation("StudentAccountsCreated") studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
people Person[] @relation("OwnerPeople")
@@map("users") @@map("users")
} }

View File

@@ -72,31 +72,55 @@ enum AttendeeStatus {
DROPPED DROPPED
} }
model Attendee { // A person the teacher works with (student, or the guardian's child). Contact
// data lives here once; `Attendee` is their membership in each group, so one
// person can be in several groups of the same teacher. The phone is unique per
// teacher through a hand-written partial index (`people_owner_phone_key`,
// `WHERE phone IS NOT NULL`): Prisma does not model it.
model Person {
id String @id @default(cuid()) id String @id @default(cuid())
groupId String @map("group_id") createdById String @map("created_by_id")
fullName String @map("full_name") fullName String @map("full_name")
email String? email String?
phone String? phone String?
guardianName String? @map("guardian_name") guardianName String? @map("guardian_name")
guardianPhone String? @map("guardian_phone") guardianPhone String? @map("guardian_phone")
notes String? notes String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
attendees Attendee[]
studentAccounts StudentAccountPerson[]
@@index([createdById])
@@map("people")
}
// Membership of a person in a group. Status, attendance, fees and the absence
// link (`notifyToken`) are per group.
model Attendee {
id String @id @default(cuid())
groupId String @map("group_id")
personId String @map("person_id")
notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token") notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
status AttendeeStatus @default(ACTIVE) status AttendeeStatus @default(ACTIVE)
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey") group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
payments Payment[] payments Payment[]
attendances Attendance[] attendances Attendance[]
slotReleases SlotRelease[] slotReleases SlotRelease[]
outboundMessages OutboundMessage[] outboundMessages OutboundMessage[]
alertResolutions AttendeeAlertResolution[] alertResolutions AttendeeAlertResolution[]
studentAccounts StudentAccountAttendee[]
absenceNotices AbsenceNotice[] absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[] reportedPayments ReportedPayment[]
@@unique([groupId, personId])
@@index([groupId], map: "attendees_groupId_idx") @@index([groupId], map: "attendees_groupId_idx")
@@index([personId])
@@map("attendees") @@map("attendees")
} }

View File

@@ -24,7 +24,7 @@ model StudentAccount {
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade) createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
attendees StudentAccountAttendee[] people StudentAccountPerson[]
tokens StudentAccessToken[] tokens StudentAccessToken[]
sessions StudentSession[] sessions StudentSession[]
passkeys StudentPasskey[] passkeys StudentPasskey[]
@@ -37,17 +37,20 @@ model StudentAccount {
@@map("student_accounts") @@map("student_accounts")
} }
model StudentAccountAttendee { // The account is linked to people, not to memberships: it sees every group the
// person is in (also the ones added later). A guardian may be linked to several
// children (N:N).
model StudentAccountPerson {
accountId String @map("account_id") accountId String @map("account_id")
attendeeId String @map("attendee_id") personId String @map("person_id")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade) account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade) person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
@@id([accountId, attendeeId]) @@id([accountId, personId])
@@index([attendeeId]) @@index([personId])
@@map("student_account_attendees") @@map("student_account_people")
} }
enum StudentTokenKind { enum StudentTokenKind {
@@ -203,6 +206,8 @@ model ReportedPayment {
receiptMime String @map("receipt_mime") receiptMime String @map("receipt_mime")
receiptName String @map("receipt_name") receiptName String @map("receipt_name")
receiptSize Int @map("receipt_size") receiptSize Int @map("receipt_size")
// Optional message from the student to the teacher.
note String?
status ReportedPaymentStatus @default(REPORTED) status ReportedPaymentStatus @default(REPORTED)
reviewedById String? @map("reviewed_by_id") reviewedById String? @map("reviewed_by_id")
reviewedAt DateTime? @map("reviewed_at") reviewedAt DateTime? @map("reviewed_at")

View File

@@ -27,6 +27,7 @@ import { invitationsRoutes } from './modules/invitations';
import { mpRoutes } from './modules/mp'; import { mpRoutes } from './modules/mp';
import { onboardingRoutes } from './modules/onboarding'; import { onboardingRoutes } from './modules/onboarding';
import { paymentsRoutes } from './modules/payments'; import { paymentsRoutes } from './modules/payments';
import { peopleRoutes } from './modules/people';
import { studentPortalRoutes } from './modules/student-portal'; import { studentPortalRoutes } from './modules/student-portal';
import { waitlistRoutes } from './modules/waitlist'; import { waitlistRoutes } from './modules/waitlist';
import { whatsappRoutes } from './modules/whatsapp'; import { whatsappRoutes } from './modules/whatsapp';
@@ -68,6 +69,7 @@ api.route('/classes', classesRoutes);
api.route('/students', studentStatusRoutes); api.route('/students', studentStatusRoutes);
api.route('/groups-risk', groupsRiskOverviewRoute); api.route('/groups-risk', groupsRiskOverviewRoute);
api.route('/attention', attentionRoutes); api.route('/attention', attentionRoutes);
api.route('/people', peopleRoutes);
api.route('/student-portal', studentPortalRoutes); api.route('/student-portal', studentPortalRoutes);
app.notFound((c) => { app.notFound((c) => {

View File

@@ -21,6 +21,7 @@ export function conflictProblem(params: {
detail: string; detail: string;
code?: string; code?: string;
instance?: string; instance?: string;
params?: ProblemDetails['params'];
}): ProblemDetails { }): ProblemDetails {
return { return {
type: `${PROBLEM_DOMAIN}/problems/conflict`, type: `${PROBLEM_DOMAIN}/problems/conflict`,
@@ -29,6 +30,7 @@ export function conflictProblem(params: {
detail: params.detail, detail: params.detail,
instance: params.instance, instance: params.instance,
code: params.code, code: params.code,
...(params.params ? { params: params.params } : {}),
}; };
} }
@@ -186,6 +188,7 @@ export function capacityReachedProblem(capacity: number | null): ProblemDetails
? `El grupo alcanzó su cupo máximo de ${capacity} miembros.` ? `El grupo alcanzó su cupo máximo de ${capacity} miembros.`
: 'El grupo alcanzó su cupo máximo de miembros.', : 'El grupo alcanzó su cupo máximo de miembros.',
code: 'group_capacity_reached', code: 'group_capacity_reached',
...(capacity ? { params: { capacity } } : {}),
}); });
} }
@@ -216,13 +219,18 @@ export function noAttendeesToBillProblem(): ProblemDetails {
code: 'no_attendees_to_bill', code: 'no_attendees_to_bill',
}); });
} }
function paymentRequiredProblem(params: { detail: string; code: string }): ProblemDetails { function paymentRequiredProblem(params: {
detail: string;
code: string;
params?: ProblemDetails['params'];
}): ProblemDetails {
return { return {
type: `${PROBLEM_DOMAIN}/problems/plan`, type: `${PROBLEM_DOMAIN}/problems/plan`,
title: 'Payment Required', title: 'Payment Required',
status: 402, status: 402,
detail: params.detail, detail: params.detail,
code: params.code, code: params.code,
...(params.params ? { params: params.params } : {}),
}; };
} }
@@ -236,6 +244,7 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob
? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.` ? `El plan Free permite hasta ${max} ${max === 1 ? 'grupo' : 'grupos'}. Pasate a Pro para crear más.`
: `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`, : `El plan Free permite hasta ${max} alumnos activos. Pasate a Pro para sumar más.`,
code: 'plan_limit_reached', code: 'plan_limit_reached',
params: { limit, max },
}); });
} }
@@ -247,6 +256,7 @@ export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutom
? 'Cobrar con Mercado Pago está disponible en el plan Pro.' ? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.', : 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
code: 'plan_feature_required', code: 'plan_feature_required',
params: { feature },
}); });
} }

View File

@@ -8,6 +8,7 @@ import type {
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
export const HISTORY_SESSIONS_LIMIT = 20; export const HISTORY_SESSIONS_LIMIT = 20;
@@ -33,8 +34,8 @@ export class GetAttendeeHistory {
const attendee = await db.attendee.findFirst({ const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId }, where: { id: attendeeId, groupId },
select: { id: true, fullName: true, createdAt: true }, select: { id: true, createdAt: true, person: { select: { fullName: true } } },
}); }).then((row) => row && flattenPerson(row));
if (!attendee) { if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId)); return err(notFoundResourceProblem('Attendee', attendeeId));
} }

View File

@@ -15,6 +15,7 @@ import {
URGENT_MEMBERS_LIMIT, URGENT_MEMBERS_LIMIT,
} from '@gruperly/shared'; } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance'; import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
@@ -76,8 +77,8 @@ export class GetGroupsRiskOverview {
const [attendees, sessions, attendances] = await Promise.all([ const [attendees, sessions, attendances] = await Promise.all([
db.attendee.findMany({ db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' }, where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true, fullName: true, createdAt: true }, select: { id: true, groupId: true, createdAt: true, person: { select: { fullName: true } } },
}) as Promise<AttendeeRow[]>, }).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
db.classSession.findMany({ db.classSession.findMany({
where: { groupId: { in: groupIds }, startsAt: { gte: since } }, where: { groupId: { in: groupIds }, startsAt: { gte: since } },
select: { id: true, groupId: true, startsAt: true }, select: { id: true, groupId: true, startsAt: true },

View File

@@ -8,6 +8,7 @@ import type {
} from '@gruperly/shared'; } from '@gruperly/shared';
import { ok, summarizeMemberAttendance } from '@gruperly/shared'; import { ok, summarizeMemberAttendance } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance'; import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk'; import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
@@ -73,8 +74,8 @@ export async function findStudentsAtRisk(
}), }),
db.attendee.findMany({ db.attendee.findMany({
where: { groupId, status: 'ACTIVE' }, where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true, createdAt: true }, select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
}), }).then((rows) => rows.map(flattenPerson)),
db.attendance.findMany({ db.attendance.findMany({
where: { attendee: { groupId } }, where: { attendee: { groupId } },
select: { select: {

View File

@@ -0,0 +1,24 @@
import type { AddAttendeeToGroup as AddAttendeeToGroupBody } from '@gruperly/shared';
import { AddAttendeeToGroupSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { AddAttendeeToGroup } from './use-case';
const route = new Hono();
route.post('/:groupId/attendees/:attendeeId/add-to-group', validate.json(AddAttendeeToGroupSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new AddAttendeeToGroup();
const result = await useCase.execute({
groupId: c.req.param('groupId'),
attendeeId: c.req.param('attendeeId'),
userId: user.id,
targetGroupId: (c.req.valid('json') as AddAttendeeToGroupBody).targetGroupId,
});
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,88 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, 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 } from '@/modules/group-waitlist/lib/helpers';
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
import { alreadyInGroupProblem, isUniqueViolation } from '@/modules/people/lib/people';
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
type AddAttendeeToGroupDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
};
type AddAttendeeToGroupCommand = {
groupId: string;
attendeeId: string;
userId: string;
targetGroupId: string;
};
/* "Agregar a otro grupo": the same person gets a membership in another group of
the teacher and keeps this one. It does not take a new student slot of the
plan (the person is already counted) but the target's capacity applies. A
former membership there (DROPPED) is reactivated, history included. */
export class AddAttendeeToGroup {
constructor(private readonly deps: AddAttendeeToGroupDeps = {}) {}
async execute(command: AddAttendeeToGroupCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
const { groupId, attendeeId, userId, targetGroupId } = command;
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
if (!sourceResult.ok) return sourceResult;
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true },
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
if (targetGroupId === groupId) {
return err(
conflictProblem({
detail: 'El miembro ya pertenece a este grupo.',
code: 'attendee_same_group',
}),
);
}
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
if (!targetResult.ok) return targetResult;
const target = targetResult.value;
try {
return await unitOfWork.executeResult(
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
const former = await tx.attendee.findFirst({
where: { groupId: targetGroupId, personId: attendee.personId },
select: { id: true, status: true },
});
if (former && former.status !== 'DROPPED') return err(alreadyInGroupProblem());
const canJoin = await checkCanJoinGroup(tx, target, null);
if (!canJoin.ok) return canJoin;
const membership = former
? await tx.attendee.update({
where: { id: former.id },
data: { status: 'ACTIVE' },
include: attendeeWithPerson,
})
: await tx.attendee.create({
data: { groupId: targetGroupId, personId: attendee.personId },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(membership));
},
);
} catch (error) {
// Two clicks at once: the unique (group, person) lets only one through.
if (isUniqueViolation(error)) return err(alreadyInGroupProblem());
throw error;
}
}
}

View File

@@ -8,6 +8,7 @@ import {
notFoundResourceProblem, notFoundResourceProblem,
} from '@/http/problem-builders'; } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { phoneVariants } from '@/modules/people/lib/people';
import { normalizePhone } from '../../lib/helpers'; import { normalizePhone } from '../../lib/helpers';
type AddToGroupWaitlistDeps = { type AddToGroupWaitlistDeps = {
@@ -72,10 +73,7 @@ export class AddToGroupWaitlist {
const existingAttendee = await db.attendee.findFirst({ const existingAttendee = await db.attendee.findFirst({
where: { where: {
groupId, groupId,
OR: [ person: { phone: { in: phoneVariants(payload.phone) } },
{ phone },
{ phone: payload.phone.trim() },
],
}, },
}); });

View File

@@ -9,10 +9,10 @@ import { err, ok } from '@gruperly/shared';
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders'; import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; import { type AttendeeRecord, attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type BulkCreateAttendeesDeps = { type BulkCreateAttendeesDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>; planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
@@ -43,23 +43,29 @@ export class BulkCreateAttendeesUseCase {
return err(noGroupAccessProblem()); return err(noGroupAccessProblem());
} }
// Load the group's existing phone numbers /* The teacher's people by phone: a row whose phone is already someone they
const existingAttendees = await db.attendee.findMany({ have is added to this group as that person (linked), unless that person
where: { groupId }, is already in the group (duplicate). */
select: { phone: true }, const people = await db.person.findMany({
where: { createdById: group.createdById, phone: { not: null } },
select: {
id: true,
phone: true,
attendees: { select: { groupId: true, status: true } },
},
}); });
const peopleByPhone = new Map<string, (typeof people)[number]>();
const existingPhones = new Set<string>(); for (const person of people) {
for (const a of existingAttendees) { if (person.phone) peopleByPhone.set(normalizePhone(person.phone), person);
if (a.phone) {
existingPhones.add(normalizePhone(a.phone));
}
} }
let duplicatesCount = 0; let duplicatesCount = 0;
let invalidCount = 0; let invalidCount = 0;
const toCreateData: Array<{ // Only people not active in any group take a new slot of the plan.
groupId: string; let newlyCounted = 0;
const seenPhones = new Set<string>();
const toLink: string[] = [];
const toCreate: Array<{
fullName: string; fullName: string;
phone: string; phone: string;
email: string | null; email: string | null;
@@ -75,14 +81,21 @@ export class BulkCreateAttendeesUseCase {
continue; continue;
} }
if (existingPhones.has(phone)) { const existing = peopleByPhone.get(phone);
if (seenPhones.has(phone) || existing?.attendees.some((membership) => membership.groupId === groupId)) {
duplicatesCount++; duplicatesCount++;
continue; continue;
} }
seenPhones.add(phone);
existingPhones.add(phone); if (existing) {
toCreateData.push({ toLink.push(existing.id);
groupId, if (!existing.attendees.some((membership) => membership.status === 'ACTIVE')) newlyCounted++;
continue;
}
newlyCounted++;
toCreate.push({
fullName: rawFullName, fullName: rawFullName,
phone, phone,
email: item.email?.trim() || null, email: item.email?.trim() || null,
@@ -94,26 +107,44 @@ export class BulkCreateAttendeesUseCase {
// reason about than a clear "your plan allows N". // reason about than a clear "your plan allows N".
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees( const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
group.createdById, group.createdById,
toCreateData.length, newlyCounted,
); );
if (!allowed.ok) { if (!allowed.ok) {
return allowed; return allowed;
} }
const createdRecords: AttendeeRecord[] = []; const createdRecords: AttendeeRecord[] = [];
for (const data of toCreateData) { for (const personId of toLink) {
const record = await db.attendee.create({ data }); createdRecords.push(
createdRecords.push(record as unknown as AttendeeRecord); await db.attendee.create({
data: { groupId, personId },
include: attendeeWithPerson,
}),
);
}
for (const data of toCreate) {
createdRecords.push(
await db.attendee.create({
data: {
group: { connect: { id: groupId } },
person: { create: { ...data, createdById: group.createdById } },
},
include: attendeeWithPerson,
}),
);
} }
const createdCount = createdRecords.length; const createdCount = createdRecords.length;
const linkedCount = toLink.length;
const linkedNote = linkedCount > 0 ? ` (${linkedCount} ya estaban en otros de tus grupos)` : '';
const message = duplicatesCount > 0 const message = duplicatesCount > 0
? `${createdCount} alumnos agregados con éxito, ${duplicatesCount} duplicados omitidos.` ? `${createdCount} alumnos agregados con éxito${linkedNote}, ${duplicatesCount} duplicados omitidos.`
: `${createdCount} alumnos agregados con éxito.`; : `${createdCount} alumnos agregados con éxito${linkedNote}.`;
return ok({ return ok({
totalProcessed: payload.attendees.length, totalProcessed: payload.attendees.length,
createdCount, createdCount,
linkedCount,
duplicatesCount, duplicatesCount,
invalidCount, invalidCount,
message, message,

View File

@@ -4,16 +4,21 @@ import { err, ok } from '@gruperly/shared';
import { import {
alreadyWaitlistedProblem, alreadyWaitlistedProblem,
capacityReachedProblem, capacityReachedProblem,
conflictProblem,
noGroupAccessProblem, noGroupAccessProblem,
notFoundResourceProblem, notFoundResourceProblem,
} from '@/http/problem-builders'; } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; import {
alreadyInGroupProblem,
findPersonByPhone,
isUniqueViolation,
personExistsProblem,
} from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type CreateAttendeeDeps = { type CreateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>; planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
@@ -50,26 +55,38 @@ export class CreateAttendeeUseCase {
} }
const phone = normalizePhone(payload.phone); const phone = normalizePhone(payload.phone);
const existing = await db.attendee.findFirst({
where: {
groupId,
OR: [
{ phone },
{ phone: payload.phone.trim() },
],
},
});
if (existing) { /* The person: the one the form picked (`personId`, after the "ya existe"
hint) or a new one. A phone the teacher already has is never duplicated. */
let person: { id: string; fullName: string } | null = null;
if (payload.personId) {
person = await db.person.findFirst({
where: { id: payload.personId, createdById: group.createdById },
select: { id: true, fullName: true },
});
if (!person) {
return err(notFoundResourceProblem('Person', payload.personId));
}
} else {
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
if (samePhone) {
return err( return err(
conflictProblem({ samePhone.attendees.some((membership) => membership.groupId === groupId)
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.', ? alreadyInGroupProblem()
code: 'attendee_already_registered', : personExistsProblem(),
}),
); );
} }
}
const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim(); // A former member (DROPPED) comes back on the same membership: history included.
const membership = person
? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } })
: null;
if (membership && membership.status !== 'DROPPED') {
return err(alreadyInGroupProblem());
}
const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
if (group.capacity !== null) { if (group.capacity !== null) {
const currentCount = await db.attendee.count({ const currentCount = await db.attendee.count({
@@ -108,25 +125,51 @@ export class CreateAttendeeUseCase {
} }
} }
// The owner's plan pays for the attendee, whoever adds it. // The owner's plan pays for the attendee, whoever adds it. It counts people:
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById); // someone already active in another group does not take a new slot.
const alreadyCounted = person
? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0
: false;
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
group.createdById,
alreadyCounted ? 0 : 1,
);
if (!allowed.ok) { if (!allowed.ok) {
return allowed; return allowed;
} }
const attendee = await db.attendee.create({ try {
const attendee = membership
? await db.attendee.update({
where: { id: membership.id },
data: { status: 'ACTIVE' },
include: attendeeWithPerson,
})
: await db.attendee.create({
data: { data: {
groupId, group: { connect: { id: groupId } },
person: person
? { connect: { id: person.id } }
: {
create: {
createdById: group.createdById,
fullName, fullName,
phone, phone,
email: payload.email?.trim() || null, email: payload.email?.trim() || null,
notes: payload.notes?.trim() || null, notes: payload.notes?.trim() || null,
}, },
},
},
include: attendeeWithPerson,
}); });
return ok({ return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) });
outcome: 'created', } catch (error) {
attendee: toAttendeeDto(attendee as unknown as AttendeeRecord), // Lost a race: someone created that person or membership meanwhile.
}); if (isUniqueViolation(error)) {
return err(person ? alreadyInGroupProblem() : personExistsProblem());
}
throw error;
}
} }
} }

View File

@@ -4,7 +4,7 @@ import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { toAttendeeListItemDto } from '../../lib/helpers'; import { attendeeWithPerson, toAttendeeListItemDto } from '../../lib/helpers';
type ListAttendeesDeps = { type ListAttendeesDeps = {
db?: Pick<PrismaClient, 'attendee'>; db?: Pick<PrismaClient, 'attendee'>;
@@ -28,6 +28,7 @@ export class ListAttendees {
take: query.pageSize, take: query.pageSize,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
include: { include: {
...attendeeWithPerson,
// By class date, not by `markedAt`: marking attendance late must not // By class date, not by `markedAt`: marking attendance late must not
// change which class counts as recent. // change which class counts as recent.
attendances: { attendances: {

View File

@@ -4,8 +4,8 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
import { toAttendeeDetailDto } from '../../lib/helpers'; import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
type GetAttendeeDeps = { type GetAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>; db?: Pick<PrismaClient, 'group' | 'attendee'>;
@@ -31,6 +31,7 @@ export class GetAttendee {
const attendee = await db.attendee.findFirst({ const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId }, where: { id: attendeeId, groupId },
include: { include: {
person: { select: { ...personContactSelect, ...personMembershipsSelect } },
payments: { payments: {
where: { where: {
status: { not: 'CANCELLED' }, status: { not: 'CANCELLED' },
@@ -46,7 +47,14 @@ export class GetAttendee {
return err(notFoundResourceProblem('Attendee', attendeeId)); return err(notFoundResourceProblem('Attendee', attendeeId));
} }
return ok(toAttendeeDetailDto(attendee)); const { attendees: memberships, ...person } = attendee.person;
return ok(
toAttendeeDetailDto({
...attendee,
person,
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
}),
);
} }
} }

View File

@@ -0,0 +1,24 @@
import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared';
import { MoveAttendeeSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { MoveAttendee } from './use-case';
const route = new Hono();
route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new MoveAttendee();
const result = await useCase.execute({
groupId: c.req.param('groupId'),
attendeeId: c.req.param('attendeeId'),
userId: user.id,
targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId,
});
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,77 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, 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 } from '@/modules/group-waitlist/lib/helpers';
import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
type MoveAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>;
unitOfWork?: UnitOfWork;
now?: () => Date;
};
type MoveAttendeeCommand = {
groupId: string;
attendeeId: string;
userId: string;
targetGroupId: string;
};
/* Moves a member to another group of the same teacher. It is the same attendee
with another `groupId`: past attendance, fees (they stay owed to the old
group) and the student app access go with them. Only what was booked for
the old group's future classes is undone: absence notices, the EXCUSED rows
they left and the released slots. */
export class MoveAttendee {
constructor(private readonly deps: MoveAttendeeDeps = {}) {}
async execute(command: MoveAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
const { groupId, attendeeId, userId, targetGroupId } = command;
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
const now = this.deps.now?.() ?? new Date();
const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
if (!sourceResult.ok) return sourceResult;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
if (targetGroupId === groupId) {
return err(
conflictProblem({
detail: 'El miembro ya pertenece a este grupo.',
code: 'attendee_same_group',
}),
);
}
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
if (!targetResult.ok) return targetResult;
return unitOfWork.executeResult(
async (tx: Prisma.TransactionClient): Promise<Result<AttendeeDto, ProblemDetails>> => {
const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId);
if (!canJoin.ok) return canJoin;
const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } };
await tx.absenceNotice.updateMany({
where: { attendeeId, cancelledAt: null, ...futureOldClasses },
data: { cancelledAt: now },
});
await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } });
await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } });
const moved = await tx.attendee.update({
where: { id: attendeeId },
data: { groupId: targetGroupId },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(moved));
},
);
}
}

View File

@@ -36,7 +36,10 @@ export class RemoveAttendee {
} }
const group = groupResult.value; const group = groupResult.value;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } }); const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true },
});
if (!attendee) { if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId)); return err(notFoundResourceProblem('Attendee', attendeeId));
} }
@@ -49,6 +52,10 @@ export class RemoveAttendee {
return unitOfWork.executeResult( return unitOfWork.executeResult(
async (tx: Prisma.TransactionClient): Promise<Result<RemoveAttendeeResult, ProblemDetails>> => { async (tx: Prisma.TransactionClient): Promise<Result<RemoveAttendeeResult, ProblemDetails>> => {
await tx.attendee.delete({ where: { id: attendeeId } }); await tx.attendee.delete({ where: { id: attendeeId } });
// Their last group: the person goes too (with their student app link).
await tx.person.deleteMany({
where: { id: attendee.personId, attendees: { none: {} } },
});
if (!options.promoteFromWaitlist) { if (!options.promoteFromWaitlist) {
return ok({ removedAttendeeId: attendeeId, promoted: null }); return ok({ removedAttendeeId: attendeeId, promoted: null });

View File

@@ -4,10 +4,11 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { toAttendeeDto } from '../../lib/helpers'; import { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people';
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type UpdateAttendeeDeps = { type UpdateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'person'>;
}; };
type UpdateAttendeeCommand = { type UpdateAttendeeCommand = {
@@ -26,19 +27,38 @@ export class UpdateAttendeeDetails {
const access = await findGroupForUser(db, groupId, userId); const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) return access; if (!access.ok) return access;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } }); const attendee = await db.attendee.findFirst({
where: { id: attendeeId, groupId },
select: { personId: true },
});
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
const updated = await db.attendee.update({ // Contact data is the person's: the change shows in every group they are in.
where: { id: attendeeId }, try {
await db.person.update({
where: { id: attendee.personId },
data: normalizeEditableFields(input), data: normalizeEditableFields(input),
}); });
} catch (error) {
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
throw error;
}
const updated = await db.attendee.findUniqueOrThrow({
where: { id: attendeeId },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(updated)); return ok(toAttendeeDto(updated));
} }
} }
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee { function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
return Object.fromEntries( return Object.fromEntries(
Object.entries(input).map(([key, value]) => [key, value === '' ? null : value]), Object.entries(input).map(([key, value]) => {
if (value === '') return [key, null];
// Same normalization as the add form, so the phone keeps matching.
if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)];
return [key, value];
}),
); );
} }

View File

@@ -1,17 +1,37 @@
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared'; import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
export type AttendeeRecord = { /* Contact data of the person behind an attendee (shared by all their groups). */
export const personContactSelect = {
id: true,
fullName: true,
email: true,
phone: true,
guardianName: true,
guardianPhone: true,
notes: true,
} as const;
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
export const attendeeWithPerson = { person: { select: personContactSelect } } as const;
export type PersonContactRecord = {
id: string; id: string;
groupId: string;
fullName: string; fullName: string;
email: string | null; email: string | null;
phone: string | null; phone: string | null;
guardianName: string | null; guardianName: string | null;
guardianPhone: string | null; guardianPhone: string | null;
notes: string | null; notes: string | null;
};
export type AttendeeRecord = {
id: string;
groupId: string;
personId: string;
notifyToken?: string | null; notifyToken?: string | null;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
person: PersonContactRecord;
}; };
/** Listing item with the attendance and payment summary already resolved. */ /** Listing item with the attendance and payment summary already resolved. */
@@ -25,18 +45,20 @@ export type AttendeeListItemRecord = AttendeeRecord & {
export type AttendeeDetailRecord = AttendeeRecord & { export type AttendeeDetailRecord = AttendeeRecord & {
payments: AttendeeListItemRecord['payments']; payments: AttendeeListItemRecord['payments'];
otherGroups: AttendeeDetailDto['otherGroups'];
}; };
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto { export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
return { return {
id: record.id, id: record.id,
groupId: record.groupId, groupId: record.groupId,
fullName: record.fullName, personId: record.personId,
email: record.email, fullName: record.person.fullName,
phone: record.phone, email: record.person.email,
guardianName: record.guardianName, phone: record.person.phone,
guardianPhone: record.guardianPhone, guardianName: record.person.guardianName,
notes: record.notes, guardianPhone: record.person.guardianPhone,
notes: record.person.notes,
notifyToken: record.notifyToken ?? null, notifyToken: record.notifyToken ?? null,
createdAt: record.createdAt.toISOString(), createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(), updatedAt: record.updatedAt.toISOString(),
@@ -68,6 +90,7 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai
return { return {
...toAttendeeDto(record), ...toAttendeeDto(record),
payment: pickRelevantPayment(record.payments), payment: pickRelevantPayment(record.payments),
otherGroups: record.otherGroups,
}; };
} }
@@ -91,3 +114,13 @@ export function normalizePhone(rawPhone: string): string {
const digitsOnly = trimmed.replace(/\D/g, ''); const digitsOnly = trimmed.replace(/\D/g, '');
return hasPlus ? `+${digitsOnly}` : digitsOnly; return hasPlus ? `+${digitsOnly}` : digitsOnly;
} }
/* For queries that select a few person fields next to the attendee's: turns
`{ id, person: { fullName } }` into `{ id, fullName }`, so the code reading
flat rows stays as it was. */
export function flattenPerson<TRow extends { person: object }>(
row: TRow,
): Omit<TRow, 'person'> & TRow['person'] {
const { person, ...rest } = row;
return { ...rest, ...person };
}

View File

@@ -11,7 +11,9 @@ import type {
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared'; import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance'; import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { contactPhone } from '@/modules/people/lib/people';
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind'; import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
type GetAttentionOverviewDeps = { type GetAttentionOverviewDeps = {
@@ -82,9 +84,14 @@ export class GetAttentionOverview {
db.user.findUnique({ where: { id: userId }, select: { country: true } }), db.user.findUnique({ where: { id: userId }, select: { country: true } }),
db.attendee.findMany({ db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' }, where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true }, select: {
id: true,
groupId: true,
createdAt: true,
person: { select: { fullName: true, phone: true, guardianPhone: true } },
},
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
}) as Promise<AttendeeRow[]>, }).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
// Past classes only, most recent first: `toMemberAttendance` keeps the // Past classes only, most recent first: `toMemberAttendance` keeps the
// last 20 per attendee, more than the 6-class window needs. // last 20 per attendee, more than the 6-class window needs.
db.classSession.findMany({ db.classSession.findMany({
@@ -154,7 +161,7 @@ export class GetAttentionOverview {
firma: row.signature, firma: row.signature,
})); }));
const phone = attendee.phone ?? attendee.guardianPhone; const phone = contactPhone(attendee);
return { return {
attendeeId: attendee.id, attendeeId: attendee.id,
fullName: attendee.fullName, fullName: attendee.fullName,

View File

@@ -1,4 +1,5 @@
import { passkey } from '@better-auth/passkey'; import { passkey } from '@better-auth/passkey';
import { appLocaleSchema } from '@gruperly/shared';
import { betterAuth } from 'better-auth'; import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma'; import { prismaAdapter } from 'better-auth/adapters/prisma';
import { organization } from 'better-auth/plugins/organization'; import { organization } from 'better-auth/plugins/organization';
@@ -11,6 +12,18 @@ export const auth = betterAuth({
database: prismaAdapter(getPrismaClient(), { database: prismaAdapter(getPrismaClient(), {
provider: 'postgresql', provider: 'postgresql',
}), }),
user: {
additionalFields: {
// UI language chosen in Ajustes; null means "follow the device". The web
// saves it with updateUser and reads it back from the session.
locale: {
type: 'string',
required: false,
input: true,
validator: { input: appLocaleSchema.nullable() },
},
},
},
emailAndPassword: { emailAndPassword: {
enabled: true, enabled: true,
minPasswordLength: 8, minPasswordLength: 8,

View File

@@ -86,7 +86,7 @@ export type Entitlements = PlanResolution & {
}; };
type PlanGuardDeps = { type PlanGuardDeps = {
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>; db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'person'>;
enforced?: boolean; enforced?: boolean;
graceDays?: number; graceDays?: number;
now?: () => Date; now?: () => Date;
@@ -116,7 +116,10 @@ export class PlanGuard {
select: { status: true, authorizedAt: true, paidThrough: true }, select: { status: true, authorizedAt: true, paidThrough: true },
}), }),
db.group.count({ where: { createdById: ownerId } }), db.group.count({ where: { createdById: ownerId } }),
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }), // People, not memberships: someone in three groups is one student.
db.person.count({
where: { createdById: ownerId, attendees: { some: { status: 'ACTIVE' } } },
}),
]); ]);
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays()); const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());

View File

@@ -32,6 +32,7 @@ export class GetAbsenceDetails {
where: { notifyToken: query.token }, where: { notifyToken: query.token },
include: { include: {
group: { select: { id: true, name: true, days: true, time: true } }, group: { select: { id: true, name: true, days: true, time: true } },
person: { select: { fullName: true } },
}, },
}); });
if (!attendee) { if (!attendee) {
@@ -46,7 +47,7 @@ export class GetAbsenceDetails {
if (candidates.length === 0) { if (candidates.length === 0) {
return ok({ return ok({
attendeeId: attendee.id, attendeeId: attendee.id,
fullName: attendee.fullName, fullName: attendee.person.fullName,
groupName: attendee.group.name, groupName: attendee.group.name,
sessions: [], sessions: [],
}); });
@@ -75,7 +76,7 @@ export class GetAbsenceDetails {
return ok({ return ok({
attendeeId: attendee.id, attendeeId: attendee.id,
fullName: attendee.fullName, fullName: attendee.person.fullName,
groupName: attendee.group.name, groupName: attendee.group.name,
sessions: sessions.map((session) => { sessions: sessions.map((session) => {
const attendanceStatus = attendanceBySession.get(session.id) ?? null; const attendanceStatus = attendanceBySession.get(session.id) ?? null;

View File

@@ -7,6 +7,7 @@ import type {
} from '@gruperly/shared'; } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { flattenPerson } from '@/modules/attendees/lib/helpers';
import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler'; import { DEFAULT_TIME_ZONE, startOfDayInTimeZone } from '@/modules/home/lib/scheduler';
import { import {
type ClassesDb, type ClassesDb,
@@ -60,8 +61,9 @@ export class GetSessionStudents {
const [attendees, payments, attendances, releases] = await Promise.all([ const [attendees, payments, attendances, releases] = await Promise.all([
db.attendee.findMany({ db.attendee.findMany({
where: { groupId: session.groupId }, where: { groupId: session.groupId },
orderBy: { fullName: 'asc' }, orderBy: { person: { fullName: 'asc' } },
}), include: { person: { select: { fullName: true } } },
}).then((rows) => rows.map(flattenPerson)),
db.payment.findMany({ db.payment.findMany({
where: { groupId: session.groupId }, where: { groupId: session.groupId },
select: { attendeeId: true, status: true, dueDate: true }, select: { attendeeId: true, status: true, dueDate: true },

View File

@@ -8,6 +8,7 @@ import { err, ok } from '@gruperly/shared';
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
import { default as prisma, UnitOfWork } from '@/lib/prisma'; import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { countsAsNewStudent } from '@/modules/people/lib/people';
import { import {
findGroupOwnedByUser, findGroupOwnedByUser,
type GroupWaitlistEntryRecord, type GroupWaitlistEntryRecord,
@@ -17,7 +18,7 @@ import { promoteWaitlistEntryRecord } from '../../../group-waitlist/lib/promote'
import { type GroupPreRegistrationRecord } from '../../lib/helpers'; import { type GroupPreRegistrationRecord } from '../../lib/helpers';
type ApproveGroupPreRegistrationDeps = { type ApproveGroupPreRegistrationDeps = {
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>; db?: Pick<PrismaClient, 'group' | 'groupPreRegistration' | 'person'>;
unitOfWork?: UnitOfWork; unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>; planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
@@ -53,7 +54,8 @@ export class ApproveGroupPreRegistration {
); );
} }
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId); const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
if (!allowed.ok) { if (!allowed.ok) {
return allowed; return allowed;
} }

View File

@@ -1,19 +1,26 @@
import { type PromoteGroupWaitlistEntry as PromoteBody, PromoteGroupWaitlistEntrySchema } from '@gruperly/shared';
import { Hono } from 'hono'; import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details'; import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { PromoteGroupWaitlistEntry } from './use-case'; import { PromoteGroupWaitlistEntry } from './use-case';
const route = new Hono(); const route = new Hono();
route.post('/:groupId/waitlist/:entryId/promote', async (c) => { route.post(
'/:groupId/waitlist/:entryId/promote',
validate.json(PromoteGroupWaitlistEntrySchema),
async (c) => {
const user = c.get('user'); const user = c.get('user');
if (!user) { if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path)); return problemJson(c, unauthorizedProblem(c.req.path));
} }
const groupId = c.req.param('groupId'); const groupId = c.req.param('groupId');
const entryId = c.req.param('entryId'); const entryId = c.req.param('entryId');
const body = c.req.valid('json') as PromoteBody;
const useCase = new PromoteGroupWaitlistEntry(); const useCase = new PromoteGroupWaitlistEntry();
const result = await useCase.execute(groupId, entryId, user.id); const result = await useCase.execute(groupId, entryId, user.id, body.targetGroupId);
return resultJson(c, result); return resultJson(c, result);
}); },
);
export default route; export default route;

View File

@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import { default as prisma, UnitOfWork } from '@/lib/prisma'; import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { countsAsNewStudent } from '@/modules/people/lib/people';
import { import {
findGroupOwnedByUser, findGroupOwnedByUser,
type GroupWaitlistEntryRecord, type GroupWaitlistEntryRecord,
@@ -11,7 +12,7 @@ import {
import { promoteWaitlistEntryRecord } from '../../lib/promote'; import { promoteWaitlistEntryRecord } from '../../lib/promote';
type PromoteGroupWaitlistEntryDeps = { type PromoteGroupWaitlistEntryDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry' | 'person'>;
unitOfWork?: UnitOfWork; unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>; planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
@@ -23,6 +24,7 @@ export class PromoteGroupWaitlistEntry {
groupId: string, groupId: string,
entryId: string, entryId: string,
userId: string, userId: string,
targetGroupId?: string,
): Promise<Result<PromoteGroupWaitlistEntryResult, ProblemDetails>> { ): Promise<Result<PromoteGroupWaitlistEntryResult, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
@@ -39,7 +41,19 @@ export class PromoteGroupWaitlistEntry {
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId)); return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
} }
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId); // The entry leaves the waitlist of its own group but can land in another
// group of the same teacher (capacity and duplicates are checked there).
let targetGroup = groupResult.value;
if (targetGroupId && targetGroupId !== groupId) {
const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
if (!targetResult.ok) {
return targetResult;
}
targetGroup = targetResult.value;
}
const isNewStudent = await countsAsNewStudent(db, userId, entry.phone);
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId, isNewStudent ? 1 : 0);
if (!allowed.ok) { if (!allowed.ok) {
return allowed; return allowed;
} }
@@ -48,7 +62,7 @@ export class PromoteGroupWaitlistEntry {
async (tx: Prisma.TransactionClient) => { async (tx: Prisma.TransactionClient) => {
const promoteResult = await promoteWaitlistEntryRecord( const promoteResult = await promoteWaitlistEntryRecord(
tx, tx,
groupResult.value, targetGroup,
entry as unknown as GroupWaitlistEntryRecord, entry as unknown as GroupWaitlistEntryRecord,
); );
if (!promoteResult.ok) { if (!promoteResult.ok) {

View File

@@ -1,15 +1,17 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared'; import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared';
import { capacityReachedProblem, conflictProblem } from '@/http/problem-builders'; import { capacityReachedProblem } from '@/http/problem-builders';
import { type AttendeeRecord, toAttendeeDto } from '@/modules/attendees/lib/helpers'; import { attendeeWithPerson, toAttendeeDto } from '@/modules/attendees/lib/helpers';
import { alreadyInGroupProblem, findOrCreatePerson } from '@/modules/people/lib/people';
import { type GroupWaitlistEntryRecord } from './helpers'; import { type GroupWaitlistEntryRecord } from './helpers';
export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry'>; export type PromoteDb = Pick<PrismaClient, 'attendee' | 'groupWaitlistEntry' | 'person'>;
type PromoteGroup = { type PromoteGroup = {
id: string; id: string;
capacity: number | null; capacity: number | null;
createdById: string;
}; };
export async function findFirstPendingWaitlistEntry( export async function findFirstPendingWaitlistEntry(
@@ -23,11 +25,14 @@ export async function findFirstPendingWaitlistEntry(
return record as GroupWaitlistEntryRecord | null; return record as GroupWaitlistEntryRecord | null;
} }
export async function promoteWaitlistEntryRecord( /* Whether someone can join `group`: free capacity (ACTIVE members) and the
db: PromoteDb, person (when there already is one) not being a member there yet. Shared by
group: PromoteGroup, the waitlist promotion, the member move and "Agregar a otro grupo". */
entry: GroupWaitlistEntryRecord, export async function checkCanJoinGroup(
): Promise<Result<AttendeeDto, ProblemDetails>> { db: Pick<PrismaClient, 'attendee'>,
group: Pick<PromoteGroup, 'id' | 'capacity'>,
personId: string | null,
): Promise<Result<void, ProblemDetails>> {
if (group.capacity !== null) { if (group.capacity !== null) {
const currentCount = await db.attendee.count({ const currentCount = await db.attendee.count({
where: { groupId: group.id, status: 'ACTIVE' }, where: { groupId: group.id, status: 'ACTIVE' },
@@ -37,29 +42,44 @@ export async function promoteWaitlistEntryRecord(
} }
} }
if (personId) {
const existing = await db.attendee.findFirst({ const existing = await db.attendee.findFirst({
where: { groupId: group.id, phone: entry.phone }, where: { groupId: group.id, personId },
select: { id: true },
}); });
if (existing) { if (existing) {
return err( return err(alreadyInGroupProblem());
conflictProblem({ }
detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
code: 'attendee_already_registered',
}),
);
} }
const attendee = await db.attendee.create({ return ok(undefined);
data: { }
groupId: group.id,
/* The entry has its own contact data; if its phone is already one of the
teacher's people, the new membership goes to that person. */
export async function promoteWaitlistEntryRecord(
db: PromoteDb,
group: PromoteGroup,
entry: GroupWaitlistEntryRecord,
): Promise<Result<AttendeeDto, ProblemDetails>> {
const person = await findOrCreatePerson(db, group.createdById, {
fullName: entry.fullName, fullName: entry.fullName,
phone: entry.phone, phone: entry.phone,
email: entry.email, email: entry.email,
notes: entry.notes, notes: entry.notes,
},
}); });
return ok(toAttendeeDto(attendee as unknown as AttendeeRecord)); const canJoin = await checkCanJoinGroup(db, group, person.created ? null : person.id);
if (!canJoin.ok) {
return canJoin;
}
const attendee = await db.attendee.create({
data: { groupId: group.id, personId: person.id },
include: attendeeWithPerson,
});
return ok(toAttendeeDto(attendee));
} }
export type PromoteFirstResult = { export type PromoteFirstResult = {

View File

@@ -21,13 +21,15 @@ type ListGroupsDeps = {
now?: Date; now?: Date;
}; };
const OCCUPANCY_COUNT_INCLUDE = { const LIST_COUNT_INCLUDE = {
_count: { _count: {
select: { select: {
// Group members. No status filter, same as the detail page counts. // Group members. No status filter, same as the detail page counts.
attendees: true, attendees: true,
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out). // Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
waitlist: { where: { status: 'PENDING' as const } }, waitlist: { where: { status: 'PENDING' as const } },
// Payments still to collect: the ones pending and the overdue ones.
payments: { where: { status: { in: ['PENDING' as const, 'OVERDUE' as const] } } },
}, },
}, },
} satisfies Prisma.GroupInclude; } satisfies Prisma.GroupInclude;
@@ -49,7 +51,7 @@ export class ListGroups {
// time zone (or the server's if it doesn't come along). // time zone (or the server's if it doesn't come along).
const records: GroupListRecord[] = await db.group.findMany({ const records: GroupListRecord[] = await db.group.findMany({
where, where,
include: OCCUPANCY_COUNT_INCLUDE, include: LIST_COUNT_INCLUDE,
}); });
const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE; const timeZone = query.timeZone ?? DEFAULT_TIME_ZONE;

View File

@@ -26,9 +26,10 @@ export type GroupRecord = {
/* The listing adds the occupancy counters to each group so the card can show /* The listing adds the occupancy counters to each group so the card can show
them without asking for one endpoint per group. They come from the `_count` of them without asking for one endpoint per group. They come from the `_count` of
the same query: all the members (same as the detail page counts) and only the the same query: all the members (same as the detail page counts) and only the
waitlist entries still waiting for a spot (PENDING). */ waitlist entries still waiting for a spot (PENDING), plus the payments still
to collect (PENDING and OVERDUE). */
export type GroupListRecord = GroupRecord & { export type GroupListRecord = GroupRecord & {
_count?: { attendees: number; waitlist: number }; _count?: { attendees: number; waitlist: number; payments?: number };
}; };
export function toGroupDto(record: GroupRecord): GroupDto { export function toGroupDto(record: GroupRecord): GroupDto {
@@ -56,6 +57,7 @@ export function toGroupListItemDto(record: GroupListRecord): GroupListItem {
...toGroupDto(record), ...toGroupDto(record),
attendeesCount: record._count?.attendees ?? 0, attendeesCount: record._count?.attendees ?? 0,
waitlistCount: record._count?.waitlist ?? 0, waitlistCount: record._count?.waitlist ?? 0,
unpaidPaymentsCount: record._count?.payments ?? 0,
}; };
} }

View File

@@ -1,10 +1,12 @@
import { Hono } from 'hono'; import { Hono } from 'hono';
import analyticsRoutes from '../analytics/routes'; import analyticsRoutes from '../analytics/routes';
import addAttendeeToGroupRoute from '../attendees/features/add-to-group/route';
import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route'; import addToGroupWaitlistRoute from '../attendees/features/add-to-waitlist/route';
import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route'; import bulkCreateAttendeesRoute from '../attendees/features/bulk-create/route';
import createAttendeeRoute from '../attendees/features/create/route'; import createAttendeeRoute from '../attendees/features/create/route';
import getAttendeeRoute from '../attendees/features/get-by-id/route'; import getAttendeeRoute from '../attendees/features/get-by-id/route';
import getAttendeeStatsRoute from '../attendees/features/get-stats/route'; import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
import moveAttendeeRoute from '../attendees/features/move/route';
import removeAttendeeRoute from '../attendees/features/remove/route'; import removeAttendeeRoute from '../attendees/features/remove/route';
import updateAttendeeRoute from '../attendees/features/update/route'; import updateAttendeeRoute from '../attendees/features/update/route';
import groupPreRegistrationRoutes from '../group-preregistrations/routes'; import groupPreRegistrationRoutes from '../group-preregistrations/routes';
@@ -37,6 +39,8 @@ routes.route('/', getAttendeeRoute);
routes.route('/', updateAttendeeRoute); routes.route('/', updateAttendeeRoute);
routes.route('/', getAttendeeStatsRoute); routes.route('/', getAttendeeStatsRoute);
routes.route('/', removeAttendeeRoute); routes.route('/', removeAttendeeRoute);
routes.route('/', moveAttendeeRoute);
routes.route('/', addAttendeeToGroupRoute);
routes.route('/', studentAccessRoutes); routes.route('/', studentAccessRoutes);
export default routes; export default routes;

View File

@@ -74,7 +74,7 @@ export class GetHomeSummary {
take: UPCOMING_PAYMENTS_LIMIT, take: UPCOMING_PAYMENTS_LIMIT,
include: { include: {
group: { select: { name: true } }, group: { select: { name: true } },
attendee: { select: { fullName: true } }, attendee: { select: { person: { select: { fullName: true } } } },
}, },
}), }),
]); ]);
@@ -96,7 +96,7 @@ export class GetHomeSummary {
dueDate: payment.dueDate.toISOString(), dueDate: payment.dueDate.toISOString(),
status: payment.status, status: payment.status,
groupName: payment.group.name, groupName: payment.group.name,
attendeeName: payment.attendee.fullName, attendeeName: payment.attendee.person.fullName,
})), })),
pendingPreRegistrations: groups pendingPreRegistrations: groups
.filter((group) => group._count.preRegistrations > 0) .filter((group) => group._count.preRegistrations > 0)

View File

@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders'; import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { normalizePhone } from '@/modules/attendees/lib/helpers'; import { normalizePhone } from '@/modules/attendees/lib/helpers';
import { phoneVariants } from '@/modules/people/lib/people';
type JoinViaInviteDeps = { type JoinViaInviteDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupPreRegistration'>;
@@ -36,10 +37,7 @@ export class JoinViaInvite {
const existing = await db.attendee.findFirst({ const existing = await db.attendee.findFirst({
where: { where: {
groupId: group.id, groupId: group.id,
OR: [ person: { phone: { in: phoneVariants(payload.phone) } },
{ phone },
{ phone: payload.phone.trim() },
],
}, },
}); });
@@ -58,10 +56,7 @@ export class JoinViaInvite {
const existingPreRegistration = await db.groupPreRegistration.findFirst({ const existingPreRegistration = await db.groupPreRegistration.findFirst({
where: { where: {
groupId: group.id, groupId: group.id,
OR: [ phone: { in: phoneVariants(payload.phone) },
{ phone },
{ phone: payload.phone.trim() },
],
}, },
}); });

View File

@@ -19,6 +19,7 @@ import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp'; import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib'; import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
import { CHECKOUT_BACK_PATH } from '../../lib';
type BatchDeps = { type BatchDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
@@ -80,6 +81,7 @@ export class CreatePaymentBatch {
status: 'ACTIVE', status: 'ACTIVE',
...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}), ...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}),
}, },
include: { person: { select: { fullName: true } } },
}); });
if (attendees.length === 0) { if (attendees.length === 0) {
return err(noAttendeesToBillProblem()); return err(noAttendeesToBillProblem());
@@ -95,7 +97,7 @@ export class CreatePaymentBatch {
return token; return token;
} }
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`; const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`;
const dueDate = new Date(input.dueDate); const dueDate = new Date(input.dueDate);
const title = input.description?.trim() || group.name; const title = input.description?.trim() || group.name;
const createPreference = this.deps.createPreference ?? createCheckoutPreference; const createPreference = this.deps.createPreference ?? createCheckoutPreference;
@@ -149,7 +151,7 @@ export class CreatePaymentBatch {
items.push({ items.push({
paymentId: payment.id, paymentId: payment.id,
attendeeId: attendee.id, attendeeId: attendee.id,
attendeeName: attendee.fullName, attendeeName: attendee.person.fullName,
amount: unitPrice, amount: unitPrice,
currency, currency,
checkoutUrl: link?.initPoint ?? null, checkoutUrl: link?.initPoint ?? null,

View File

@@ -36,7 +36,7 @@ export class ListPayments {
where, where,
include: { include: {
group: { select: { name: true, price: true } }, group: { select: { name: true, price: true } },
attendee: { select: { fullName: true } }, attendee: { select: { person: { select: { fullName: true } } } },
}, },
skip: getPaginationOffset(query), skip: getPaginationOffset(query),
take: query.pageSize, take: query.pageSize,

View File

@@ -12,7 +12,7 @@ import { logger } from '@/logger';
import { PlanGuard } from '@/modules/billing/lib/entitlements'; import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { getMpAccessToken } from '@/modules/mp'; import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib'; import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
import { type PaymentRecord, toPaymentDto } from '../../lib'; import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib';
type RenewDeps = { type RenewDeps = {
db?: Pick<PrismaClient, 'payment' | 'user'>; db?: Pick<PrismaClient, 'payment' | 'user'>;
@@ -35,7 +35,7 @@ export class RenewPaymentLink {
const payment = await db.payment.findUnique({ const payment = await db.payment.findUnique({
where: { id: paymentId }, where: { id: paymentId },
include: { include: {
attendee: { select: { fullName: true } }, attendee: { select: { person: { select: { fullName: true } } } },
group: { group: {
select: { select: {
name: true, name: true,
@@ -83,7 +83,7 @@ export class RenewPaymentLink {
return token; return token;
} }
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`; const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`;
const createPreference = this.deps.createPreference ?? createCheckoutPreference; const createPreference = this.deps.createPreference ?? createCheckoutPreference;
let preference: { initPoint: string; id: string }; let preference: { initPoint: string; id: string };
@@ -106,7 +106,7 @@ export class RenewPaymentLink {
where: { id: payment.id }, where: { id: payment.id },
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id }, data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id },
include: { include: {
attendee: { select: { fullName: true } }, attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } }, group: { select: { name: true, price: true } },
}, },
}); });

View File

@@ -26,11 +26,12 @@ const reportSelect = {
createdAt: true, createdAt: true,
totalAmount: true, totalAmount: true,
currency: true, currency: true,
note: true,
receiptKey: true, receiptKey: true,
receiptMime: true, receiptMime: true,
receiptName: true, receiptName: true,
receiptSize: true, receiptSize: true,
attendee: { select: { id: true, fullName: true } }, attendee: { select: { id: true, person: { select: { fullName: true } } } },
group: { select: { id: true, name: true } }, group: { select: { id: true, name: true } },
items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } }, items: { select: { payment: { select: { id: true, description: true, dueDate: true, amount: true } } } },
} satisfies Prisma.ReportedPaymentSelect; } satisfies Prisma.ReportedPaymentSelect;
@@ -201,11 +202,12 @@ export class ReportedPayments {
return { return {
id: row.id, id: row.id,
status: STATUS[row.status], status: STATUS[row.status],
attendee: row.attendee, attendee: { id: row.attendee.id, fullName: row.attendee.person.fullName },
group: row.group, group: row.group,
createdAt: row.createdAt.toISOString(), createdAt: row.createdAt.toISOString(),
totalAmount: row.totalAmount.toNumber(), totalAmount: row.totalAmount.toNumber(),
currency: row.currency, currency: row.currency,
note: row.note,
fees: row.items fees: row.items
.map(({ payment }) => ({ .map(({ payment }) => ({
id: payment.id, id: payment.id,

View File

@@ -1,5 +1,9 @@
import type { PaymentDto } from '@gruperly/shared'; import type { PaymentDto } from '@gruperly/shared';
/* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app
(without a student session it falls through to /access). */
export const CHECKOUT_BACK_PATH = '/student/payments';
export type PaymentRecord = { export type PaymentRecord = {
id: string; id: string;
groupId: string; groupId: string;
@@ -14,7 +18,7 @@ export type PaymentRecord = {
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
group: { name: string; price: unknown }; group: { name: string; price: unknown };
attendee: { fullName: string }; attendee: { person: { fullName: string } };
}; };
export function toPaymentDto(record: PaymentRecord): PaymentDto { export function toPaymentDto(record: PaymentRecord): PaymentDto {
@@ -23,7 +27,7 @@ export function toPaymentDto(record: PaymentRecord): PaymentDto {
groupId: record.groupId, groupId: record.groupId,
groupName: record.group.name, groupName: record.group.name,
attendeeId: record.attendeeId, attendeeId: record.attendeeId,
attendeeName: record.attendee.fullName, attendeeName: record.attendee.person.fullName,
amount: Number(record.amount.toString()), amount: Number(record.amount.toString()),
currency: record.currency, currency: record.currency,
status: record.status, status: record.status,

View File

@@ -1 +1 @@
export { type PaymentRecord, toPaymentDto } from './helpers'; export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';

View File

@@ -0,0 +1,18 @@
import type { PersonLookupQuery } from '@gruperly/shared';
import { PersonLookupQuerySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { LookupPerson } from './use-case';
const route = new Hono();
route.get('/lookup', validate.query(PersonLookupQuerySchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const result = await new LookupPerson().execute(c.req.valid('query') as PersonLookupQuery, user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,24 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { PersonLookupQuery, PersonSummary, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { findPersonSummaryByPhone } from '../../lib/people';
type LookupPersonDeps = {
db?: Pick<PrismaClient, 'group' | 'person'>;
};
/* While the teacher types a phone in the add form: is it someone they already
have? `null` when not. */
export class LookupPerson {
constructor(private readonly deps: LookupPersonDeps = {}) {}
async execute(query: PersonLookupQuery, userId: string): Promise<Result<PersonSummary | null, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const access = await findGroupForUser(db, query.groupId, userId);
if (!access.ok) return access;
return ok(await findPersonSummaryByPhone(db, access.value.createdById, query.phone));
}
}

View File

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

View File

@@ -0,0 +1,142 @@
import { Prisma, type PrismaClient } from '@generated/prisma/client';
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
import { conflictProblem } from '@/http/problem-builders';
import { normalizePhone } from '@/modules/attendees/lib/helpers';
/* A person is the teacher's contact (student, or a guardian's child); their
`attendees` are the memberships in each group. The phone is unique per
teacher (partial index `people_owner_phone_key`), so it is how a new row is
recognized as someone the teacher already has. */
export type PeopleDb = Pick<PrismaClient, 'person'>;
/* Phones are stored normalized, but older rows may keep what was typed. */
export function phoneVariants(rawPhone: string): string[] {
const normalized = normalizePhone(rawPhone);
const trimmed = rawPhone.trim();
return normalized === trimmed ? [normalized] : [normalized, trimmed];
}
export const personMembershipsSelect = {
attendees: {
orderBy: { createdAt: 'asc' },
select: { id: true, groupId: true, status: true, group: { select: { name: true } } },
},
} as const;
type MembershipRow = {
id: string;
groupId: string;
status: PersonMembership['status'];
group: { name: string };
};
export function toMemberships(rows: MembershipRow[]): PersonMembership[] {
return rows.map((row) => ({
attendeeId: row.id,
groupId: row.groupId,
groupName: row.group.name,
status: row.status,
}));
}
export async function findPersonByPhone(db: PeopleDb, ownerId: string, rawPhone: string) {
return db.person.findFirst({
where: { createdById: ownerId, phone: { in: phoneVariants(rawPhone) } },
select: {
id: true,
fullName: true,
email: true,
phone: true,
...personMembershipsSelect,
},
});
}
export async function findPersonSummaryByPhone(
db: PeopleDb,
ownerId: string,
rawPhone: string,
): Promise<PersonSummary | null> {
const person = await findPersonByPhone(db, ownerId, rawPhone);
if (!person) return null;
return {
id: person.id,
fullName: person.fullName,
email: person.email,
phone: person.phone,
groups: toMemberships(person.attendees),
};
}
export type NewPersonData = {
fullName: string;
phone: string | null;
email?: string | null;
notes?: string | null;
};
/* Waitlist promotion, pre-registration approval and bulk import: the row has
its own contact data, and if that phone is already one of the teacher's
people the membership goes to that person (their data wins). */
export async function findOrCreatePerson(
db: PeopleDb,
ownerId: string,
data: NewPersonData,
): Promise<{ id: string; created: boolean }> {
if (data.phone) {
const existing = await findPersonByPhone(db, ownerId, data.phone);
if (existing) return { id: existing.id, created: false };
}
const person = await db.person.create({
data: {
createdById: ownerId,
fullName: data.fullName,
phone: data.phone,
email: data.email ?? null,
notes: data.notes ?? null,
},
select: { id: true },
});
return { id: person.id, created: true };
}
/* Whether adding someone with this phone takes a new student slot of the plan:
no when they are already an active member of another group. */
export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone: string | null): Promise<boolean> {
if (!rawPhone) return true;
const person = await findPersonByPhone(db, ownerId, rawPhone);
return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
}
/* The number the teacher reaches the person on: theirs, or the guardian's. */
export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null {
return person.phone ?? person.guardianPhone;
}
export function isUniqueViolation(error: unknown): boolean {
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
}
export function alreadyInGroupProblem(): ProblemDetails {
return conflictProblem({
detail: 'Esta persona ya es miembro de este grupo.',
code: 'attendee_already_registered',
});
}
/* The phone belongs to someone the teacher already has: the web offers to add
that person (`personId`) instead of creating a duplicate. */
export function personExistsProblem(): ProblemDetails {
return conflictProblem({
detail: 'Ya tenés registrada a una persona con este número de teléfono.',
code: 'person_exists',
});
}
export function personPhoneTakenProblem(): ProblemDetails {
return conflictProblem({
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
code: 'person_phone_taken',
});
}

View File

@@ -0,0 +1,8 @@
import { Hono } from 'hono';
import lookupRoute from './features/lookup/route';
const routes = new Hono();
routes.route('/', lookupRoute);
export default routes;

View File

@@ -7,7 +7,7 @@ import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { computeStudentAccess } from '../../lib/status'; import { computeStudentAccess } from '../../lib/status';
type GetStudentAccessDeps = { type GetStudentAccessDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
now?: Date; now?: Date;
}; };
@@ -23,9 +23,9 @@ export class GetStudentAccess {
const access = await findGroupForUser(db, groupId, userId); const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) return access; if (!access.ok) return access;
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { id: true } }); const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } });
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId)); if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
return ok(await computeStudentAccess(db, attendeeId, this.deps.now ?? new Date())); return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date()));
} }
} }

View File

@@ -4,11 +4,12 @@ import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from
import { notFoundResourceProblem } from '@/http/problem-builders'; import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma, { UnitOfWork } from '@/lib/prisma'; import prisma, { UnitOfWork } from '@/lib/prisma';
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers'; import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
import { contactPhone } from '@/modules/people/lib/people';
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib'; import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
import { computeStudentAccess } from '../../lib/status'; import { computeStudentAccess } from '../../lib/status';
type InviteStudentDeps = { type InviteStudentDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountAttendee'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'studentAccountPerson'>;
unitOfWork?: Pick<UnitOfWork, 'executeResult'>; unitOfWork?: Pick<UnitOfWork, 'executeResult'>;
now?: Date; now?: Date;
}; };
@@ -36,9 +37,8 @@ export class InviteStudent {
where: { id: attendeeId, groupId }, where: { id: attendeeId, groupId },
select: { select: {
id: true, id: true,
fullName: true, personId: true,
phone: true, person: { select: { fullName: true, phone: true, guardianPhone: true } },
guardianPhone: true,
group: { select: { owner: { select: { country: true } } } }, group: { select: { owner: { select: { country: true } } } },
}, },
}); });
@@ -49,8 +49,9 @@ export class InviteStudent {
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
const issued = await unitOfWork.executeResult(async (tx) => { const issued = await unitOfWork.executeResult(async (tx) => {
const link = await tx.studentAccountAttendee.findFirst({ // One account per person: inviting from any of their groups reuses it.
where: { attendeeId }, const link = await tx.studentAccountPerson.findFirst({
where: { personId: attendee.personId },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
select: { accountId: true }, select: { accountId: true },
}); });
@@ -58,7 +59,11 @@ export class InviteStudent {
link?.accountId link?.accountId
?? ( ?? (
await tx.studentAccount.create({ await tx.studentAccount.create({
data: { name: attendee.fullName, createdById: userId, attendees: { create: { attendeeId } } }, data: {
name: attendee.person.fullName,
createdById: userId,
people: { create: { personId: attendee.personId } },
},
select: { id: true }, select: { id: true },
}) })
).id; ).id;
@@ -90,8 +95,8 @@ export class InviteStudent {
return ok({ return ok({
url: studentLinkUrl(token), url: studentLinkUrl(token),
expiresAt: expiresAt.toISOString(), expiresAt: expiresAt.toISOString(),
whatsappPhone: toWhatsappPhone(attendee.phone ?? attendee.guardianPhone, attendee.group.owner.country), whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
access: await computeStudentAccess(db, attendeeId, now), access: await computeStudentAccess(db, attendee.personId, now),
}); });
} }
} }

View File

@@ -39,7 +39,7 @@ export class ListGroupAbsenceNotices {
reason: true, reason: true,
message: true, message: true,
createdAt: true, createdAt: true,
attendee: { select: { id: true, fullName: true } }, attendee: { select: { id: true, person: { select: { fullName: true } } } },
classSession: { select: { startsAt: true } }, classSession: { select: { startsAt: true } },
}, },
}); });
@@ -47,7 +47,7 @@ export class ListGroupAbsenceNotices {
return ok({ return ok({
data: notices.map((notice) => ({ data: notices.map((notice) => ({
id: notice.id, id: notice.id,
attendee: notice.attendee, attendee: { id: notice.attendee.id, fullName: notice.attendee.person.fullName },
startsAt: notice.classSession.startsAt.toISOString(), startsAt: notice.classSession.startsAt.toISOString(),
reason: notice.reason ? REASON[notice.reason] : null, reason: notice.reason ? REASON[notice.reason] : null,
message: notice.message, message: notice.message,

View File

@@ -1,17 +1,18 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { StudentAccessDto } from '@gruperly/shared'; import type { StudentAccessDto } from '@gruperly/shared';
export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountAttendee'>; export type StudentAccessStatusDb = Pick<PrismaClient, 'studentAccountPerson'>;
/* Passive state for the attendee's card: active (a live session) > invited /* Passive state for the attendee's card: active (a live session) > invited
(a pending invitation) > expired (invited before, nothing alive) > not invited. */ (a pending invitation) > expired (invited before, nothing alive) > not invited.
It is the person's access, so every group of theirs shows the same state. */
export async function computeStudentAccess( export async function computeStudentAccess(
db: StudentAccessStatusDb, db: StudentAccessStatusDb,
attendeeId: string, personId: string,
now: Date, now: Date,
): Promise<StudentAccessDto> { ): Promise<StudentAccessDto> {
const link = await db.studentAccountAttendee.findFirst({ const link = await db.studentAccountPerson.findFirst({
where: { attendeeId }, where: { personId },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
select: { select: {
account: { account: {

View File

@@ -127,7 +127,7 @@ export class CancelStudentAbsence {
where: { where: {
id: noticeId, id: noticeId,
cancelledAt: null, cancelledAt: null,
attendee: { status: { not: 'DROPPED' }, studentAccounts: { some: { accountId } } }, attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } },
}, },
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } }, select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
}); });

View File

@@ -17,7 +17,7 @@ route.get('/fees', studentSession, validate.query(StudentAttendeeQuerySchema), a
return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId)); return resultJson(c, await new GetStudentFees().execute(accountId, attendeeId));
}); });
// multipart/form-data: attendeeId, paymentIds (repeated) and file. // multipart/form-data: attendeeId, paymentIds (repeated), file and an optional note.
route.post('/payment-reports', studentSession, async (c) => { route.post('/payment-reports', studentSession, async (c) => {
const { accountId } = currentStudent(c); const { accountId } = currentStudent(c);
// Reject oversized bodies before buffering them (10 MB + room for the fields). // Reject oversized bodies before buffering them (10 MB + room for the fields).
@@ -35,6 +35,7 @@ route.post('/payment-reports', studentSession, async (c) => {
const attendeeId = form.get('attendeeId'); const attendeeId = form.get('attendeeId');
const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0); const paymentIds = form.getAll('paymentIds').filter((value): value is string => typeof value === 'string' && value.length > 0);
const file = form.get('file'); const file = form.get('file');
const note = form.get('note');
if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) { if (typeof attendeeId !== 'string' || paymentIds.length === 0 || !(file instanceof File)) {
return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' })); return problemJson(c, validationProblem({ detail: 'Elegí al menos una cuota y adjuntá el comprobante.' }));
} }
@@ -42,6 +43,7 @@ route.post('/payment-reports', studentSession, async (c) => {
const result = await new ReportStudentPayment().execute(accountId, { const result = await new ReportStudentPayment().execute(accountId, {
attendeeId, attendeeId,
paymentIds, paymentIds,
note: typeof note === 'string' ? note : null,
file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) }, file: { name: file.name, bytes: new Uint8Array(await file.arrayBuffer()) },
}); });
return resultJson(c, result, { status: 201 }); return resultJson(c, result, { status: 201 });

View File

@@ -54,6 +54,7 @@ export class GetStudentFees {
status: true, status: true,
createdAt: true, createdAt: true,
reviewedAt: true, reviewedAt: true,
note: true,
rejectionReason: true, rejectionReason: true,
items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } }, items: { select: { payment: { select: { id: true, description: true, dueDate: true } } } },
}, },
@@ -85,6 +86,7 @@ export class GetStudentFees {
status: REPORT_STATUS[report.status], status: REPORT_STATUS[report.status],
createdAt: report.createdAt.toISOString(), createdAt: report.createdAt.toISOString(),
reviewedAt: report.reviewedAt?.toISOString() ?? null, reviewedAt: report.reviewedAt?.toISOString() ?? null,
note: report.note,
rejectionReason: report.rejectionReason, rejectionReason: report.rejectionReason,
fees: report.items.map(({ payment }) => ({ fees: report.items.map(({ payment }) => ({
id: payment.id, id: payment.id,

View File

@@ -32,10 +32,20 @@ export class GetStudentLinkInfo {
account: { account: {
select: { select: {
name: true, name: true,
people: {
orderBy: { createdAt: 'asc' },
take: 1,
select: {
person: {
select: {
attendees: { attendees: {
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
take: 1, take: 1,
select: { attendee: { select: { group: { select: { name: true, owner: { select: { name: true } } } } } } }, select: { group: { select: { name: true, owner: { select: { name: true } } } } },
},
},
},
},
}, },
}, },
}, },
@@ -52,7 +62,7 @@ export class GetStudentLinkInfo {
return ok({ status: 'invalid' }); return ok({ status: 'invalid' });
} }
const group = row.account.attendees[0]?.attendee.group ?? null; const group = row.account.people[0]?.person.attendees[0]?.group ?? null;
return ok({ return ok({
status: 'valid', status: 'valid',
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery', kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',

View File

@@ -20,20 +20,26 @@ export class GetStudentMe {
pendingRecoveryEmail: true, pendingRecoveryEmail: true,
welcomedAt: true, welcomedAt: true,
_count: { select: { passkeys: true } }, _count: { select: { passkeys: true } },
attendees: { // Linked people, and every group each of them is in.
where: { attendee: { status: { not: 'DROPPED' } } }, people: {
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
select: { select: {
attendee: { person: {
select: {
fullName: true,
attendees: {
where: { status: { not: 'DROPPED' } },
orderBy: { createdAt: 'asc' },
select: { select: {
id: true, id: true,
fullName: true,
group: { select: { id: true, name: true, owner: { select: { name: true } } } }, group: { select: { id: true, name: true, owner: { select: { name: true } } } },
}, },
}, },
}, },
}, },
}, },
},
},
}); });
if (!account) return err(unauthorizedProblem('/student-portal/me')); if (!account) return err(unauthorizedProblem('/student-portal/me'));
@@ -46,13 +52,15 @@ export class GetStudentMe {
hasPasskey: account._count.passkeys > 0, hasPasskey: account._count.passkeys > 0,
welcomed: account.welcomedAt !== null, welcomed: account.welcomedAt !== null,
}, },
students: account.attendees.map(({ attendee }) => ({ students: account.people.flatMap(({ person }) =>
person.attendees.map((attendee) => ({
attendeeId: attendee.id, attendeeId: attendee.id,
fullName: attendee.fullName, fullName: person.fullName,
groupId: attendee.group.id, groupId: attendee.group.id,
groupName: attendee.group.name, groupName: attendee.group.name,
teacherName: attendee.group.owner.name, teacherName: attendee.group.owner.name,
})), })),
),
}); });
} }
} }

View File

@@ -1,7 +1,7 @@
import { randomBytes } from 'node:crypto'; import { randomBytes } from 'node:crypto';
import { Prisma, type PrismaClient } from '@generated/prisma/client'; import { Prisma, type PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared'; import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { err, ok, REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared';
import { conflictProblem, validationProblem } from '@/http/problem-builders'; import { conflictProblem, validationProblem } from '@/http/problem-builders';
import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type'; import { detectReceiptType, RECEIPT_EXTENSIONS, RECEIPT_MAX_BYTES } from '@/lib/file-type';
import prisma, { UnitOfWork } from '@/lib/prisma'; import prisma, { UnitOfWork } from '@/lib/prisma';
@@ -19,6 +19,7 @@ type ReportPaymentDeps = {
export type ReportPaymentInput = { export type ReportPaymentInput = {
attendeeId: string; attendeeId: string;
paymentIds: string[]; paymentIds: string[];
note?: string | null;
file: { name: string; bytes: Uint8Array }; file: { name: string; bytes: Uint8Array };
}; };
@@ -37,6 +38,11 @@ export class ReportStudentPayment {
const attendee = await findLinkedAttendee(db, accountId, input.attendeeId); const attendee = await findLinkedAttendee(db, accountId, input.attendeeId);
if (!attendee) return err(studentAttendeeNotFoundProblem()); if (!attendee) return err(studentAttendeeNotFoundProblem());
const note = input.note?.trim() || null;
if (note && note.length > REPORTED_PAYMENT_NOTE_MAX) {
return err(validationProblem({ detail: `La nota puede tener hasta ${REPORTED_PAYMENT_NOTE_MAX} caracteres.`, errors: { note: ['too_long'] } }));
}
if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) { if (input.file.bytes.length === 0 || input.file.bytes.length > RECEIPT_MAX_BYTES) {
return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } })); return err(validationProblem({ detail: 'El comprobante tiene que pesar hasta 10 MB.', errors: { file: ['too_large'] } }));
} }
@@ -83,6 +89,7 @@ export class ReportStudentPayment {
receiptMime: mime, receiptMime: mime,
receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`, receiptName: input.file.name.slice(0, 200) || `comprobante.${RECEIPT_EXTENSIONS[mime]}`,
receiptSize: input.file.bytes.length, receiptSize: input.file.bytes.length,
note,
createdAt: now, createdAt: now,
items: { create: paymentIds.map((paymentId) => ({ paymentId })) }, items: { create: paymentIds.map((paymentId) => ({ paymentId })) },
}, },

View File

@@ -75,7 +75,7 @@ export class SetRecoveryEmail {
await sender.sendStudentEmailConfirmation({ await sender.sendStudentEmailConfirmation({
email, email,
name: account.name, name: account.name,
url: `${webUrl()}/acceso/mail/${token}`, url: `${webUrl()}/access/email/${token}`,
}); });
} catch (error) { } catch (error) {
logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent'); logger.error({ error, accountId }, 'Student recovery email confirmation could not be sent');

View File

@@ -1,36 +1,21 @@
import type { Prisma } from '@generated/prisma/client'; import type { Prisma } from '@generated/prisma/client';
export type StudentAccessDb = {
studentAccountAttendee: Prisma.StudentAccountAttendeeDelegate;
};
/* The authorization rule of every student endpoint: only the attendees linked
to the session's account. Anything else is a 404 (we don't confirm ids). */
export async function linkedAttendeeIds(db: StudentAccessDb, accountId: string): Promise<string[]> {
const links = await db.studentAccountAttendee.findMany({
// A DROPPED attendee loses access; a PAUSED one keeps it.
where: { accountId, attendee: { status: { not: 'DROPPED' } } },
select: { attendeeId: true },
orderBy: { createdAt: 'asc' },
});
return links.map((link) => link.attendeeId);
}
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate }; export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
/* One attendee of the session, with what the student screens need from the /* The authorization rule of every student endpoint: an attendee (membership)
group. null for an attendee not linked to the account (or DROPPED): routes of a person linked to the session's account, with what the student screens
answer 404, the same as for an id that doesn't exist. */ need from the group. The account is linked to the person, so every group
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
access): routes answer 404, the same as for an id that doesn't exist. */
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) { export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
return db.attendee.findFirst({ return db.attendee.findFirst({
where: { where: {
id: attendeeId, id: attendeeId,
status: { not: 'DROPPED' }, status: { not: 'DROPPED' },
studentAccounts: { some: { accountId } }, person: { studentAccounts: { some: { accountId } } },
}, },
select: { select: {
id: true, id: true,
fullName: true,
groupId: true, groupId: true,
group: { group: {
select: { select: {

View File

@@ -1,6 +1,7 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { contactPhone } from '@/modules/people/lib/people';
import { import {
addTotals, addTotals,
type DispatchItem, type DispatchItem,
@@ -69,7 +70,9 @@ export class SendPaymentReminders {
currency: true, currency: true,
dueDate: true, dueDate: true,
checkoutUrl: true, checkoutUrl: true,
attendee: { select: { id: true, fullName: true, phone: true, guardianPhone: true } }, attendee: {
select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } },
},
}, },
orderBy: { dueDate: 'asc' }, orderBy: { dueDate: 'asc' },
}); });
@@ -82,10 +85,10 @@ export class SendPaymentReminders {
groupId: group.id, groupId: group.id,
attendeeId: payment.attendee.id, attendeeId: payment.attendee.id,
paymentId: payment.id, paymentId: payment.id,
rawPhone: payment.attendee.phone ?? payment.attendee.guardianPhone, rawPhone: contactPhone(payment.attendee.person),
message: { message: {
kind: 'PAYMENT_REMINDER', kind: 'PAYMENT_REMINDER',
studentName: payment.attendee.fullName, studentName: payment.attendee.person.fullName,
groupName: group.name, groupName: group.name,
amount: formatAmount(Number(payment.amount.toString()), payment.currency, country), amount: formatAmount(Number(payment.amount.toString()), payment.currency, country),
dueDate: formatDueDate(payment.dueDate, country), dueDate: formatDueDate(payment.dueDate, country),

View File

@@ -5,6 +5,7 @@ import {
findStudentsAtRisk, findStudentsAtRisk,
type StudentsAtRiskDb, type StudentsAtRiskDb,
} from '@/modules/analytics/features/get-students-at-risk/use-case'; } from '@/modules/analytics/features/get-students-at-risk/use-case';
import { contactPhone } from '@/modules/people/lib/people';
import { import {
addTotals, addTotals,
type DispatchItem, type DispatchItem,
@@ -69,11 +70,11 @@ export class SendReengagementMessages {
}), }),
db.attendee.findMany({ db.attendee.findMany({
where: { id: { in: ids } }, where: { id: { in: ids } },
select: { id: true, phone: true, guardianPhone: true }, select: { id: true, person: { select: { phone: true, guardianPhone: true } } },
}), }),
]); ]);
const coolingDown = new Set(recent.map((row) => row.attendeeId)); const coolingDown = new Set(recent.map((row) => row.attendeeId));
const phones = new Map(contacts.map((row) => [row.id, row.phone ?? row.guardianPhone])); const phones = new Map(contacts.map((row) => [row.id, contactPhone(row.person)]));
for (const student of atRisk) { for (const student of atRisk) {
if (coolingDown.has(student.attendeeId)) continue; if (coolingDown.has(student.attendeeId)) continue;

View File

@@ -0,0 +1,175 @@
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(),
update: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
},
}));
import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups';
const teacherId = 'teacher-1';
const group = (overrides: Record<string, unknown> = {}) => ({
id: 'group-1',
name: 'Taller de Pintura',
createdById: teacherId,
capacity: 20,
...overrides,
});
const targetGroup = (overrides: Record<string, unknown> = {}) =>
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
const person = {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
};
const membership = (overrides: Record<string, unknown> = {}) => ({
id: 'att-2',
groupId: 'group-2',
personId: 'person-1',
person,
notifyToken: 'notify-2',
status: 'ACTIVE',
createdAt: new Date('2026-11-02T10:00:00.000Z'),
updatedAt: new Date('2026-11-02T10:00:00.000Z'),
...overrides,
});
function addRequest(targetGroupId: string, userId = teacherId) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', { id: userId } as never);
await next();
});
app.route('/groups', groupsRoutes);
return app.request('/groups/group-1/attendees/att-1/add-to-group', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
}
describe('POST /groups/:groupId/attendees/:attendeeId/add-to-group', () => {
beforeEach(() => {
vi.clearAllMocks();
prisma.group.findUnique.mockReset();
prisma.attendee.findFirst.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
prisma.attendee.count.mockResolvedValue(3);
});
it('creates a membership of the same person in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce(null);
prisma.attendee.create.mockResolvedValue(membership() as never);
const res = await addRequest('group-2');
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({
id: 'att-2',
groupId: 'group-2',
personId: 'person-1',
fullName: 'Martín Gómez',
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-2', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
// The source membership is not touched.
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('reactivates a former (DROPPED) membership in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce({ id: 'att-old', status: 'DROPPED' } as never);
prisma.attendee.update.mockResolvedValue(membership({ id: 'att-old' }) as never);
const res = await addRequest('group-2');
expect(res.status).toBe(200);
expect(prisma.attendee.update).toHaveBeenCalledWith({
where: { id: 'att-old' },
data: { status: 'ACTIVE' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the person is already in the target group', async () => {
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce({ id: 'att-2', status: 'PAUSED' } as never);
const res = await addRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_already_registered');
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ capacity: 3 }) as never);
prisma.attendee.findFirst
.mockResolvedValueOnce({ personId: 'person-1' } as never)
.mockResolvedValueOnce(null);
const res = await addRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('group_capacity_reached');
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects adding to the same group', async () => {
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
const res = await addRequest('group-1');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_same_group');
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique.mockReset();
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never);
prisma.attendee.findFirst.mockResolvedValueOnce({ personId: 'person-1' } as never);
const res = await addRequest('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
});

View File

@@ -38,12 +38,21 @@ function makeGroup(overrides: Record<string, unknown> = {}) {
const attendee = { const attendee = {
id: 'a-1', id: 'a-1',
groupId: 'group-1', groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: 'ana@example.com', email: 'ana@example.com',
phone: '5512345678', phone: '5512345678',
guardianName: 'Luis Pérez', guardianName: 'Luis Pérez',
guardianPhone: null, guardianPhone: null,
notes: null, notes: null,
// Every membership of the person: this one and another group.
attendees: [
{ id: 'a-1', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Funcional' } },
{ id: 'a-2', groupId: 'group-2', status: 'PAUSED', group: { name: 'Yoga' } },
],
},
notifyToken: 'token-1', notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'), createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -67,6 +76,7 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
expect(await res.json()).toEqual({ expect(await res.json()).toEqual({
id: 'a-1', id: 'a-1',
groupId: 'group-1', groupId: 'group-1',
personId: 'person-1',
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: 'ana@example.com', email: 'ana@example.com',
phone: '5512345678', phone: '5512345678',
@@ -77,10 +87,12 @@ describe('GET /groups/:groupId/attendees/:attendeeId', () => {
createdAt: '2026-08-01T10:00:00.000Z', createdAt: '2026-08-01T10:00:00.000Z',
updatedAt: '2026-08-01T10:00:00.000Z', updatedAt: '2026-08-01T10:00:00.000Z',
payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' }, payment: { status: 'PENDING', dueDate: '2026-10-10T00:00:00.000Z' },
otherGroups: [{ attendeeId: 'a-2', groupId: 'group-2', groupName: 'Yoga', status: 'PAUSED' }],
}); });
expect(prisma.attendee.findFirst).toHaveBeenCalledWith({ expect(prisma.attendee.findFirst).toHaveBeenCalledWith({
where: { id: 'a-1', groupId: 'group-1' }, where: { id: 'a-1', groupId: 'group-1' },
include: { include: {
person: { select: expect.objectContaining({ fullName: true, attendees: expect.any(Object) }) },
payments: { payments: {
where: { where: {
status: { not: 'CANCELLED' }, status: { not: 'CANCELLED' },

View File

@@ -0,0 +1,220 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
group: {
findUnique: mock(),
},
attendee: {
findFirst: mock(),
count: mock(),
update: mock(),
},
absenceNotice: {
updateMany: mock(),
},
attendance: {
deleteMany: mock(),
},
slotRelease: {
deleteMany: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {
executeResult = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
execute = mock(async (cb: (tx: unknown) => Promise<unknown>) => cb(db));
},
}));
import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups';
const teacherId = 'teacher-1';
const group = (overrides: Record<string, unknown> = {}) => ({
id: 'group-1',
name: 'Taller de Pintura',
description: null,
createdById: teacherId,
inviteToken: null,
createdAt: new Date('2026-09-01T10:00:00.000Z'),
updatedAt: new Date('2026-09-01T10:00:00.000Z'),
days: ['MONDAY'],
time: '18:00',
capacity: 20,
price: 1500,
billingType: 'MONTHLY',
dueDay: 10,
...overrides,
});
const targetGroup = (overrides: Record<string, unknown> = {}) =>
group({ id: 'group-2', name: 'Taller de Cerámica', ...overrides });
const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez',
phone: '+5491133445566',
email: null,
guardianName: null,
guardianPhone: null,
notes: null,
},
notifyToken: 'notify-1',
status: 'ACTIVE',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
});
function moveRequest(targetGroupId: string, userId = teacherId, attendeeId = 'att-1') {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', { id: userId } as never);
await next();
});
app.route('/groups', groupsRoutes);
return app.request(`/groups/group-1/attendees/${attendeeId}/move`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
}
describe('POST /groups/:groupId/attendees/:attendeeId/move', () => {
beforeEach(() => {
vi.clearAllMocks();
prisma.group.findUnique.mockReset();
});
it('moves the member to the target group and undoes the old group future bookings', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
prisma.attendee.findFirst.mockResolvedValueOnce(attendee() as never).mockResolvedValueOnce(null);
prisma.attendee.count.mockResolvedValue(3);
prisma.attendee.update.mockResolvedValue(attendee({ groupId: 'group-2' }) as never);
const res = await moveRequest('group-2');
expect(res.status).toBe(200);
const body = await res.json();
expect(body.groupId).toBe('group-2');
expect(prisma.attendee.update).toHaveBeenCalledWith({
where: { id: 'att-1' },
data: { groupId: 'group-2' },
include: { person: { select: expect.any(Object) } },
});
const futureOldClasses = {
classSession: { groupId: 'group-1', startsAt: { gt: expect.any(Date) } },
};
expect(prisma.absenceNotice.updateMany).toHaveBeenCalledWith({
where: { attendeeId: 'att-1', cancelledAt: null, ...futureOldClasses },
data: { cancelledAt: expect.any(Date) },
});
expect(prisma.attendance.deleteMany).toHaveBeenCalledWith({
where: { attendeeId: 'att-1', ...futureOldClasses },
});
expect(prisma.slotRelease.deleteMany).toHaveBeenCalledWith({
where: { attendeeId: 'att-1', isClaimed: false, ...futureOldClasses },
});
});
it('rejects moving to the same group', async () => {
prisma.group.findUnique.mockResolvedValue(group() as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await moveRequest('group-1');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_same_group');
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ createdById: 'other-user' }) as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await moveRequest('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('returns 404 when the target group does not exist', async () => {
prisma.group.findUnique.mockResolvedValueOnce(group() as never).mockResolvedValueOnce(null);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await moveRequest('group-missing');
expect(res.status).toBe(404);
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup({ capacity: 5 }) as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
prisma.attendee.count.mockResolvedValue(5);
const res = await moveRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('group_capacity_reached');
expect(prisma.attendee.update).not.toHaveBeenCalled();
expect(prisma.absenceNotice.updateMany).not.toHaveBeenCalled();
});
it('rejects with 409 when the person is already a member of the target group', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(group() as never)
.mockResolvedValueOnce(targetGroup() as never);
prisma.attendee.findFirst
.mockResolvedValueOnce(attendee() as never)
.mockResolvedValueOnce({ id: 'att-existing' } as never);
prisma.attendee.count.mockResolvedValue(3);
const res = await moveRequest('group-2');
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('attendee_already_registered');
expect(prisma.attendee.findFirst).toHaveBeenLastCalledWith({
where: { groupId: 'group-2', personId: 'person-1' },
select: { id: true },
});
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('returns 404 when the member is not in the group', async () => {
prisma.group.findUnique.mockResolvedValue(group() as never);
prisma.attendee.findFirst.mockResolvedValue(null);
const res = await moveRequest('group-2', teacherId, 'att-missing');
expect(res.status).toBe(404);
});
it('rejects a non-owner user', async () => {
prisma.group.findUnique.mockResolvedValue(group() as never);
const res = await moveRequest('group-2', 'other-user');
expect(res.status).toBe(403);
expect(prisma.attendee.update).not.toHaveBeenCalled();
});
it('returns 400 without a target group', async () => {
const res = await moveRequest('');
expect(res.status).toBe(400);
});
});

View File

@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test' import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'
import { Prisma } from '@generated/prisma/client'
import { Hono } from 'hono' import { Hono } from 'hono'
const db = { const db = {
group: { findUnique: mock() }, group: { findUnique: mock() },
attendee: { findFirst: mock(), update: mock() }, attendee: { findFirst: mock(), findUniqueOrThrow: mock() },
person: { update: mock() },
} }
mock.module('@/lib/prisma', () => ({ mock.module('@/lib/prisma', () => ({
@@ -15,15 +17,20 @@ mock.module('@/lib/prisma', () => ({
import updateAttendeeRoute from '@/modules/attendees/features/update/route' import updateAttendeeRoute from '@/modules/attendees/features/update/route'
const userId = 'user-1' const userId = 'user-1'
const attendee = { const person = {
id: 'a-1', id: 'person-1',
groupId: 'group-1',
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: null, email: null,
phone: null, phone: null,
guardianName: null, guardianName: null,
guardianPhone: null, guardianPhone: null,
notes: 'Llega temprano', notes: 'Llega temprano',
}
const attendee = {
id: 'a-1',
groupId: 'group-1',
personId: 'person-1',
person,
notifyToken: 'token-1', notifyToken: 'token-1',
createdAt: new Date('2026-08-01T10:00:00.000Z'), createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T12:00:00.000Z'), updatedAt: new Date('2026-10-01T12:00:00.000Z'),
@@ -51,11 +58,10 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
db.attendee.findFirst.mockResolvedValue(attendee) db.attendee.findFirst.mockResolvedValue(attendee)
}) })
it('actualiza contacto y conserva los campos vacíos como null', async () => { it('actualiza el contacto de la persona y conserva los campos vacíos como null', async () => {
db.attendee.update.mockResolvedValue({ db.attendee.findUniqueOrThrow.mockResolvedValue({
...attendee, ...attendee,
email: 'ana@example.com', person: { ...person, email: 'ana@example.com' },
phone: null,
}) })
const response = await makeApp().request('/groups/group-1/attendees/a-1', { const response = await makeApp().request('/groups/group-1/attendees/a-1', {
@@ -65,14 +71,49 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
}) })
expect(response.status).toBe(200) expect(response.status).toBe(200)
expect(db.attendee.update).toHaveBeenCalledWith({ expect(await response.json()).toMatchObject({ id: 'a-1', personId: 'person-1', email: 'ana@example.com' })
where: { id: 'a-1' }, // The person's row: the change shows in every group they are in.
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { email: 'ana@example.com', phone: null }, data: { email: 'ana@example.com', phone: null },
}) })
}) })
it('normaliza el teléfono como el alta', async () => {
db.attendee.findUniqueOrThrow.mockResolvedValue(attendee)
await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '11 2345-6789' }),
})
expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'person-1' },
data: { phone: '1123456789' },
})
})
it('devuelve 409 si el teléfono ya es de otra persona del profe', async () => {
db.person.update.mockRejectedValueOnce(
new Prisma.PrismaClientKnownRequestError('Unique constraint failed', {
code: 'P2002',
clientVersion: 'test',
}),
)
const response = await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ phone: '1123456789' }),
})
expect(response.status).toBe(409)
expect(await response.json()).toMatchObject({ code: 'person_phone_taken' })
})
it('actualiza una única nota', async () => { it('actualiza una única nota', async () => {
db.attendee.update.mockResolvedValue({ ...attendee, notes: 'Traer colchoneta' }) db.attendee.findUniqueOrThrow.mockResolvedValue({ ...attendee, person: { ...person, notes: 'Traer colchoneta' } })
await makeApp().request('/groups/group-1/attendees/a-1', { await makeApp().request('/groups/group-1/attendees/a-1', {
method: 'PATCH', method: 'PATCH',
@@ -80,8 +121,8 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
body: JSON.stringify({ notes: 'Traer colchoneta' }), body: JSON.stringify({ notes: 'Traer colchoneta' }),
}) })
expect(db.attendee.update).toHaveBeenCalledWith({ expect(db.person.update).toHaveBeenCalledWith({
where: { id: 'a-1' }, where: { id: 'person-1' },
data: { notes: 'Traer colchoneta' }, data: { notes: 'Traer colchoneta' },
}) })
}) })
@@ -94,6 +135,6 @@ describe('PATCH /groups/:groupId/attendees/:attendeeId', () => {
}) })
expect(response.status).toBe(400) expect(response.status).toBe(400)
expect(db.attendee.update).not.toHaveBeenCalled() expect(db.person.update).not.toHaveBeenCalled()
}) })
}) })

View File

@@ -15,6 +15,10 @@ const db = {
create: mock(), create: mock(),
count: mock(), count: mock(),
}, },
person: {
findFirst: mock(),
findMany: mock(),
},
groupWaitlistEntry: { groupWaitlistEntry: {
findMany: mock(), findMany: mock(),
findFirst: mock(), findFirst: mock(),
@@ -60,9 +64,34 @@ function makeApp(userValue: unknown) {
return app; return app;
} }
const personRow = (overrides: Record<string, unknown> = {}) => ({
id: 'person-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
...overrides,
});
const attendeeRow = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1',
groupId: 'group-1',
personId: 'person-1',
person: personRow(),
notifyToken: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
...overrides,
});
describe('attendee incorporation & invite-token in groups', () => { describe('attendee incorporation & invite-token in groups', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
// Nobody with that phone among the teacher's people, unless a test says so.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.findMany.mockResolvedValue([]);
}); });
describe('GET /groups/:groupId/invite-token', () => { describe('GET /groups/:groupId/invite-token', () => {
@@ -109,18 +138,7 @@ describe('attendee incorporation & invite-token in groups', () => {
it('creates an attendee for the group', async () => { it('creates an attendee for the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never); prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null); prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.create.mockResolvedValue({ prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
email: 'martin@example.com',
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: 'Viene con su hermano',
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
const app = makeApp({ id: teacherId }); const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', { const res = await app.request('/groups/group-1/attendees', {
@@ -140,20 +158,95 @@ describe('attendee incorporation & invite-token in groups', () => {
expect(data.outcome).toBe('created'); expect(data.outcome).toBe('created');
expect(data.attendee.fullName).toBe('Martín Gómez'); expect(data.attendee.fullName).toBe('Martín Gómez');
expect(data.attendee.phone).toBe('+5491133445566'); expect(data.attendee.phone).toBe('+5491133445566');
expect(data.attendee.personId).toBe('person-1');
// A new person of the group owner, created with the membership.
expect(prisma.attendee.create).toHaveBeenCalledWith({ expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { data: {
groupId: 'group-1', group: { connect: { id: 'group-1' } },
person: {
create: {
createdById: teacherId,
fullName: 'Martín Gómez', fullName: 'Martín Gómez',
phone: '+5491133445566', phone: '+5491133445566',
email: 'martin@example.com', email: 'martin@example.com',
notes: 'Viene con su hermano', notes: 'Viene con su hermano',
}, },
},
},
include: { person: { select: expect.any(Object) } },
}); });
}); });
it('answers person_exists when the phone is already a person of another group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue({
...personRow(),
attendees: [{ id: 'att-9', groupId: 'group-9', status: 'ACTIVE', group: { name: 'Yoga' } }],
} as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'Martín', lastName: 'Gómez', phone: '+54 9 11 3344-5566' }),
});
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('person_exists');
expect(prisma.person.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: { createdById: teacherId, phone: { in: ['+5491133445566', '+54 9 11 3344-5566'] } },
}),
);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('adds an existing person (personId) to the group without a new plan slot', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue({ id: 'person-1', fullName: 'Martín Gómez' } as never);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(1);
prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-1' }),
});
expect(res.status).toBe(201);
expect(prisma.person.findFirst).toHaveBeenCalledWith({
where: { id: 'person-1', createdById: teacherId },
select: { id: true, fullName: true },
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { group: { connect: { id: 'group-1' } }, person: { connect: { id: 'person-1' } } },
include: { person: { select: expect.any(Object) } },
});
});
it('returns 404 for a personId of another teacher', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.person.findFirst.mockResolvedValue(null);
const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ firstName: 'x', phone: '1133445566', personId: 'person-other' }),
});
expect(res.status).toBe(404);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects duplicate phone number in individual add', async () => { it('rejects duplicate phone number in individual add', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never); prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never); prisma.person.findFirst.mockResolvedValue({
...personRow(),
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
const app = makeApp({ id: teacherId }); const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees', { const res = await app.request('/groups/group-1/attendees', {
@@ -197,18 +290,7 @@ describe('attendee incorporation & invite-token in groups', () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never); prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.attendee.findFirst.mockResolvedValue(null); prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.count.mockResolvedValue(20); prisma.attendee.count.mockResolvedValue(20);
prisma.attendee.create.mockResolvedValue({ prisma.attendee.create.mockResolvedValue(attendeeRow() as never);
id: 'att-1',
groupId: 'group-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
guardianName: null,
guardianPhone: null,
notes: null,
createdAt: new Date('2026-09-18T10:00:00.000Z'),
updatedAt: new Date('2026-09-18T10:00:00.000Z'),
} as never);
const app = makeApp({ id: teacherId }); const app = makeApp({ id: teacherId });
const res = await app.request('/groups/group-1/attendees?allowOverflow=true', { const res = await app.request('/groups/group-1/attendees?allowOverflow=true', {
@@ -412,16 +494,19 @@ describe('attendee incorporation & invite-token in groups', () => {
describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => { describe('POST /groups/:groupId/attendees/bulk (bulk import)', () => {
it('imports multiple attendees, skipping duplicates and reporting counts', async () => { it('imports multiple attendees, skipping duplicates and reporting counts', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never); prisma.group.findUnique.mockResolvedValue(mockGroup as never);
// Simulate that an attendee with phone '11111111' already exists // The teacher's people: '11111111' is already in this group, '44444444'
prisma.attendee.findMany.mockResolvedValue([ // is in another group only (and active there).
{ phone: '11111111' }, prisma.person.findMany.mockResolvedValue([
{ id: 'person-in-group', phone: '11111111', attendees: [{ groupId: 'group-1', status: 'ACTIVE' }] },
{ id: 'person-elsewhere', phone: '44444444', attendees: [{ groupId: 'group-9', status: 'ACTIVE' }] },
] as never); ] as never);
prisma.attendee.create.mockImplementation(async ({ data }: { data: any }) => ({ prisma.attendee.create.mockImplementation(async ({ data }: { data: any }) => ({
id: `att-${Math.random()}`, id: `att-${Math.random()}`,
...data, groupId: 'group-1',
guardianName: null, personId: data.personId ?? 'person-new',
guardianPhone: null, notifyToken: null,
person: personRow({ fullName: data.person?.create?.fullName ?? 'Existente' }),
createdAt: new Date('2026-09-18T10: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-18T10:00:00.000Z'),
})); }));
@@ -434,19 +519,27 @@ describe('attendee incorporation & invite-token in groups', () => {
attendees: [ attendees: [
{ firstName: 'Ana', lastName: 'García', phone: '22222222' }, { firstName: 'Ana', lastName: 'García', phone: '22222222' },
{ firstName: 'Pedro', lastName: 'López', phone: '33333333' }, { firstName: 'Pedro', lastName: 'López', phone: '33333333' },
{ firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the DB { firstName: 'Duplicado', lastName: 'Existente', phone: '11111111' }, // Already in the group
{ firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch { firstName: 'Duplicado', lastName: 'EnLote', phone: '22222222' }, // Duplicate within the batch
{ firstName: 'Otra', lastName: 'Persona', phone: '44444444' }, // In another group: linked
], ],
}), }),
}); });
expect(res.status).toBe(201); expect(res.status).toBe(201);
const data = await res.json(); const data = await res.json();
expect(data.totalProcessed).toBe(4); expect(data.totalProcessed).toBe(5);
expect(data.createdCount).toBe(2); expect(data.createdCount).toBe(3);
expect(data.linkedCount).toBe(1);
expect(data.duplicatesCount).toBe(2); expect(data.duplicatesCount).toBe(2);
expect(data.message).toBe('2 alumnos agregados con éxito, 2 duplicados omitidos.'); expect(data.message).toBe(
expect(prisma.attendee.create).toHaveBeenCalledTimes(2); '3 alumnos agregados con éxito (1 ya estaban en otros de tus grupos), 2 duplicados omitidos.',
);
expect(prisma.attendee.create).toHaveBeenCalledTimes(3);
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', personId: 'person-elsewhere' },
include: { person: { select: expect.any(Object) } },
});
}); });
}); });
@@ -456,12 +549,8 @@ describe('attendee incorporation & invite-token in groups', () => {
{ {
id: 'att-1', id: 'att-1',
groupId: 'group-1', groupId: 'group-1',
fullName: 'Ana García', personId: 'person-1',
email: null, person: personRow({ fullName: 'Ana García', phone: '22222222', email: null, notes: null }),
phone: '22222222',
guardianName: null,
guardianPhone: null,
notes: null,
createdAt: new Date('2026-09-18T10: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-18T10:00:00.000Z'),
attendances: [], attendances: [],
@@ -487,6 +576,7 @@ describe('attendee incorporation & invite-token in groups', () => {
// The row summary is requested in the same query: one request per // The row summary is requested in the same query: one request per
// member would be N+1 over a listing of up to 100. // member would be N+1 over a listing of up to 100.
include: { include: {
person: { select: expect.any(Object) },
attendances: { attendances: {
orderBy: { classSession: { startsAt: 'desc' } }, orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT, take: RECENT_ATTENDANCE_LIMIT,

View File

@@ -11,12 +11,16 @@ function record(
return { return {
id: 'att-1', id: 'att-1',
groupId: 'group-1', groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: null, email: null,
phone: null, phone: null,
guardianName: null, guardianName: null,
guardianPhone: null, guardianPhone: null,
notes: null, notes: null,
},
notifyToken: null, notifyToken: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'), createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -89,10 +93,12 @@ describe('toAttendeeListItemDto', () => {
}); });
it('conserva los campos del DTO plano', () => { it('conserva los campos del DTO plano', () => {
const dto = toAttendeeListItemDto(record({ phone: '22222222' })); const base = record();
const dto = toAttendeeListItemDto(record({ person: { ...base.person, phone: '22222222' } }));
expect(dto.fullName).toBe('Ana Pérez'); expect(dto.fullName).toBe('Ana Pérez');
expect(dto.phone).toBe('22222222'); expect(dto.phone).toBe('22222222');
expect(dto.personId).toBe('person-1');
expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z'); expect(dto.createdAt).toBe('2026-08-01T10:00:00.000Z');
}); });
}); });

View File

@@ -19,15 +19,30 @@ import { attendeesRoutes } from '@/modules/attendees';
const app = new Hono(); const app = new Hono();
app.route('/attendees', attendeesRoutes); app.route('/attendees', attendeesRoutes);
const attendeeRow = { const personSelect = {
id: 'attendee-1', id: true,
groupId: 'group-1', fullName: true,
email: true,
phone: true,
guardianName: true,
guardianPhone: true,
notes: true,
};
const person = {
id: 'person-1',
fullName: 'Ana Pérez', fullName: 'Ana Pérez',
email: 'ana@example.com', email: 'ana@example.com',
phone: null, phone: null,
guardianName: 'Luis Pérez', guardianName: 'Luis Pérez',
guardianPhone: null, guardianPhone: null,
notes: null, notes: null,
};
const attendeeRow = {
id: 'attendee-1',
groupId: 'group-1',
personId: 'person-1',
notifyToken: null, notifyToken: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'), createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'),
@@ -36,6 +51,7 @@ const attendeeRow = {
// What the Prisma mock returns: the row plus the summary relations. // What the Prisma mock returns: the row plus the summary relations.
const attendee = { const attendee = {
...attendeeRow, ...attendeeRow,
person,
attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }], attendances: [{ status: 'ABSENT' }, { status: 'PRESENT' }, { status: 'PRESENT' }],
payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }], payments: [{ status: 'OVERDUE', dueDate: new Date('2026-09-10T00:00:00.000Z') }],
}; };
@@ -56,6 +72,12 @@ describe('attendees routes', () => {
data: [ data: [
{ {
...attendeeRow, ...attendeeRow,
fullName: person.fullName,
email: person.email,
phone: person.phone,
guardianName: person.guardianName,
guardianPhone: person.guardianPhone,
notes: person.notes,
createdAt: attendeeRow.createdAt.toISOString(), createdAt: attendeeRow.createdAt.toISOString(),
updatedAt: attendeeRow.updatedAt.toISOString(), updatedAt: attendeeRow.updatedAt.toISOString(),
// The query comes most recent first; the row shows them // The query comes most recent first; the row shows them
@@ -71,6 +93,7 @@ describe('attendees routes', () => {
take: 10, take: 10,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
include: { include: {
person: { select: personSelect },
attendances: { attendances: {
orderBy: { classSession: { startsAt: 'desc' } }, orderBy: { classSession: { startsAt: 'desc' } },
take: RECENT_ATTENDANCE_LIMIT, take: RECENT_ATTENDANCE_LIMIT,

View File

@@ -12,7 +12,8 @@ function makeDb(params: {
return { return {
billingSubscription: { findUnique: mock(async () => params.subscription ?? null) }, billingSubscription: { findUnique: mock(async () => params.subscription ?? null) },
group: { count: mock(async () => params.groups ?? 0) }, group: { count: mock(async () => params.groups ?? 0) },
attendee: { count: mock(async () => params.attendees ?? 0) }, // People with an active membership: someone in two groups counts once.
person: { count: mock(async () => params.attendees ?? 0) },
}; };
} }

View File

@@ -29,7 +29,14 @@ describe('plan guards in the use cases', () => {
it('checks a bulk import against the group owner, with the number of new attendees', async () => { it('checks a bulk import against the group owner, with the number of new attendees', async () => {
const db = { const db = {
group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) }, group: { findUnique: mock(async () => ({ id: 'g1', createdById: ownerId, members: [{ userId: 'admin-1' }] })) },
attendee: { findMany: mock(async () => [{ phone: '1111' }]), create: mock() }, attendee: { create: mock() },
// '1111' is already in this group; '4444' is active in another group.
person: {
findMany: mock(async () => [
{ id: 'p1', phone: '1111', attendees: [{ groupId: 'g1', status: 'ACTIVE' }] },
{ id: 'p4', phone: '4444', attendees: [{ groupId: 'g2', status: 'ACTIVE' }] },
]),
},
}; };
const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) }; const planGuard = { canAddAttendees: mock(async () => err(planLimitReachedProblem('attendees', 15))) };
@@ -38,9 +45,11 @@ describe('plan guards in the use cases', () => {
{ fullName: 'Ana', phone: '2222' }, { fullName: 'Ana', phone: '2222' },
{ fullName: 'Beto', phone: '3333' }, { fullName: 'Beto', phone: '3333' },
{ fullName: 'Repetido', phone: '1111' }, { fullName: 'Repetido', phone: '1111' },
{ fullName: 'De otro grupo', phone: '4444' },
], ],
} as never); } as never);
// Only the two new people: the one already active elsewhere takes no slot.
expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2); expect(planGuard.canAddAttendees).toHaveBeenCalledWith(ownerId, 2);
expect(result.ok).toBe(false); expect(result.ok).toBe(false);
expect(db.attendee.create).not.toHaveBeenCalled(); expect(db.attendee.create).not.toHaveBeenCalled();

View File

@@ -159,8 +159,8 @@ describe('classes routes', () => {
it('incluye estado de pago dinámico, asistencia y ausencia avisada', async () => { it('incluye estado de pago dinámico, asistencia y ausencia avisada', async () => {
prisma.classSession.findUnique.mockResolvedValue(makeSession()); prisma.classSession.findUnique.mockResolvedValue(makeSession());
prisma.attendee.findMany.mockResolvedValue([ prisma.attendee.findMany.mockResolvedValue([
{ id: 'attendee-1', fullName: 'Ana Pérez' }, { id: 'attendee-1', person: { fullName: 'Ana Pérez' } },
{ id: 'attendee-2', fullName: 'Bruno Díaz' }, { id: 'attendee-2', person: { fullName: 'Bruno Díaz' } },
]); ]);
prisma.payment.findMany.mockResolvedValue([ prisma.payment.findMany.mockResolvedValue([
{ attendeeId: 'attendee-1', status: 'OVERDUE', dueDate: new Date('2026-09-01T00:00:00.000Z') }, { attendeeId: 'attendee-1', status: 'OVERDUE', dueDate: new Date('2026-09-01T00:00:00.000Z') },
@@ -443,7 +443,7 @@ describe('classes routes', () => {
prisma.attendee.findUnique.mockResolvedValue({ prisma.attendee.findUnique.mockResolvedValue({
id: 'attendee-1', id: 'attendee-1',
fullName: 'Ana Pérez', person: { fullName: 'Ana Pérez' },
group: { group: {
id: 'group-1', id: 'group-1',
name: 'Funcional', name: 'Funcional',

View File

@@ -63,7 +63,10 @@ describe.skipIf(!url)('payment review (real database)', () => {
], ],
}); });
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } }); await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.teacher } });
await db.attendee.create({ data: { id: ids.ana, groupId: ids.group, fullName: 'Ana', createdAt: new Date('2026-01-01T00:00:00Z') } }); await db.person.create({ data: { id: `${ids.ana}-person`, createdById: ids.teacher, fullName: 'Ana' } });
await db.attendee.create({
data: { id: ids.ana, groupId: ids.group, personId: `${ids.ana}-person`, createdAt: new Date('2026-01-01T00:00:00Z') },
});
await db.studentAccount.create({ await db.studentAccount.create({
data: { data: {
id: ids.account, id: ids.account,
@@ -71,7 +74,7 @@ describe.skipIf(!url)('payment review (real database)', () => {
createdById: ids.teacher, createdById: ids.teacher,
recoveryEmail: 'ana@test.local', recoveryEmail: 'ana@test.local',
recoveryEmailVerifiedAt: NOW, recoveryEmailVerifiedAt: NOW,
attendees: { create: { attendeeId: ids.ana } }, people: { create: { personId: `${ids.ana}-person` } },
}, },
}); });
await db.payment.create({ await db.payment.create({

View File

@@ -19,7 +19,14 @@ describe.skipIf(!url)('student access (real database)', () => {
// Same contract as UnitOfWork.executeResult, built on this file's own client // Same contract as UnitOfWork.executeResult, built on this file's own client
// (other test files mock '@/lib/prisma'). // (other test files mock '@/lib/prisma').
let unitOfWork: { executeResult: unknown }; let unitOfWork: { executeResult: unknown };
const ids = { user: `test-user-${suffix}`, group: `test-group-${suffix}`, attendee: `test-att-${suffix}` }; const ids = {
user: `test-user-${suffix}`,
group: `test-group-${suffix}`,
group2: `test-group2-${suffix}`,
person: `test-person-${suffix}`,
attendee: `test-att-${suffix}`,
attendee2: `test-att2-${suffix}`,
};
beforeAll(async () => { beforeAll(async () => {
db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) }); db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url as string }) });
@@ -42,7 +49,11 @@ describe.skipIf(!url)('student access (real database)', () => {
}; };
await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } }); await db.user.create({ data: { id: ids.user, name: 'Profe Test', email: `${ids.user}@test.local` } });
await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } }); await db.group.create({ data: { id: ids.group, name: 'Natación', createdById: ids.user } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, fullName: 'Ana Pérez' } }); await db.group.create({ data: { id: ids.group2, name: 'Yoga', createdById: ids.user } });
// One person in two groups of the teacher.
await db.person.create({ data: { id: ids.person, createdById: ids.user, fullName: 'Ana Pérez' } });
await db.attendee.create({ data: { id: ids.attendee, groupId: ids.group, personId: ids.person } });
await db.attendee.create({ data: { id: ids.attendee2, groupId: ids.group2, personId: ids.person } });
}); });
afterAll(async () => { afterAll(async () => {
@@ -96,7 +107,7 @@ describe.skipIf(!url)('student access (real database)', () => {
if (!loser.ok) expect(loser.error.status).toBe(410); if (!loser.ok) expect(loser.error.status).toBe(410);
} }
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } }); const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } }); const sessions = await db.studentSession.findMany({ where: { accountId: account.accountId, revokedAt: null } });
expect(sessions).toHaveLength(1); expect(sessions).toHaveLength(1);
expect(sessions[0]?.device).toBe('iPhone · Safari'); expect(sessions[0]?.device).toBe('iPhone · Safari');
@@ -122,7 +133,7 @@ describe.skipIf(!url)('student access (real database)', () => {
if (!first.ok) throw new Error('invite failed'); if (!first.ok) throw new Error('invite failed');
const consumed = await consume(tokenOf(first.value.url)); const consumed = await consume(tokenOf(first.value.url));
expect(consumed.ok).toBe(true); expect(consumed.ok).toBe(true);
const linked = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } }); const linked = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
await db.studentPasskey.create({ await db.studentPasskey.create({
data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' }, data: { accountId: linked.accountId, credentialId: `cred-${suffix}`, publicKey: new Uint8Array([1]), device: 'iPhone · Safari' },
}); });
@@ -141,9 +152,25 @@ describe.skipIf(!url)('student access (real database)', () => {
expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false); expect((await consume(tokenOf(pendingOld.value.url))).ok).toBe(false);
expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true); expect((await consume(tokenOf(reinvite.value.url))).ok).toBe(true);
const account = await db.studentAccountAttendee.findFirstOrThrow({ where: { attendeeId: ids.attendee } }); const account = await db.studentAccountPerson.findFirstOrThrow({ where: { personId: ids.person } });
expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1); expect(await db.studentSession.count({ where: { accountId: account.accountId, revokedAt: null } })).toBe(1);
const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user); const after = await new GetStudentAccess({ db }).execute(ids.group, ids.attendee, ids.user);
expect(after).toMatchObject({ ok: true, value: { status: 'active' } }); expect(after).toMatchObject({ ok: true, value: { status: 'active' } });
}); });
it('una sola cuenta por persona: invitar desde otro grupo la reutiliza', async () => {
const fromFirst = await invite();
if (!fromFirst.ok) throw new Error('invite failed');
const fromSecond = await new InviteStudent({ db, unitOfWork: unitOfWork as never }).execute(
ids.group2,
ids.attendee2,
ids.user,
);
if (!fromSecond.ok) throw new Error('invite failed');
expect(await db.studentAccountPerson.count({ where: { personId: ids.person } })).toBe(1);
// Same state from both groups: it is the person's access.
const fromGroup2 = await new GetStudentAccess({ db }).execute(ids.group2, ids.attendee2, ids.user);
expect(fromGroup2).toMatchObject({ ok: true, value: { status: 'invited' } });
});
}); });

View File

@@ -8,6 +8,7 @@ import type { FileStorage } from '@/lib/storage';
import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case'; import { CancelStudentAbsence, NotifyStudentAbsences } from '@/modules/student-portal/features/absences/use-case';
import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case'; import { GetStudentClasses } from '@/modules/student-portal/features/classes/use-case';
import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case'; import { GetStudentFees } from '@/modules/student-portal/features/fees/use-case';
import { GetStudentMe } from '@/modules/student-portal/features/me/use-case';
import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case'; import { ReportStudentPayment } from '@/modules/student-portal/features/payment-reports/use-case';
const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined; const url = process.env.DB_TESTS === '1' ? process.env.DATABASE_URL : undefined;
@@ -30,7 +31,12 @@ describe.skipIf(!url)('student portal (real database)', () => {
const ids = { const ids = {
user: `t-user-${suffix}`, user: `t-user-${suffix}`,
group: `t-group-${suffix}`, group: `t-group-${suffix}`,
yoga: `t-yoga-${suffix}`,
personAna: `t-p-ana-${suffix}`,
personBeto: `t-p-beto-${suffix}`,
ana: `t-ana-${suffix}`, ana: `t-ana-${suffix}`,
anaYoga: `t-ana-yoga-${suffix}`,
betoYoga: `t-beto-yoga-${suffix}`,
beto: `t-beto-${suffix}`, beto: `t-beto-${suffix}`,
accountAna: `t-acc-ana-${suffix}`, accountAna: `t-acc-ana-${suffix}`,
accountBeto: `t-acc-beto-${suffix}`, accountBeto: `t-acc-beto-${suffix}`,
@@ -50,17 +56,29 @@ describe.skipIf(!url)('student portal (real database)', () => {
await db.group.create({ await db.group.create({
data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' }, data: { id: ids.group, name: 'Natación', createdById: ids.user, days: ['MONDAY', 'WEDNESDAY', 'FRIDAY'], time: '18:00' },
}); });
await db.group.create({
data: { id: ids.yoga, name: 'Yoga', createdById: ids.user, days: ['TUESDAY'], time: '10:00' },
});
await db.person.createMany({
data: [
{ id: ids.personAna, createdById: ids.user, fullName: 'Ana' },
{ id: ids.personBeto, createdById: ids.user, fullName: 'Beto' },
],
});
// Ana and Beto are in both groups.
await db.attendee.createMany({ await db.attendee.createMany({
data: [ data: [
{ id: ids.ana, groupId: ids.group, fullName: 'Ana' }, { id: ids.ana, groupId: ids.group, personId: ids.personAna },
{ id: ids.beto, groupId: ids.group, fullName: 'Beto' }, { id: ids.beto, groupId: ids.group, personId: ids.personBeto },
{ id: ids.anaYoga, groupId: ids.yoga, personId: ids.personAna },
{ id: ids.betoYoga, groupId: ids.yoga, personId: ids.personBeto },
], ],
}); });
await db.studentAccount.create({ await db.studentAccount.create({
data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, attendees: { create: { attendeeId: ids.ana } } }, data: { id: ids.accountAna, name: 'Ana', createdById: ids.user, people: { create: { personId: ids.personAna } } },
}); });
await db.studentAccount.create({ await db.studentAccount.create({
data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, attendees: { create: { attendeeId: ids.beto } } }, data: { id: ids.accountBeto, name: 'Beto', createdById: ids.user, people: { create: { personId: ids.personBeto } } },
}); });
await db.payment.createMany({ await db.payment.createMany({
data: [ data: [
@@ -117,6 +135,21 @@ describe.skipIf(!url)('student portal (real database)', () => {
expect(!invented.ok && invented.error.status).toBe(400); expect(!invented.ok && invented.error.status).toBe(400);
}); });
it('la cuenta de la persona ve todos sus grupos, y solo los suyos', async () => {
const me = await new GetStudentMe({ db }).execute(ids.accountAna);
if (!me.ok) throw new Error('me failed');
expect(me.value.students.map((student) => [student.attendeeId, student.groupName])).toEqual([
[ids.ana, 'Natación'],
[ids.anaYoga, 'Yoga'],
]);
// Her membership in the second group is reachable; Beto's in that group is not.
expect((await new GetStudentFees({ db }).execute(ids.accountAna, ids.anaYoga)).ok).toBe(true);
const foreign = await new GetStudentFees({ db }).execute(ids.accountAna, ids.betoYoga);
expect(foreign.ok).toBe(false);
if (!foreign.ok) expect(foreign.error.status).toBe(404);
});
it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => { it('IDOR: una cuenta no ve ni toca datos de otro alumno', async () => {
expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false); expect((await new GetStudentClasses({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);
expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false); expect((await new GetStudentFees({ db, now: NOW }).execute(ids.accountBeto, ids.ana)).ok).toBe(false);

View File

@@ -61,7 +61,7 @@ describe('groups routes', () => {
it('lists groups scoped to the current user', async () => { it('lists groups scoped to the current user', async () => {
prisma.group.findMany.mockResolvedValue([ prisma.group.findMany.mockResolvedValue([
{ ...group, _count: { attendees: 4, waitlist: 1 } }, { ...group, _count: { attendees: 4, waitlist: 1, payments: 3 } },
]); ]);
prisma.group.count.mockResolvedValue(1); prisma.group.count.mockResolvedValue(1);
@@ -76,6 +76,7 @@ describe('groups routes', () => {
updatedAt: group.updatedAt.toISOString(), updatedAt: group.updatedAt.toISOString(),
attendeesCount: 4, attendeesCount: 4,
waitlistCount: 1, waitlistCount: 1,
unpaidPaymentsCount: 3,
}, },
], ],
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 }, pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
@@ -89,7 +90,11 @@ describe('groups routes', () => {
where, where,
include: { include: {
_count: { _count: {
select: { attendees: true, waitlist: { where: { status: 'PENDING' } } }, select: {
attendees: true,
waitlist: { where: { status: 'PENDING' } },
payments: { where: { status: { in: ['PENDING', 'OVERDUE'] } } },
},
}, },
}, },
}); });

View File

@@ -82,7 +82,7 @@ describe('GetHomeSummary', () => {
dueDate: new Date('2026-09-25T12:00:00.000Z'), dueDate: new Date('2026-09-25T12:00:00.000Z'),
status: 'PENDING', status: 'PENDING',
group: { name: 'Cuadrilla A' }, group: { name: 'Cuadrilla A' },
attendee: { fullName: 'Ana García' }, attendee: { person: { fullName: 'Ana García' } },
}, },
]); ]);
@@ -130,7 +130,7 @@ describe('GetHomeSummary', () => {
where: { groupId: { in: ['g2', 'g1'] }, status: { in: ['PENDING', 'OVERDUE'] } }, where: { groupId: { in: ['g2', 'g1'] }, status: { in: ['PENDING', 'OVERDUE'] } },
orderBy: [{ dueDate: 'asc' }], orderBy: [{ dueDate: 'asc' }],
take: 5, take: 5,
include: { group: { select: { name: true } }, attendee: { select: { fullName: true } } }, include: { group: { select: { name: true } }, attendee: { select: { person: { select: { fullName: true } } } } },
}); });
}); });

View File

@@ -81,8 +81,8 @@ describe('create payments batch', () => {
prisma.group.findUnique.mockResolvedValue(groupOwner); prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([ prisma.attendee.findMany.mockResolvedValue([
{ id: 'att-1', fullName: 'Juana' }, { id: 'att-1', person: { fullName: 'Juana' } },
{ id: 'att-2', fullName: 'Pedro' }, { id: 'att-2', person: { fullName: 'Pedro' } },
]); ]);
prisma.payment.create prisma.payment.create
.mockResolvedValueOnce({ id: 'pay-1' }) .mockResolvedValueOnce({ id: 'pay-1' })
@@ -142,14 +142,14 @@ describe('create payments batch', () => {
unitPrice: 120, unitPrice: 120,
currencyId: 'ARS', currencyId: 'ARS',
externalReference: 'pay-1', externalReference: 'pay-1',
backUrl: `${webOrigin}/payments`, backUrl: `${webOrigin}/student/payments`,
}); });
}); });
it('derives the currency from the owner country and defaults when there is none', async () => { it('derives the currency from the owner country and defaults when there is none', async () => {
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } }); prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } });
prisma.user.findUnique.mockResolvedValue({ id: userId, country: null }); prisma.user.findUnique.mockResolvedValue({ id: userId, country: null });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', fullName: 'Pedro' }]); prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', person: { fullName: 'Pedro' } }]);
prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' }); prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' });
const useCase = batchUseCase(); const useCase = batchUseCase();
createPreference.mockResolvedValueOnce({ createPreference.mockResolvedValueOnce({
@@ -169,13 +169,14 @@ describe('create payments batch', () => {
expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' }); expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' });
expect(prisma.attendee.findMany).toHaveBeenCalledWith({ expect(prisma.attendee.findMany).toHaveBeenCalledWith({
where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } }, where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } },
include: { person: { select: { fullName: true } } },
}); });
}); });
it('propagates the not-connected problem and creates no rows', async () => { it('propagates the not-connected problem and creates no rows', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner); prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]); prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
getToken = mock(async () => ({ getToken = mock(async () => ({
ok: false, ok: false,
error: { error: {
@@ -203,7 +204,7 @@ describe('create payments batch', () => {
it('answers 409 over HTTP when the owner has no linked account', async () => { it('answers 409 over HTTP when the owner has no linked account', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner); prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' }); prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]); prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', person: { fullName: 'Juana' } }]);
prisma.mpAccount.findUnique.mockResolvedValue(null); prisma.mpAccount.findUnique.mockResolvedValue(null);
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', { const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {

View File

@@ -49,7 +49,7 @@ function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
paidAt: null, paidAt: null,
createdAt: new Date('2026-10-01T10:00:00.000Z'), createdAt: new Date('2026-10-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T10:00:00.000Z'), updatedAt: new Date('2026-10-01T10:00:00.000Z'),
attendee: { fullName: 'Juana Pérez' }, attendee: { person: { fullName: 'Juana Pérez' } },
group: { group: {
name: 'Vinyasa', name: 'Vinyasa',
price: { toString: () => '120.00' }, price: { toString: () => '120.00' },
@@ -101,13 +101,13 @@ describe('renew payment link', () => {
unitPrice: 120, unitPrice: 120,
currencyId: 'ARS', currencyId: 'ARS',
externalReference: 'pay-1', externalReference: 'pay-1',
backUrl: `${webOrigin}/payments`, backUrl: `${webOrigin}/student/payments`,
}); });
expect(prisma.payment.update).toHaveBeenCalledWith({ expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' }, where: { id: 'pay-1' },
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' }, data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
include: { include: {
attendee: { select: { fullName: true } }, attendee: { select: { person: { select: { fullName: true } } } },
group: { select: { name: true, price: true } }, group: { select: { name: true, price: true } },
}, },
}); });

View File

@@ -36,7 +36,7 @@ const payment = {
createdAt: new Date('2026-08-01T10:00:00.000Z'), createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'),
group: { name: 'Cuadrilla Alfa', price: 150.5 }, group: { name: 'Cuadrilla Alfa', price: 150.5 },
attendee: { fullName: 'Juana Pérez' }, attendee: { person: { fullName: 'Juana Pérez' } },
}; };
function makeApp(userValue: unknown) { function makeApp(userValue: unknown) {
@@ -93,7 +93,7 @@ describe('payments routes', () => {
where: { groupId: { in: ['group-1'] } }, where: { groupId: { in: ['group-1'] } },
include: { include: {
group: { select: { name: true, price: true } }, group: { select: { name: true, price: true } },
attendee: { select: { fullName: true } }, attendee: { select: { person: { select: { fullName: true } } } },
}, },
skip: 0, skip: 0,
take: 10, take: 10,

View File

@@ -10,6 +10,11 @@ const db = {
count: mock(), count: mock(),
create: mock(), create: mock(),
}, },
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: { groupWaitlistEntry: {
findFirst: mock(), findFirst: mock(),
create: mock(), create: mock(),
@@ -69,12 +74,16 @@ const preRegistration = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({ const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1', id: 'att-1',
groupId: 'group-1', groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez', fullName: 'Martín Gómez',
phone: '+5491133445566', phone: '+5491133445566',
email: null, email: null,
guardianName: null, guardianName: null,
guardianPhone: null, guardianPhone: null,
notes: null, notes: null,
},
notifyToken: 'notify-1', notifyToken: 'notify-1',
createdAt: new Date('2026-09-18T10: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-18T10:00:00.000Z'),
@@ -107,6 +116,9 @@ function makeApp(userValue: unknown) {
describe('group pre-registrations', () => { describe('group pre-registrations', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
// The phone is nobody the teacher has yet: promoting creates the person.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
}); });
describe('GET /groups/:groupId/preregistrations', () => { describe('GET /groups/:groupId/preregistrations', () => {
@@ -183,14 +195,19 @@ describe('group pre-registrations', () => {
expect(body.outcome).toBe('added'); expect(body.outcome).toBe('added');
expect(body.attendee.fullName).toBe('Martín Gómez'); expect(body.attendee.fullName).toBe('Martín Gómez');
expect(body.waitlistEntry).toBeNull(); expect(body.waitlistEntry).toBeNull();
expect(prisma.attendee.create).toHaveBeenCalledWith({ expect(prisma.person.create).toHaveBeenCalledWith({
data: { data: {
groupId: 'group-1', createdById: teacherId,
fullName: 'Martín Gómez', fullName: 'Martín Gómez',
phone: '+5491133445566', phone: '+5491133445566',
email: null, email: null,
notes: null, notes: null,
}, },
select: { id: true },
});
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-1', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
}); });
expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({ expect(prisma.groupPreRegistration.update).toHaveBeenCalledWith({
where: { id: 'pre-1' }, where: { id: 'pre-1' },
@@ -255,6 +272,13 @@ describe('group pre-registrations', () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never); prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never); prisma.groupPreRegistration.findFirst.mockResolvedValue(preRegistration() as never);
prisma.attendee.count.mockResolvedValue(5); prisma.attendee.count.mockResolvedValue(5);
prisma.person.findFirst.mockResolvedValue({
id: 'person-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
prisma.attendee.findFirst.mockResolvedValue(attendee() as never); prisma.attendee.findFirst.mockResolvedValue(attendee() as never);
const res = await makeApp({ id: teacherId }).request( const res = await makeApp({ id: teacherId }).request(

View File

@@ -95,6 +95,8 @@ describe('computeStudentAlerts: pagos', () => {
gravedad: 'vigilar', gravedad: 'vigilar',
etiqueta: 'Cuota vencida', etiqueta: 'Cuota vencida',
detalle: 'La cuota de octubre venció el 10/10.', detalle: 'La cuota de octubre venció el 10/10.',
razon: 'cuota',
valores: { cuotas: 1, vencimientos: ['2026-10-10T12:00:00.000Z'] },
firma: 'pay_1', firma: 'pay_1',
peso: 1, peso: 1,
}, },

View File

@@ -74,7 +74,7 @@ describe('link del alumno', () => {
expiresAt: new Date(NOW.getTime() + 1000), expiresAt: new Date(NOW.getTime() + 1000),
account: { account: {
name: 'Ana', name: 'Ana',
attendees: [{ attendee: { group: { name: 'Natación', owner: { name: 'Caro' } } } }], people: [{ person: { attendees: [{ group: { name: 'Natación', owner: { name: 'Caro' } } }] } }],
}, },
})), })),
updateMany: mock(), updateMany: mock(),

View File

@@ -1,4 +1,5 @@
import { describe, expect, it } from 'bun:test'; import { describe, expect, it } from 'bun:test';
import { REPORTED_PAYMENT_NOTE_MAX } from '@gruperly/shared';
import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type'; import { detectReceiptType, RECEIPT_MAX_BYTES } from '@/lib/file-type';
import type { FileStorage } from '@/lib/storage'; import type { FileStorage } from '@/lib/storage';
import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler'; import { occurrencesBetween, startOfWeekInTimeZone } from '@/modules/home/lib/scheduler';
@@ -45,6 +46,15 @@ describe('tipo real del comprobante (magic bytes)', () => {
const noStorage = new ReportStudentPayment({ db: db as never, storage: null }); const noStorage = new ReportStudentPayment({ db: db as never, storage: null });
const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } }); const unavailable = await noStorage.execute('acc', { attendeeId: 'a1', paymentIds: ['p1'], file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) } });
expect(!unavailable.ok && unavailable.error.status).toBe(503); expect(!unavailable.ok && unavailable.error.status).toBe(503);
const longNote = await useCase.execute('acc', {
attendeeId: 'a1',
paymentIds: ['p1'],
note: 'x'.repeat(REPORTED_PAYMENT_NOTE_MAX + 1),
file: { name: 'a.pdf', bytes: pad(ascii('%PDF-1.7')) },
});
expect(!longNote.ok && longNote.error.errors).toEqual({ note: ['too_long'] });
expect(puts).toEqual([]);
}); });
}); });

View File

@@ -12,6 +12,11 @@ const db = {
create: mock(), create: mock(),
delete: mock(), delete: mock(),
}, },
person: {
findFirst: mock(),
create: mock(),
deleteMany: mock(),
},
groupWaitlistEntry: { groupWaitlistEntry: {
findMany: mock(), findMany: mock(),
findFirst: mock(), findFirst: mock(),
@@ -70,12 +75,16 @@ const waitlistEntry = (overrides: Record<string, unknown> = {}) => ({
const attendee = (overrides: Record<string, unknown> = {}) => ({ const attendee = (overrides: Record<string, unknown> = {}) => ({
id: 'att-1', id: 'att-1',
groupId: 'group-1', groupId: 'group-1',
personId: 'person-1',
person: {
id: 'person-1',
fullName: 'Martín Gómez', fullName: 'Martín Gómez',
phone: '+5491133445566', phone: '+5491133445566',
email: null, email: null,
guardianName: null, guardianName: null,
guardianPhone: null, guardianPhone: null,
notes: null, notes: null,
},
createdAt: new Date('2026-09-18T10: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-18T10:00:00.000Z'),
...overrides, ...overrides,
@@ -94,6 +103,9 @@ function makeApp(userValue: unknown) {
describe('group waitlist management', () => { describe('group waitlist management', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
// The phone is nobody the teacher has yet: promoting creates the person.
prisma.person.findFirst.mockResolvedValue(null);
prisma.person.create.mockResolvedValue({ id: 'person-1' } as never);
}); });
describe('GET /groups/:groupId/waitlist', () => { describe('GET /groups/:groupId/waitlist', () => {
@@ -146,7 +158,12 @@ describe('group waitlist management', () => {
const data = await res.json(); const data = await res.json();
expect(data.attendee.fullName).toBe('Martín Gómez'); expect(data.attendee.fullName).toBe('Martín Gómez');
expect(prisma.attendee.create).toHaveBeenCalledWith({ expect(prisma.attendee.create).toHaveBeenCalledWith({
data: expect.objectContaining({ groupId: 'group-1', fullName: 'Martín Gómez', phone: '+5491133445566' }), data: { groupId: 'group-1', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.person.create).toHaveBeenCalledWith({
data: expect.objectContaining({ createdById: teacherId, fullName: 'Martín Gómez', phone: '+5491133445566' }),
select: { id: true },
}); });
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } }); expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
}); });
@@ -167,10 +184,17 @@ describe('group waitlist management', () => {
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled(); expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
}); });
it('rejects with 409 when the phone already belongs to an attendee', async () => { it('rejects with 409 when the person is already a member of the group', async () => {
prisma.group.findUnique.mockResolvedValue(mockGroup as never); prisma.group.findUnique.mockResolvedValue(mockGroup as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never); prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5); prisma.attendee.count.mockResolvedValue(5);
prisma.person.findFirst.mockResolvedValue({
id: 'person-1',
fullName: 'Martín Gómez',
email: null,
phone: '+5491133445566',
attendees: [{ id: 'att-existing', groupId: 'group-1', status: 'ACTIVE', group: { name: 'Pintura' } }],
} as never);
prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never); prisma.attendee.findFirst.mockResolvedValue({ id: 'att-existing' } as never);
const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', { const res = await makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
@@ -204,6 +228,72 @@ describe('group waitlist management', () => {
expect(res.status).toBe(403); expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled(); expect(prisma.attendee.create).not.toHaveBeenCalled();
}); });
const promoteTo = (targetGroupId: string) =>
makeApp({ id: teacherId }).request('/groups/group-1/waitlist/wl-1/promote', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ targetGroupId }),
});
it('places the entry in another group of the teacher and removes it from the origin waitlist', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', name: 'Taller de Cerámica' } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
prisma.attendee.findFirst.mockResolvedValue(null);
prisma.attendee.create.mockResolvedValue(attendee({ groupId: 'group-2' }) as never);
const res = await promoteTo('group-2');
expect(res.status).toBe(200);
expect(prisma.group.findUnique).toHaveBeenLastCalledWith({ where: { id: 'group-2' } });
expect(prisma.attendee.count).toHaveBeenCalledWith({ where: { groupId: 'group-2', status: 'ACTIVE' } });
expect(prisma.attendee.create).toHaveBeenCalledWith({
data: { groupId: 'group-2', personId: 'person-1' },
include: { person: { select: expect.any(Object) } },
});
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
});
it('rejects a target group owned by another teacher', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', createdById: 'other-user' } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
const res = await promoteTo('group-2');
expect(res.status).toBe(403);
expect(prisma.attendee.create).not.toHaveBeenCalled();
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
it('returns 404 when the target group does not exist', async () => {
prisma.group.findUnique.mockResolvedValueOnce(mockGroup as never).mockResolvedValueOnce(null);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
const res = await promoteTo('group-missing');
expect(res.status).toBe(404);
expect(prisma.attendee.create).not.toHaveBeenCalled();
});
it('rejects with 409 when the target group reached its capacity', async () => {
prisma.group.findUnique
.mockResolvedValueOnce(mockGroup as never)
.mockResolvedValueOnce({ ...mockGroup, id: 'group-2', capacity: 5 } as never);
prisma.groupWaitlistEntry.findFirst.mockResolvedValue(waitlistEntry() as never);
prisma.attendee.count.mockResolvedValue(5);
const res = await promoteTo('group-2');
expect(res.status).toBe(409);
const body = await res.json();
expect(body.code).toBe('group_capacity_reached');
expect(prisma.groupWaitlistEntry.delete).not.toHaveBeenCalled();
});
}); });
describe('DELETE /groups/:groupId/waitlist/:entryId', () => { describe('DELETE /groups/:groupId/waitlist/:entryId', () => {
@@ -260,6 +350,10 @@ describe('group waitlist management', () => {
expect(body.removedAttendeeId).toBe('att-1'); expect(body.removedAttendeeId).toBe('att-1');
expect(body.promoted).toBeNull(); expect(body.promoted).toBeNull();
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } }); expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
// Their last group: the person goes too (no-op if they are in others).
expect(prisma.person.deleteMany).toHaveBeenCalledWith({
where: { id: 'person-1', attendees: { none: {} } },
});
}); });
it('removes an attendee and promotes the first pending waitlist entry atomically', async () => { it('removes an attendee and promotes the first pending waitlist entry atomically', async () => {
@@ -288,8 +382,9 @@ describe('group waitlist management', () => {
expect(body.promoted).toMatchObject({ id: 'wl-1', fullName: 'Sofía Ruiz' }); expect(body.promoted).toMatchObject({ id: 'wl-1', fullName: 'Sofía Ruiz' });
expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } }); expect(prisma.attendee.delete).toHaveBeenCalledWith({ where: { id: 'att-1' } });
expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } }); expect(prisma.groupWaitlistEntry.delete).toHaveBeenCalledWith({ where: { id: 'wl-1' } });
expect(prisma.attendee.create).toHaveBeenCalledWith({ expect(prisma.person.create).toHaveBeenCalledWith({
data: expect.objectContaining({ fullName: 'Sofía Ruiz', phone: '+5491133778899' }), data: expect.objectContaining({ fullName: 'Sofía Ruiz', phone: '+5491133778899' }),
select: { id: true },
}); });
}); });

View File

@@ -37,7 +37,7 @@ function payment(id: string, attendee: Record<string, unknown>, overrides: Recor
currency: 'ARS', currency: 'ARS',
dueDate: new Date('2026-10-20T15:00:00.000Z'), dueDate: new Date('2026-10-20T15:00:00.000Z'),
checkoutUrl: `https://mpago.la/${id}`, checkoutUrl: `https://mpago.la/${id}`,
attendee: { phone: null, guardianPhone: null, ...attendee }, attendee: { id: attendee.id, person: { phone: null, guardianPhone: null, ...attendee } },
...overrides, ...overrides,
}; };
} }
@@ -282,11 +282,11 @@ describe('re-engagement messages', () => {
]); ]);
db.attendee.findMany db.attendee.findMany
.mockResolvedValueOnce([ .mockResolvedValueOnce([
{ id: 'att-1', fullName: 'Ana López', phone: '1123456789', createdAt: enrolled }, { id: 'att-1', person: { fullName: 'Ana López', phone: '1123456789' }, createdAt: enrolled },
{ id: 'att-2', fullName: 'Beto', phone: '1198765432', createdAt: enrolled }, { id: 'att-2', person: { fullName: 'Beto', phone: '1198765432' }, createdAt: enrolled },
]) ])
.mockResolvedValueOnce([ .mockResolvedValueOnce([
{ id: 'att-1', phone: '1123456789', guardianPhone: null }, { id: 'att-1', person: { phone: '1123456789', guardianPhone: null } },
]); ]);
db.attendance.findMany.mockResolvedValue([ db.attendance.findMany.mockResolvedValue([
{ attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } }, { attendeeId: 'att-1', classSessionId: 's1', status: 'ABSENT', classSession: { startsAt: s1 } },

3
apps/web/bunfig.toml Normal file
View File

@@ -0,0 +1,3 @@
[test]
# Inicializa i18n en es-AR: los tests asertan el copy en español.
preload = ["./test/setup.ts"]

View File

@@ -21,10 +21,12 @@
"@tanstack/react-router": "^1.170.38", "@tanstack/react-router": "^1.170.38",
"better-auth": "1.7.2", "better-auth": "1.7.2",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"i18next": "^26.5.11",
"lucide-react": "^1.34.0", "lucide-react": "^1.34.0",
"react": "^19.0.0", "react": "^19.0.0",
"react-dom": "^19.0.0", "react-dom": "^19.0.0",
"react-hook-form": "^7.54.0", "react-hook-form": "^7.54.0",
"react-i18next": "^17.1.9",
"tailwind-merge": "^3.6.0", "tailwind-merge": "^3.6.0",
"zod": "3.24.2" "zod": "3.24.2"
}, },

View File

@@ -1,15 +1,17 @@
import { Link, useLocation } from '@tanstack/react-router' import { Link, useLocation } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { NavBadge } from './NavBadge' import { NavBadge } from './NavBadge'
import { isNavItemActive, NAV_ITEMS } from './nav-items' import { isNavItemActive, NAV_ITEMS } from './nav-items'
export function BottomNav() { export function BottomNav() {
const location = useLocation() const location = useLocation()
const { t } = useTranslation('layout')
return ( return (
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden"> <nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur lg:hidden">
<div className="mx-auto grid max-w-md grid-cols-4"> <div className="mx-auto grid max-w-md grid-cols-4">
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => { {NAV_ITEMS.map(({ labelKey, to, icon: Icon, badge }) => {
const isActive = isNavItemActive(location.pathname, to) const isActive = isNavItemActive(location.pathname, to)
return ( return (
<Link <Link
@@ -32,7 +34,7 @@ export function BottomNav() {
<Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} /> <Icon className="size-5" strokeWidth={isActive ? 2.25 : 2} />
{badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null} {badge ? <NavBadge kind={badge} className="absolute -right-2.5 -top-1.5" /> : null}
</span> </span>
<span className="leading-none">{label}</span> <span className="leading-none">{t(labelKey)}</span>
</Link> </Link>
) )
})} })}

View File

@@ -1,52 +1,55 @@
import { Link, useLocation } from '@tanstack/react-router' import { Link, useLocation } from '@tanstack/react-router'
import { ChevronRight } from 'lucide-react' import { ChevronRight } from 'lucide-react'
import { useTranslation } from 'react-i18next'
type Crumb = { label: string; to?: string } type CrumbKey = 'home' | 'groups' | 'payments' | 'settings' | 'security' | 'profile'
type Crumb = { label: CrumbKey; to?: string }
const BREADCRUMBS: Record<string, Crumb[]> = { const BREADCRUMBS: Record<string, Crumb[]> = {
'/': [{ label: 'Inicio' }], '/': [{ label: 'home' }],
'/groups': [ '/groups': [
{ label: 'Inicio', to: '/' }, { label: 'home', to: '/' },
{ label: 'Grupos' }, { label: 'groups' },
], ],
'/payments': [ '/payments': [
{ label: 'Inicio', to: '/' }, { label: 'home', to: '/' },
{ label: 'Cobros' }, { label: 'payments' },
], ],
'/settings': [ '/settings': [
{ label: 'Inicio', to: '/' }, { label: 'home', to: '/' },
{ label: 'Ajustes' }, { label: 'settings' },
], ],
'/security': [ '/security': [
{ label: 'Inicio', to: '/' }, { label: 'home', to: '/' },
{ label: 'Ajustes', to: '/settings' }, { label: 'settings', to: '/settings' },
{ label: 'Seguridad' }, { label: 'security' },
], ],
'/profile': [ '/profile': [
{ label: 'Inicio', to: '/' }, { label: 'home', to: '/' },
{ label: 'Mi perfil' }, { label: 'profile' },
], ],
} }
export function Breadcrumb() { export function Breadcrumb() {
const location = useLocation() const location = useLocation()
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'Inicio' }] const { t } = useTranslation('layout')
const crumbs = BREADCRUMBS[location.pathname] ?? [{ label: 'home' }]
return ( return (
<nav aria-label="Breadcrumb" className="hidden items-center gap-1.5 text-sm lg:flex"> <nav aria-label={t('breadcrumb')} className="hidden items-center gap-1.5 text-sm lg:flex">
{crumbs.map((crumb, i) => { {crumbs.map((crumb, i) => {
const isLast = i === crumbs.length - 1 const isLast = i === crumbs.length - 1
return ( return (
<span key={crumb.label} className="flex items-center gap-1.5"> <span key={crumb.label} className="flex items-center gap-1.5">
{i > 0 ? <ChevronRight className="size-3.5 text-foreground/40" /> : null} {i > 0 ? <ChevronRight className="size-3.5 text-foreground/40" /> : null}
{isLast ? ( {isLast ? (
<span className="font-medium text-primary">{crumb.label}</span> <span className="font-medium text-primary">{t(`nav.${crumb.label}`)}</span>
) : ( ) : (
<Link <Link
to={crumb.to!} to={crumb.to!}
className="text-foreground/50 transition-colors hover:text-primary" className="text-foreground/50 transition-colors hover:text-primary"
> >
{crumb.label} {t(`nav.${crumb.label}`)}
</Link> </Link>
)} )}
</span> </span>

View File

@@ -1,10 +1,12 @@
import { Link } from '@tanstack/react-router' import { Link } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { Logo } from '../brand' import { Logo } from '../brand'
import { Breadcrumb } from './Breadcrumb' import { Breadcrumb } from './Breadcrumb'
import { ThemeToggle } from './ThemeToggle' import { ThemeToggle } from './ThemeToggle'
import { UserMenu } from './UserMenu' import { UserMenu } from './UserMenu'
export function Header() { export function Header() {
const { t } = useTranslation('layout')
return ( return (
<header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur"> <header className="sticky top-0 z-40 h-16 w-full border-b border-border bg-background/90 backdrop-blur">
<div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6"> <div className="mx-auto flex h-full w-full max-w-7xl items-center justify-between px-4 lg:px-6">
@@ -12,7 +14,7 @@ export function Header() {
{/* `Link` and not `<a>`: on mobile the logo is the only way back to the {/* `Link` and not `<a>`: on mobile the logo is the only way back to the
home screen and an anchor would reload the whole document, losing home screen and an anchor would reload the whole document, losing
the in-memory state (React Query cache, install event). */} the in-memory state (React Query cache, install event). */}
<Link to="/" className="flex items-center lg:hidden" aria-label="Gruperly inicio"> <Link to="/" className="flex items-center lg:hidden" aria-label={t('homeLink')}>
<Logo className="h-8" /> <Logo className="h-8" />
</Link> </Link>
<Breadcrumb /> <Breadcrumb />

View File

@@ -1,10 +1,12 @@
import { useReportedPaymentsCount } from '../../features/payments/reportedPayments' import { useReportedPaymentsCount } from '../../features/payments/reportedPayments'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
/* Counter of a nav item: today only "Pagos para verificar" on Cobros. The /* Counter of a nav item: today only "Pagos para verificar" on Cobros. The
number is in the accessible name too (sr-only), not only in the dot. */ number is in the accessible name too (sr-only), not only in the dot. */
export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) { export function NavBadge({ kind, className }: { kind: 'reported-payments'; className?: string }) {
const count = useReportedPaymentsCount() const count = useReportedPaymentsCount()
const { t } = useTranslation('layout')
if (kind !== 'reported-payments' || count === 0) return null if (kind !== 'reported-payments' || count === 0) return null
return ( return (
<span <span
@@ -13,8 +15,8 @@ export function NavBadge({ kind, className }: { kind: 'reported-payments'; class
className, className,
)} )}
> >
{count > 99 ? '99+' : count} <span aria-hidden="true">{count > 99 ? '99+' : count}</span>
<span className="sr-only"> pagos para verificar</span> <span className="sr-only">{t('reportedPayments', { count })}</span>
</span> </span>
) )
} }

View File

@@ -1,7 +1,10 @@
import { useTranslation } from 'react-i18next'
export function PublicFooter() { export function PublicFooter() {
const { t } = useTranslation('layout')
return ( return (
<footer className="border-t border-border px-4 py-4 text-center text-xs text-foreground/40"> <footer className="border-t border-border px-4 py-4 text-center text-xs text-foreground/40">
Gruperly — Gestión sencilla de cobros y grupos {t('publicFooter')}
</footer> </footer>
) )
} }

View File

@@ -1,4 +1,5 @@
import { Link, useLocation } from '@tanstack/react-router' import { Link, useLocation } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { Logo } from '../brand' import { Logo } from '../brand'
import { NavBadge } from './NavBadge' import { NavBadge } from './NavBadge'
@@ -6,6 +7,7 @@ import { isNavItemActive, NAV_ITEMS } from './nav-items'
export function Sidebar({ immersive = false }: { immersive?: boolean }) { export function Sidebar({ immersive = false }: { immersive?: boolean }) {
const location = useLocation() const location = useLocation()
const { t } = useTranslation('layout')
return ( return (
// Without the global header there's nothing to clear above: the sidebar // Without the global header there's nothing to clear above: the sidebar
@@ -19,12 +21,12 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
> >
{/* `Link` and not `<a>`: an anchor would reload the document and lose the {/* `Link` and not `<a>`: an anchor would reload the document and lose the
in-memory state (React Query cache, install event). */} in-memory state (React Query cache, install event). */}
<Link to="/" className="mb-8 flex items-center px-1" aria-label="Gruperly inicio"> <Link to="/" className="mb-8 flex items-center px-1" aria-label={t('homeLink')}>
<Logo className="h-10" /> <Logo className="h-10" />
</Link> </Link>
<nav className="flex flex-col gap-1"> <nav className="flex flex-col gap-1">
{NAV_ITEMS.map(({ label, to, icon: Icon, badge }) => { {NAV_ITEMS.map(({ labelKey, to, icon: Icon, badge }) => {
const isActive = isNavItemActive(location.pathname, to) const isActive = isNavItemActive(location.pathname, to)
return ( return (
<Link <Link
@@ -39,7 +41,7 @@ export function Sidebar({ immersive = false }: { immersive?: boolean }) {
)} )}
> >
<Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} /> <Icon className="size-5" strokeWidth={isActive ? 2.2 : 2} />
{label} {t(labelKey)}
{badge ? <NavBadge kind={badge} className="ml-auto" /> : null} {badge ? <NavBadge kind={badge} className="ml-auto" /> : null}
</Link> </Link>
) )

Some files were not shown because too many files have changed in this diff Show More