15 Commits

Author SHA1 Message Date
Jose Selesan
060a4f09e4 feat: app de alumnos sin contraseña (invitación de un solo uso, avisos de falta y pagos informados)
- Acceso del alumno o tutor con link de un solo uso (hash SHA-256, consumo
  atómico, el GET no consume), sesión propia de 90 días deslizante, passkeys
  opcionales (SimpleWebAuthn) y mail de recuperación con rate limit.
- Lado alumno (/i/:token, /acceso, /alumno/*): inicio, clases, avisar falta,
  pagos, informar pago con comprobante (S3 privado, magic bytes) y perfil.
- Lado profe: acceso a la app en la ficha del alumno (invitar/reinvitar),
  "Pagos para verificar" en Cobros con badge, faltas avisadas en la ficha de
  grupo y datos para transferir en Ajustes.
- "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas informadas.
- Zona horaria por defecto: Buenos Aires.
- Migración add_student_access, tests contra Postgres real (test:db) y docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 15:39:09 -03:00
Jose Selesan
b99bc4d519 feat: rediseño de Grupos y pantalla "Requiere atención"
- Grupos: subtítulo con resumen (grupos · alumnos · lugares libres),
  sección "Requiere atención" con los 4 alumnos más urgentes y tarjetas
  con avatares (punteados por lugar libre en grupos chicos, superpuestos
  con "+N" en grandes; con alerta primero y anillo de gravedad).
- Pantalla nueva /groups/attention: filtros Todos/Asistencia/Pagos,
  secciones Urgente y A vigilar, Contactar / Enviar recordatorio por
  wa.me y "Resuelto" persistente con update optimista.
- FAB "Nuevo grupo" que se pliega al scrollear (respeta reduced motion);
  los toasts en mobile suben para no quedar debajo.
- Alertas centralizadas en computeStudentAlerts (shared). La regla de
  asistencia pasa a: urgente = 3 seguidas o 4 de las últimas 6; a vigilar
  = 2 de las últimas 4 (sin inactividad por días ni tendencia). Cuotas:
  1 vencida vigilar, 2+ urgente.
- Backend: GET /attention y POST /attention/:attendeeId/resolve; tabla
  attendee_alert_resolutions (la alerta vuelve si cambia la firma).
- Tokens de gravedad para claro y oscuro; se quita el indicador de pills.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:35:07 -03:00
Jose Selesan
90f31290d4 feat(web): pulido mobile de ficha de grupo, alumno, nuevo grupo y ajustes
- Ficha de grupo: "Agregar miembro" a todo el ancho y debajo Estadísticas,
  Cobrar y Compartir con icono y texto (antes iconos sueltos en mobile).
  Los mensajes automáticos de WhatsApp quedan en una fila plegable que
  arranca cerrada si no hay ninguno activo.
- Historial del alumno: arranca en la primera clase registrada si es
  anterior al alta, como la lista y la regla de riesgo ("1 de 5" en ambos).
- Nuevo grupo: cupo 10 por defecto, precio vacío obligatorio y foco
  inicial en el nombre.
- Ajustes: chevron en Seguridad; el botón de tema del header queda solo
  en desktop (en mobile vive en Apariencia).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:33:37 -03:00
Jose Selesan
e6d405a71e feat: una sola regla de riesgo y preinscripciones pendientes en Inicio
- Estadísticas ("Alumnos en riesgo") y el job de reenganche usan la misma
  regla de dominio que la lista de grupos e Inicio
  (summarizeMemberAttendance). El armado del historial por alumno vive en
  analytics/lib/member-attendance.ts y se borra el clasificador viejo
  (racha o asistencia mensual < 50%).
- El badge de alumnos en riesgo muestra el motivo real (faltas seguidas,
  días sin venir o asistencia en baja).
- GET /home devuelve pendingPreRegistrations por grupo (en la misma
  consulta de grupos) y "Para atender" las lista con link a la ficha en
  la pestaña Pendientes (?section=pending).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:28:21 -03:00
Jose Selesan
b12ffdda37 feat(web): rediseño de Inicio en mobile y criterio de inactividad por clases faltadas
- Inicio: saludo con fecha, estadísticas compactas en fila (arregla el
  "0 / 0 por cobrar"), sección "Para atender" (alumnos en riesgo alto y
  cobros vencidos), tarjeta de clase de hoy con CTA a todo el ancho y
  estado vacío de cobros que lleva a vincular Mercado Pago.
- Riesgo: la inactividad se mide desde la última presencia hasta la última
  clase faltada, no contra hoy; un grupo sin clases registradas ya no pone
  a todos sus miembros en riesgo alto.
- Tarjeta de grupo: el aviso usa el motivo real ("12 días sin venir") en
  vez de "0 faltas".
- Días del horario en orden de calendario (sortWeekDays).
- Toast por encima del BottomNav en mobile; ficha de alumno sin flecha de
  volver en mobile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:18:18 -03:00
Jose Selesan
9617447e05 feat(billing): proveedores intercambiables (Mercado Pago en AR, Stripe en el resto)
- Puerto BillingProvider con adaptadores de Mercado Pago (/preapproval) y
  Stripe (Checkout en modo suscripción, fetch plano). El país elige proveedor
  solo para suscripciones nuevas; sync, cancel y webhook usan row.provider.
- Migración add_billing_providers (provider, checkout_ref, ids genéricos).
- fix: /authorized_payments/search respondía 400 "Invalid value for limit";
  se pagina por offset sin limit.
- fix: si falla la consulta de cobros, la sync guarda igual el estado de la
  suscripción (ya no queda PENDING tras autorizar) y reintenta los cobros.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:01:07 -03:00
Jose Selesan
cd82a1e549 feat: add subscription plans. Add admin panel. Add password recovery 2026-10-24 18:31:55 -03:00
Jose Selesan
f5e77c99f6 feat(billing): planes Free/Pro con Suscripciones de Mercado Pago
- Módulo billing: suscripción Pro mensual vía /preapproval con credenciales
  de plataforma por país, webhook firmado y reconciliación por polling.
- PlanGuard en los use-cases que crean grupos/alumnos, cobran con MP o
  activan automatizaciones (402 plan_limit_reached / plan_feature_required /
  plan_read_only), detrás de BILLING_ENFORCEMENT.
- Onboarding: paso Plan obligatorio (POST /onboarding/plan); con Free se
  saltean Cobros y WhatsApp.
- Web: pantalla /billing, aviso de Pro desde el MutationCache.
- Migración billing_subscriptions y docs/billing.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:49:27 -03:00
Jose Selesan
f4d2c26e29 feat(whatsapp): vincular con el número de teléfono además del QR
Desde el teléfono no se puede escanear el QR de la propia pantalla. Con
OpenWA el profesor ahora puede escribir su número y recibir un código de
8 caracteres para ingresar en WhatsApp (POST /whatsapp/connect/pairing-code).
En mobile el modal arranca por el número y en desktop por el QR.

- Puerto: requestPairingCode opcional (Kapso no lo implementa).
- OpenWA: reintenta el 409 mientras la sesión arranca.
- Número normalizado con el país del profesor (toWhatsappE164).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:15:02 -03:00
Jose Selesan
bef4056f8e fix(web): distinguir WhatsApp no configurado de otros errores de estado
Ajustes y el paso del onboarding mostraban "no está disponible" ante
cualquier fallo de GET /whatsapp/status. Ahora solo un 503 da ese
mensaje; el resto muestra el código del error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:02:14 -03:00
Jose Selesan
2467ebc0f6 chore(whatsapp): sacar OpenWA del docker-compose
OpenWA se instala por separado: la API le habla por OPENWA_API_URL (sin
default). La guía documenta el compose recomendado y el alta de la key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:34:53 -03:00
Jose Selesan
ec65c2198d feat(whatsapp): mensajes automáticos semanales con proveedor intercambiable
- Puerto MessagingProvider con adaptadores OpenWA (MVP, QR) y Kapso
  (setup link de Meta + templates), elegido con WHATSAPP_PROVIDER.
- Vinculación del WhatsApp del profesor en el onboarding y en Ajustes.
- Job semanal (lunes 10:00 AR): recordatorio de pago y reenganche a
  alumnos en riesgo (cooldown 14 días), con switches por grupo.
- Idempotencia por (kind, attendee, semana ISO), webhooks firmados con
  HMAC y deduplicados, normalización de teléfonos a E.164.
- Servicio openwa en docker-compose y guía en docs/whatsapp.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 08:38:09 -03:00
Jose Selesan
8c5caecdda feat: add country selection during onboarding and implement payment management features
- Introduced CountryStep component for selecting the country during onboarding, affecting payment currency.
- Updated FirstGroupStep to include country information.
- Enhanced PaymentsProvider to manage payment states and renewals.
- Created PaymentRow component for displaying individual payment details.
- Implemented PaymentsView for listing and filtering payments by group and status.
- Added API endpoints for fetching and creating payments, including batch processing.
- Defined payment schemas for validation and data handling.
- Updated GroupHeader and GroupDetailView to include charging functionality for group members.
2026-10-08 11:42:13 -03:00
b11dd47534 Merge pull request 'feat(mp): add Mercado Pago reauthorization notice and status card components' (#10) from feat/add-mercado-pago into development
Reviewed-on: #10
2026-10-07 15:03:36 +00:00
Jose Selesan
21a4c69f38 feat(mp): add Mercado Pago reauthorization notice and status card components
- Implemented MpReauthNotice component to notify users when reauthorization is needed.
- Created MpStatusCard component to display the current status of the Mercado Pago account.
- Added utility functions and constants for handling Mercado Pago status and messages.
- Introduced hooks for managing the connection and disconnection of Mercado Pago accounts.
- Developed a disconnect confirmation modal for user actions.
- Added tests for the new functionality and utility functions.
- Defined schemas for Mercado Pago account status and callback reasons in shared package.
2026-10-07 12:00:38 -03:00
458 changed files with 31520 additions and 2302 deletions

View File

@@ -35,6 +35,46 @@ BETTER_AUTH_SECRET=""
# EMAIL_SERVER_PASSWORD="" # EMAIL_SERVER_PASSWORD=""
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>" # EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
# Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales
# GET /mp/connect responde 503 mp_not_configured y la app sigue funcionando
# (el paso "Cobros" del onboarding es salteable).
# Generate it with: openssl rand -base64 32 -- exactly 32 bytes once decoded.
# TOKEN_ENCRYPTION_KEY=""
# Redirect URL registered in the Mercado Pago panel, character for character.
# The panel requires HTTPS (no http://localhost): local dev goes through a tunnel.
# MP_REDIRECT_URI="https://api.gruperly.com/api/v1/mp/callback"
# MP_CLIENT_ID=""
# MP_CLIENT_SECRET=""
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md).
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra
# entre países). No son las del OAuth del profesor. Un país sin las dos queda
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY.
# MP_PLATFORM_ACCESS_TOKEN_AR=""
# MP_PLATFORM_WEBHOOK_SECRET_AR=""
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
# BILLING_ENFORCEMENT="off"
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
# BILLING_GRACE_DAYS="7"
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
# whatsapp_not_configured y el paso del onboarding es salteable.
# WHATSAPP_PROVIDER="openwa" # openwa (MVP) | kapso
# WHATSAPP_SEND_INTERVAL_MS="5000" # pausa entre envios del mismo profesor
#
# OpenWA (se instala aparte, fuera de este compose).
# OPENWA_API_URL="https://openwa.example.com/api"
# OPENWA_API_KEY="" # key OPERATOR, sin allowedSessions
# OPENWA_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/openwa"
# OPENWA_WEBHOOK_SECRET="" # 16+ caracteres: openssl rand -hex 24
#
# Kapso (API oficial de WhatsApp Cloud).
# KAPSO_API_KEY=""
# KAPSO_CALLBACK_URL="https://app.gruperly.com/api/v1/whatsapp/callback"
# KAPSO_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/kapso"
# KAPSO_WEBHOOK_SECRET="" # el mismo del project webhook de Kapso
# Only if you want the API on another domain: it is baked into the Vite bundle # Only if you want the API on another domain: it is baked into the Vite bundle
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same # and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
# origin (recommended). # origin (recommended).

View File

@@ -31,18 +31,51 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`. - `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
- `src/logger.ts` — pino + pino-pretty. - `src/logger.ts` — pino + pino-pretty.
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`). - `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`. - `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete). - `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
## Gotchas operativos ## Gotchas operativos
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`. - **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness. - **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
4. La idempotencia de los envíos es el `@@unique([kind, attendeeId, periodKey])` de `outbound_messages` (semana ISO): la fila se crea **antes** de llamar al proveedor y su id es el `Idempotency-Key`.
5. Los teléfonos se guardan en formato nacional: el envío pasa por `toWhatsappE164` (shared) con el país del profesor.
6. Sin SDK de Kapso (trae su propio zod): `fetch` plano.
7. El sandbox de Kapso no soporta templates.
8. OpenWA se instala **aparte** (no está en `docker-compose.yml`); la API le habla por `OPENWA_API_URL`. Su guard SSRF rechaza webhooks a hosts internos que no estén en `SSRF_ALLOWED_HOSTS`.
9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`.
10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos.
11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`.
- **Billing (`modules/billing/`)**: es lo que el **profesor le paga a Gruperly** (Pro mensual), no lo que pagan los alumnos. Ojo con esto:
1. Proveedor intercambiable detrás del puerto `BillingProvider` (`providers/billing-provider.ts`, mismo patrón que WhatsApp): Mercado Pago (`/preapproval`) en **AR** y Stripe (Checkout en modo suscripción, `fetch` plano sin SDK) en el resto; el mapa es `BILLING_PROVIDER_BY_COUNTRY` (shared). Los use-cases, `SyncSubscription` y el job **nunca** importan un adaptador: piden `getBillingProvider(id)` (inyectable como `providers` en `deps`). El país elige proveedor solo para suscripciones **nuevas**: sync/cancel/webhook usan siempre `row.provider`. MP usa credenciales **de plataforma por país** (`MP_PLATFORM_ACCESS_TOKEN_<CC>`, nunca `getMpAccessToken`); Stripe, una sola cuenta (`STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET`) que cobra en la moneda local (CLP es zero-decimal). Sin credenciales: `503 billing_not_available`. Con Stripe la suscripción no existe hasta completar el checkout: la fila guarda `checkoutRef` (la session) y la sync completa `externalId`.
2. Los límites (`PLAN_LIMITS` en shared) se miden contra el **dueño del grupo** (`group.createdById`), con `PlanGuard` inyectado en el `constructor(deps)` de los use-cases (`canCreateGroup`, `canAddAttendees`, `requireFeature`). Un use-case nuevo que cree grupos/alumnos, cobre con MP o active automatizaciones tiene que pasar por el guard.
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.
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.
- **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:
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.
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`.
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**.
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).
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`).
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`.
- `.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
@@ -53,13 +86,14 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- **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`).
- **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`). - **Router ES file-based** (TanStack Router + `@tanstack/router-plugin`): las rutas viven en `apps/web/src/routes/` y solo contienen definiciones (`createFileRoute` + `component`), sin lógica de UI. `src/router.tsx` solo crea el router con el `routeTree` importado de `src/routeTree.gen.ts` (**archivo generado por el plugin en build/dev, versionado en git**: si agregás/renombrás una ruta, corré `bun --filter @gruperly/web build` para regenerarlo). Las rutas autenticadas cuelgan del layout pathless `_authenticated.tsx` (`AppLayoutGuard` + `RootLayout` con `<Outlet />`).
- **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado. - **Vistas en `apps/web/src/features/<feature>/`**: un componente por archivo, nombre de archivo en PascalCase igual al componente, imports relativos (sin alias). El estado compartido padre-hijo vive en un `*Provider.tsx` del feature (contexto + queries/mutations de React Query) que se monta en el route file; los componentes hijos consumen `use<Feature>()` y las forms locales mantienen su propio estado.
- **Grupos y "Requiere atención"** comparten la query `['attention']` (`features/attention/queries.ts`): el "Resuelto" es optimista sobre ese caché y por eso los contadores de Grupos se mueven sin refetch. El "Nuevo grupo" de Grupos es un FAB (`NewGroupFab`, se pliega al scrollear con `useCollapseOnScroll`) y por eso los toasts en mobile van a `bottom-[calc(9rem+…)]`. Los colores de gravedad son tokens (`alert-urgent-*`, `alert-watch-*`, `free-fg`) definidos para claro y oscuro en `index.css`.
- Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista. - Nav (Inicio/Grupos/Cobros/Ajustes) vive en `apps/web/src/components/layout/nav-items.ts`; es la fuente única para `BottomNav` (móvil) y `Sidebar` (desktop) — no dupliques la lista.
- **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos. - **Rutas immersive (Large Title)**: la ficha de grupo, sus estadísticas y la asistencia arman su propia barra de título (`components/layout/LargeTitle.tsx`) en vez del header global. La lista está en `apps/web/src/lib/immersive-routes.ts` (`isImmersiveRoute`, con test) y la consulta `RootLayout`: si el pathname matchea, no se renderiza `<Header />`, `<main>` va `pt-0` y el `Sidebar` pasa a `top-0 h-dvh`. Ojo con dos cosas: (1) un `sticky` solo se pega mientras su **caja padre** esté en pantalla, así que la barra no puede colgar del bloque del feature (se despegaría a los ~200px): se monta por portal en `ImmersiveBarHost`, una caja `h-14` que el layout pone de primer hijo de `<main>`. (2) el colapso va ligado al scroll (pos del `h1` en cada frame), no a una transición CSS, y el estado vive dentro de `LargeTitle` para que `children` no se re-renderice en cada frame. Para sumar una pantalla: registrar el path en `immersive-routes.ts` y usar `<LargeTitle>`; nada más. En las tres pantallas el `<h1>` se renderiza siempre, incluso en estado de carga o error: es lo que le da altura a la barra y evita que el layout salte cuando llegan los datos.
- **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos. - **UI**: primitivos propios en `apps/web/src/components/ui/` (avatar, button, badge) más helper `cn()` en `src/lib/utils.ts` (clsx + tailwind-merge). Aunque `stack.md` mencione Shadcn, **todavía no está instalado** (sin Radix); úsalos directos.
- **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición. - **Foco al abrir formularios**: siempre que una acción muestre o monte un formulario, el primer campo editable debe recibir el foco automáticamente. Preferí `autoFocus` cuando el formulario aparece por render condicional; si permanece montado u otro flujo lo impide, usá un `ref` con foco explícito al activar la edición.
- Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`. - Layout mobile-first: `RootLayout` usa columna `max-w-md` en móvil y dos columnas (Sidebar + contenido `max-w-6xl`) en `lg+`.
- **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa. - **Safe areas (iOS standalone)**: `index.html` lleva `viewport-fit=cover`; todo elemento fijo pegado al borde inferior (hoy `BottomNav`) necesita `env(safe-area-inset-bottom)` en su padding, y el `pb` del `<main>` en `RootLayout` lo suma (`pb-[calc(6rem+env(safe-area-inset-bottom))]`). Si agregás otro elemento fijo abajo, seguí el mismo patrón o el home indicator lo tapa.
- **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen. - **Sin "volver atrás" en mobile**: en ninguna vista se muestra un link/botón de navegación a la página anterior cuando se ve en mobile (se apoya en el gesto de back del dispositivo). **Excepción**: `/groups/attention` ("Requiere atención", sin entrada en el nav) muestra su botón Volver también en mobile. Los links de "volver" solo en desktop: usar `hidden ... lg:inline-flex` (p. ej. `create-group`, `group-detail`) o `hidden lg:flex` (`Breadcrumb`). No confundir con botones "Volver" de pasos dentro de un wizard/formulario: esos sí se mantienen.
## Fuentes de contexto ## Fuentes de contexto

110
README.md
View File

@@ -67,6 +67,113 @@ En DevTools → Application: el manifest sin warnings, el service worker `activa
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`. 1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo). 2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
## Mercado Pago (OAuth)
Los cobros llegan a la cuenta del profesor a través de una app de Mercado Pago en modo directo: el profesor autoriza desde el panel de MP y los pagos entran en su propia cuenta, sin comisión ni split de plataforma (`platform_id=mp`). El OAuth vive en `apps/backend/src/modules/mp/`; los links de pago y la reconciliación están en `modules/payments/` (ver [Cobros](#cobros-links-de-pago)).
**Panel de Mercado Pago** (Developer panel → Tu aplicación):
- **Redirect URL**: el panel la exige en **HTTPS** (rechaza `http://localhost`) y tiene que coincidir carácter por carácter con `MP_REDIRECT_URI`. En local, meté un túnel delante del backend y registrá esa URL HTTPS tanto en el panel como en la env var: `ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000` (el *dev domain* de ngrok es fijo por cuenta, gratis) o un túnel nombrado de Cloudflare (`cloudflared tunnel route dns …`). `WEB_URL` y `VITE_API_URL` siguen en localhost: el túnel solo lo usa el navegador para volver desde MP. Los *quick tunnels* de cloudflared generan una URL nueva en cada arranque, así que obligan a regenerar la URL en el panel y en la env var cada reinicio.
- **PKCE (S256)**: activado. El `code_verifier` se genera y se consume en el servidor, nunca pasa por el navegador.
- **Permisos**: `offline_access read write`. Sin `offline_access` Mercado Pago no devuelve *refresh token* y la renovación automática no tiene con qué trabajar.
**Variables de entorno** (`apps/backend/.env` en local, pestaña Environment del compose en Dokploy):
| Variable | ¿Obligatoria? | Descripción |
| --- | --- | --- |
| `MP_CLIENT_ID` | para vincular | Client ID de la app de MP |
| `MP_CLIENT_SECRET` | para vincular | Secret de la app de MP |
| `MP_REDIRECT_URI` | para vincular | Callback registrado en el panel |
| `TOKEN_ENCRYPTION_KEY` | para vincular | `openssl rand -base64 32`. Cifra los tokens en reposo con AES-256-GCM. Si no decodifica a 32 bytes, el backend lo rechaza al guardar la cuenta |
Sin las cuatro, `GET /api/v1/mp/connect` responde `503 mp_not_configured` y la app sigue funcionando: el paso "Cobros" del onboarding es **salteable**.
En local se usan las credenciales de **producción** de la app: no existe OAuth sandbox en MP (las credenciales de prueba del panel son solo Public Key y Access Token, sin Client ID/secret). No hay riesgo, porque el OAuth solo vincula una cuenta y no mueve dinero; se prueba con una cuenta propia y se desvincúa con `DELETE /mp/connect`. Los links de pago también se prueban con la cuenta propia (crear un link no cobra nada; el cobro real le pide credenciales de pago al alumno).
### Cómo funciona
```text
onboarding/ajustes → GET /mp/connect → { authorizationUrl } (state + PKCE en la DB, 10 min)
→ https://auth.mercadopago.com/authorization
→ GET /mp/callback → ?code&state (se quema el state, se cambia el código)
→ 302 a /onboarding?mp=success o /settings?mp=error&reason=…
```
- La API de MP es `GET /mp/status` (`none` | `active` | `requires_reauth`) y `DELETE /mp/connect` (desvincula; conserva la fila para que la cuenta de MP quede reservada al mismo profesor).
- Los tokens se guardan cifrados; `status` nunca devuelve tokens, scope ni el id completo de MP (solo los últimos 4 dígitos, para que el profesor confirme que vinculó la cuenta correcta).
- Un cron diario (`17 3 * * *` UTC) renueva las cuentas que vencen en menos de 30 días, en lotes de 20 con `FOR UPDATE SKIP LOCKED`. Solo `invalid_grant` marca la cuenta como `requires_reauth`; un 5xx o un fallo de red se reintenta al día siguiente, para no bloquear a un profesor por una tarde mala de MP. `apps/backend/src/modules/mp/access-token.ts` (`getMpAccessToken`) renueva bajo demanda si el token está por vencer.
### Verificar a mano
1. `bun dev`, crear una cuenta nueva y llegar al paso "Cobros".
2. **Vincular**: "Vincular cuenta" debe abrir el consent de MP; al aceptar se vuelve a `/onboarding` con el mensaje de cuenta vinculada, y Ajustes → Cobros muestra "Vinculada" con los últimos 4 dígitos.
3. **Saltear**: con una cuenta nueva, "Lo hago después" deja crear el grupo igual; el resumen final ofrece vincularlo después desde Ajustes.
4. **Denegar**: en la pantalla de consentimiento de MP, elegir no autorizar → vuelve con "No autorizaste la conexión en Mercado Pago" y el estado sigue en `none`.
5. **Desvincular**: Ajustes → Cobros → Desvincular (pide confirmación) deja el estado en `none` y la tarjeta de cuenta conectada desaparece.
6. **Reautenticación**: `UPDATE users SET ...` no hace falta; para forzarla, `UPDATE mp_accounts SET status = 'REQUIRES_REAUTH'` y recargar cualquier pantalla: aparece el aviso global (excepto en Ajustes, donde la tarjeta ofrece la acción).
```bash
# Estado real, con la sesión del profesor:
curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: <cookie de sesión>' | jq
```
## Cobros (links de pago)
Un cobro es un **link de pago de Checkout Pro por alumno y por período**. El profesor lo dispara desde la ficha del grupo (**Cobrar**, habilitado cuando el grupo tiene precio): se crea un `Payment` por cada asistente activo y, para cada uno, una preferencia de Checkout Pro con `external_reference` = id del pago. Crear un link no cobra nada; el cobro real lo paga el alumno desde el link.
La moneda sale del país del profesor (`user.country`, elegido en el onboarding; default `AR` → `ARS`): `AR→ARS, BR→BRL, CL→CLP, CO→COP, MX→MXN, PE→PEN, UY→UYU`.
**Endpoints** (todos requieren sesión; solo grupos propios o donde el profesor es miembro):
| Endpoint | Qué hace |
| --- | --- |
| `POST /api/v1/groups/:groupId/payments/batch` | Crea el lote. Body: `{ dueDate, description?, attendeeIds? }`. Responde `201` con `{ total, linked, failed, items }`; cada item es `LINKED` (trae `checkoutUrl`) o `FAILED` (error del proveedor, la fila queda `PENDING` sin link) |
| `POST /api/v1/payments/:id/renew` | Regenera el link de un pago que lo perdió (item `FAILED`). Idempotente: si ya tiene link, lo devuelve tal cual |
| `GET /api/v1/payments?groupId&status&page&pageSize` | Lista paginada `{ data, pagination }` de los cobros visibles |
**Estados**: `PENDING` (esperando pago) → `PAID` (aprobado en MP) | `OVERDUE` (venció + 24 h de gracia y sigue sin pagar; sigue siendo cobrable) | `CANCELLED` (reservado, hoy no se usa).
**Reconciliación, sin webhook.** El MVP consolida por polling porque un webhook exige una URL pública y verificación de firma, y no aporta nada a esta escala: un cron cada 15 min consulta la API de MP por `external_reference`, y si el pago está `approved` marca el `Payment` como `PAID` (guarda `mpPaymentId` y `paidAt`). Solo toca pagos con link y de más de 5 min de antigüedad, en lotes de 50. Un cron diario (`4 4 * * *` UTC) convierte en `OVERDUE` los `PENDING` cuya fecha venció hace más de 24 h. Los anuncian en el log (`startPaymentJobs()` en `apps/backend/src/server.ts`).
**En la web**: la vista **Cobros** (nav) filtra por grupo y estado y deja copiar el link o regenerarlo con "Generar link" (botón renovar). Del modal **Cobrar** en la ficha del grupo se eligen vencimiento y descripción (default: mes en mayúscula) y se muestra un link por alumno para copiar, con los que fallaron listos para reintentar.
**Errores típicos**: `409 group_without_price` (el grupo no tiene precio definido), `409 no_attendees_to_bill` (sin alumnos activos), `409 mp_not_connected` (el dueño desvinculó MP), `503 mp_not_configured` (faltan las env vars del OAuth).
### Verificar a mano (además del flujo de OAuth)
1. Con un grupo con precio y alumnos, "Cobrar" → elegir vencimiento → los links se generan uno por alumno.
2. En **Cobros** el grupo aparece con `PENDING` por alumno; "Copiar" pega un link `https://www.mercadopago.com.ar/checkout/v1/…`.
3. Abrir el link, pagar (puede fallar si el teste es con la cuenta real: probar el "sandbox de pago" del panel si existe) y esperar la reconciliación (hasta 15 min) o correr el job a mano.
4. Un pago aprobado pasa a `PAID`; uno cuyo vencimiento pasó (con +24 h) pasa a `OVERDUE` y permite regenerar el link.
## WhatsApp (recordatorios y reenganche)
Una vez por semana (lunes 10:00, hora de Argentina) Gruperly le escribe por WhatsApp, **desde el número del profesor**, a los miembros de los grupos que tengan la automatización prendida:
- **Recordatorio de pago**: cobros `PENDING`/`OVERDUE` con link que vencen en los próximos 7 días o ya vencieron.
- **Reenganche**: los mismos que muestra "Alumnos en riesgo", como mucho uno cada 14 días.
Las dos se prenden por grupo (ficha del grupo → "Mensajes automáticos por WhatsApp") y vienen apagadas. El profesor vincula su número en el onboarding (paso "WhatsApp", salteable) o en Ajustes → WhatsApp.
El envío pasa por un proveedor intercambiable (`WHATSAPP_PROVIDER`):
- **`openwa`** (MVP, default): gateway self-hosted. El profesor lo vincula escaneando un QR o, desde el teléfono, con un código para su número; los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número.
- **`kapso`**: API oficial de Meta. La vinculación es un setup link y los mensajes usan templates aprobados.
El código vive en `apps/backend/src/modules/whatsapp/`.
| Variable | ¿Obligatoria? | Descripción |
| --- | --- | --- |
| `WHATSAPP_PROVIDER` | no | `openwa` (default) o `kapso` |
| `OPENWA_API_URL`, `OPENWA_API_KEY` | con OpenWA | URL de la API de OpenWA y una key OPERATOR |
| `OPENWA_WEBHOOK_URL`, `OPENWA_WEBHOOK_SECRET` | no | Confirmaciones de entrega y lectura. El secreto es obligatorio si hay URL |
| `KAPSO_API_KEY`, `KAPSO_CALLBACK_URL`, `KAPSO_WEBHOOK_URL`, `KAPSO_WEBHOOK_SECRET` | con Kapso | Ver la guía |
| `WHATSAPP_SEND_INTERVAL_MS` | no | Pausa entre envíos del mismo profesor. Default `5000` |
Si faltan las variables del proveedor activo, `/whatsapp/*` responde `503 whatsapp_not_configured` y la app sigue funcionando.
La guía completa está en **[docs/whatsapp.md](docs/whatsapp.md)**: arquitectura, deploy de OpenWA y primera API key, setup de Kapso y templates, riesgos, verificación a mano, troubleshooting y una guía para el profesor.
## Deploy en producción (Docker / Dokploy) ## Deploy en producción (Docker / Dokploy)
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx). Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
@@ -87,6 +194,9 @@ El compose las interpola desde el entorno. En Dokploy van en la pestaña **Envir
| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` | | `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` |
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider | | `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider |
| `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) | | `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) |
| `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI` | no | Vinculación con Mercado Pago. Sin ellos, `/mp/connect` responde 503 y la app anda igual (ver [Mercado Pago](#mercadopago-oauth)) |
| `TOKEN_ENCRYPTION_KEY` | no (sí para cobrar) | `openssl rand -base64 32`. Cifra los tokens de MP en reposo |
| `WHATSAPP_PROVIDER`, `OPENWA_*`, `KAPSO_*`, `WHATSAPP_SEND_INTERVAL_MS` | no | Mensajes automáticos por WhatsApp (ver [WhatsApp](#whatsapp-recordatorios-y-reenganche)). OpenWA no está en el compose: se instala aparte y la API le habla por `OPENWA_API_URL` |
| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio | | `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio |
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones | | `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |

View File

@@ -18,4 +18,79 @@ EMAIL_SERVER_HOST=""
EMAIL_SERVER_PORT="587" EMAIL_SERVER_PORT="587"
EMAIL_SERVER_USER="" EMAIL_SERVER_USER=""
EMAIL_SERVER_PASSWORD="" EMAIL_SERVER_PASSWORD=""
EMAIL_FROM="Gruperly <no-reply@gruperly.com>" EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
# Mercado Pago (OAuth, Authorization Code + PKCE)
MP_CLIENT_ID=""
MP_CLIENT_SECRET=""
# Debe coincidir exactamente con la "Redirect URL" de la app en el panel de MP.
# El panel exige HTTPS (rechaza http://localhost): en local usá un túnel
# (p. ej. ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000) y cargá
# la URL del túnel acá y en el panel.
MP_REDIRECT_URI=""
# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM).
# Generar con: openssl rand -base64 32
TOKEN_ENCRYPTION_KEY=""
# Suscripción a Gruperly Pro (ver docs/billing.md). Argentina la cobra con
# Suscripciones de Mercado Pago; el resto de los países, con Stripe.
# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina (no
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
MP_PLATFORM_ACCESS_TOKEN_AR=""
MP_PLATFORM_WEBHOOK_SECRET_AR=""
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
STRIPE_SECRET_KEY=""
STRIPE_WEBHOOK_SECRET=""
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
BILLING_ENFORCEMENT="off"
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
BILLING_GRACE_DAYS="7"
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
ADMIN_EMAILS=""
# WhatsApp: recordatorios de pago y reenganche semanales (ver docs/whatsapp.md).
# Proveedor: openwa (MVP, gateway self-hosted con QR) | kapso (API oficial de Meta).
WHATSAPP_PROVIDER="openwa"
# Pausa entre dos envíos del mismo profesor, en ms (OpenWA recomienda < 15 msg/min).
WHATSAPP_SEND_INTERVAL_MS="5000"
# OpenWA (se instala aparte). En local: docker run, ver docs/whatsapp.md.
OPENWA_API_URL="http://localhost:2785/api"
# Key OPERATOR sin allowedSessions, creada con la key ADMIN de /app/data/.api-key.
OPENWA_API_KEY=""
# Opcional. Sin webhook la vinculación funciona (el status hace polling), pero no
# llegan las confirmaciones de entrega/lectura. Si lo cargás, el secreto es obligatorio.
OPENWA_WEBHOOK_URL=""
# 16+ caracteres. Generar con: openssl rand -hex 24
OPENWA_WEBHOOK_SECRET=""
# Kapso (WHATSAPP_PROVIDER="kapso"). Las URLs tienen que ser públicas (túnel en local).
KAPSO_API_KEY=""
KAPSO_CALLBACK_URL=""
KAPSO_WEBHOOK_URL=""
# El mismo secreto del project webhook configurado en el dashboard de Kapso.
KAPSO_WEBHOOK_SECRET=""
# KAPSO_API_URL="https://api.kapso.ai"
# App de alumnos (acceso sin contraseña por link de un solo uso; ver AGENTS.md).
# Comprobantes de pago: storage privado compatible con S3 (RustFS, MinIO, R2, AWS).
# Sin estas cuatro variables, "Informar pago" responde 503 storage_not_available.
S3_ENDPOINT="http://localhost:9000"
S3_BUCKET="gruperly-receipts"
S3_ACCESS_KEY_ID=""
S3_SECRET_ACCESS_KEY=""
S3_REGION="us-east-1"
# on = URLs estilo AWS (bucket.endpoint). RustFS/MinIO usan path-style: dejalo vacío.
S3_VIRTUAL_HOSTED=""
# Días que se guarda un comprobante después de que el profe lo revisó. 0 = para siempre.
RECEIPT_RETENTION_DAYS="0"
# WebAuthn (Face ID / huella del alumno). Por defecto salen de WEB_URL; cambialos
# solo si la web se sirve desde otro origen (p. ej. un túnel para probar en el teléfono).
# WEBAUTHN_RP_ID="localhost"
# WEBAUTHN_ORIGIN="http://localhost:6173"
# Proxies delante de la API que agregan X-Forwarded-For (1 = solo nginx; 2 = Traefik + nginx).
# Define qué IP cuenta para el rate limit de "Pedir un link a mi mail".
TRUSTED_PROXY_HOPS="1"

View File

@@ -9,6 +9,7 @@
"build": "prisma generate && tsc", "build": "prisma generate && tsc",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "bun test", "test": "bun test",
"test:db": "DB_TESTS=1 bun test test/db",
"test:watch": "bun test --watch", "test:watch": "bun test --watch",
"lint": "biome check .", "lint": "biome check .",
"lint:fix": "biome check . --write", "lint:fix": "biome check . --write",
@@ -23,6 +24,7 @@
"@gruperly/shared": "workspace:*", "@gruperly/shared": "workspace:*",
"@prisma/adapter-pg": "^7.10.0", "@prisma/adapter-pg": "^7.10.0",
"@prisma/client": "^7.10.0", "@prisma/client": "^7.10.0",
"@simplewebauthn/server": "13.3.3",
"better-auth": "1.7.2", "better-auth": "1.7.2",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"hono": "^4.13.3", "hono": "^4.13.3",

View File

@@ -0,0 +1,56 @@
-- Mercado Pago OAuth (Authorization Code + PKCE). Replaces the simulated
-- payment setup, where a fake access token was stored in plaintext.
-- CreateEnum
CREATE TYPE "MpAccountStatus" AS ENUM ('ACTIVE', 'REQUIRES_REAUTH', 'REVOKED');
-- CreateTable
CREATE TABLE "mp_accounts" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"mp_user_id" TEXT NOT NULL,
"access_token_enc" TEXT NOT NULL,
"refresh_token_enc" TEXT NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"scope" TEXT,
"live_mode" BOOLEAN NOT NULL DEFAULT false,
"status" "MpAccountStatus" NOT NULL DEFAULT 'ACTIVE',
"connected_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "mp_accounts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "mp_oauth_states" (
"state" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"code_verifier" TEXT NOT NULL,
"return_to" TEXT NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "mp_oauth_states_pkey" PRIMARY KEY ("state")
);
-- CreateIndex
CREATE INDEX "mp_accounts_status_expiresAt_idx" ON "mp_accounts"("status", "expires_at");
-- CreateIndex
CREATE UNIQUE INDEX "mp_accounts_ownerId_key" ON "mp_accounts"("owner_id");
-- CreateIndex
CREATE UNIQUE INDEX "mp_accounts_mpUserId_key" ON "mp_accounts"("mp_user_id");
-- CreateIndex
CREATE INDEX "mp_oauth_states_expiresAt_idx" ON "mp_oauth_states"("expires_at");
-- AddForeignKey
ALTER TABLE "mp_accounts" ADD CONSTRAINT "mp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- DropTable
DROP TABLE "merchant_accounts";
-- DropEnum
DROP TYPE "PaymentProvider";

View File

@@ -0,0 +1,13 @@
-- Country of the professor (onboarding) + Mercado Pago Checkout Pro payment links.
-- AlterTable (users)
ALTER TABLE "users" ADD COLUMN "country_code" TEXT;
-- AlterTable (payments)
ALTER TABLE "payments" ADD COLUMN "description" TEXT;
ALTER TABLE "payments" ADD COLUMN "checkout_url" TEXT;
ALTER TABLE "payments" ADD COLUMN "mp_preference_id" TEXT;
ALTER TABLE "payments" ADD COLUMN "mp_payment_id" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "payments_mp_preference_id_key" ON "payments"("mp_preference_id");

View File

@@ -0,0 +1,129 @@
-- WhatsApp messaging: linked accounts (provider-agnostic), Kapso templates,
-- outbound message log and webhook dedupe; plus the per-group automation switches.
-- CreateEnum
CREATE TYPE "MessagingProviderId" AS ENUM ('OPENWA', 'KAPSO');
-- CreateEnum
CREATE TYPE "WhatsappAccountStatus" AS ENUM ('PENDING', 'ACTIVE', 'DISCONNECTED');
-- CreateEnum
CREATE TYPE "WhatsappMessageKind" AS ENUM ('PAYMENT_REMINDER', 'REENGAGEMENT');
-- CreateEnum
CREATE TYPE "OutboundMessageStatus" AS ENUM ('QUEUED', 'SENT', 'DELIVERED', 'READ', 'FAILED', 'SKIPPED');
-- CreateEnum
CREATE TYPE "WhatsappTemplateStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'DISABLED');
-- AlterTable
ALTER TABLE "groups" ADD COLUMN "auto_payment_reminders" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "auto_reengagement" BOOLEAN NOT NULL DEFAULT false;
-- AlterTable (pre-existing drift: the schema already declares this default)
ALTER TABLE "payments" ALTER COLUMN "currency" SET DEFAULT 'ARS';
-- CreateTable
CREATE TABLE "whatsapp_accounts" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"provider" "MessagingProviderId" NOT NULL,
"status" "WhatsappAccountStatus" NOT NULL DEFAULT 'PENDING',
"external_id" TEXT,
"display_phone_number" TEXT,
"provider_data" JSONB,
"connected_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "whatsapp_accounts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "whatsapp_templates" (
"id" TEXT NOT NULL,
"account_id" TEXT NOT NULL,
"kind" "WhatsappMessageKind" NOT NULL,
"name" TEXT NOT NULL,
"language" TEXT NOT NULL,
"meta_template_id" TEXT,
"status" "WhatsappTemplateStatus" NOT NULL DEFAULT 'PENDING',
"rejected_reason" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "whatsapp_templates_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "outbound_messages" (
"id" TEXT NOT NULL,
"owner_id" TEXT NOT NULL,
"group_id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"payment_id" TEXT,
"kind" "WhatsappMessageKind" NOT NULL,
"provider" "MessagingProviderId" NOT NULL,
"period_key" TEXT NOT NULL,
"to_phone" TEXT NOT NULL,
"provider_message_id" TEXT,
"status" "OutboundMessageStatus" NOT NULL DEFAULT 'QUEUED',
"error_code" TEXT,
"error_message" TEXT,
"sent_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "outbound_messages_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "whatsapp_webhook_events" (
"provider" "MessagingProviderId" NOT NULL,
"dedupe_key" TEXT NOT NULL,
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "whatsapp_webhook_events_pkey" PRIMARY KEY ("provider","dedupe_key")
);
-- CreateIndex
CREATE UNIQUE INDEX "whatsapp_accounts_ownerId_key" ON "whatsapp_accounts"("owner_id");
-- CreateIndex
CREATE UNIQUE INDEX "whatsapp_accounts_provider_externalId_key" ON "whatsapp_accounts"("provider", "external_id");
-- CreateIndex
CREATE INDEX "whatsapp_templates_status_idx" ON "whatsapp_templates"("status");
-- CreateIndex
CREATE UNIQUE INDEX "whatsapp_templates_accountId_kind_key" ON "whatsapp_templates"("account_id", "kind");
-- CreateIndex
CREATE INDEX "outbound_messages_attendeeId_kind_createdAt_idx" ON "outbound_messages"("attendee_id", "kind", "created_at");
-- CreateIndex
CREATE INDEX "outbound_messages_groupId_createdAt_idx" ON "outbound_messages"("group_id", "created_at");
-- CreateIndex
CREATE UNIQUE INDEX "outbound_messages_kind_attendeeId_periodKey_key" ON "outbound_messages"("kind", "attendee_id", "period_key");
-- CreateIndex
CREATE UNIQUE INDEX "outbound_messages_provider_providerMessageId_key" ON "outbound_messages"("provider", "provider_message_id");
-- CreateIndex
CREATE INDEX "whatsapp_webhook_events_receivedAt_idx" ON "whatsapp_webhook_events"("received_at");
-- AddForeignKey
ALTER TABLE "whatsapp_accounts" ADD CONSTRAINT "whatsapp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "whatsapp_templates" ADD CONSTRAINT "whatsapp_templates_accountId_fkey" FOREIGN KEY ("account_id") REFERENCES "whatsapp_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_groupId_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_attendeeId_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_paymentId_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@@ -0,0 +1,74 @@
-- CreateEnum
CREATE TYPE "SubscriptionStatus" AS ENUM ('PENDING', 'AUTHORIZED', 'PAUSED', 'CANCELLED');
-- AlterTable
ALTER TABLE "users" ADD COLUMN "plan_selected_at" TIMESTAMP(3);
-- CreateTable
CREATE TABLE "billing_subscriptions" (
"id" TEXT NOT NULL,
"user_id" TEXT NOT NULL,
"country_code" TEXT NOT NULL,
"currency" TEXT NOT NULL,
"amount" DECIMAL(12,2) NOT NULL,
"payer_email" TEXT NOT NULL,
"mp_preapproval_id" TEXT,
"status" "SubscriptionStatus" NOT NULL DEFAULT 'PENDING',
"requested_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"authorized_at" TIMESTAMP(3),
"next_payment_date" TIMESTAMP(3),
"paid_through" TIMESTAMP(3),
"last_synced_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "billing_subscriptions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "billing_charges" (
"id" TEXT NOT NULL,
"subscription_id" TEXT NOT NULL,
"mp_authorized_payment_id" TEXT NOT NULL,
"amount" DECIMAL(12,2) NOT NULL,
"currency" TEXT NOT NULL,
"status" TEXT NOT NULL,
"paid_at" TIMESTAMP(3),
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "billing_charges_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "billing_webhook_events" (
"country_code" TEXT NOT NULL,
"dedupe_key" TEXT NOT NULL,
"received_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "billing_webhook_events_pkey" PRIMARY KEY ("country_code","dedupe_key")
);
-- CreateIndex
CREATE UNIQUE INDEX "billing_subscriptions_userId_key" ON "billing_subscriptions"("user_id");
-- CreateIndex
CREATE UNIQUE INDEX "billing_subscriptions_mpPreapprovalId_key" ON "billing_subscriptions"("mp_preapproval_id");
-- CreateIndex
CREATE INDEX "billing_subscriptions_status_lastSyncedAt_idx" ON "billing_subscriptions"("status", "last_synced_at");
-- CreateIndex
CREATE UNIQUE INDEX "billing_charges_mpAuthorizedPaymentId_key" ON "billing_charges"("mp_authorized_payment_id");
-- CreateIndex
CREATE INDEX "billing_charges_subscriptionId_createdAt_idx" ON "billing_charges"("subscription_id", "created_at");
-- CreateIndex
CREATE INDEX "billing_webhook_events_receivedAt_idx" ON "billing_webhook_events"("received_at");
-- AddForeignKey
ALTER TABLE "billing_subscriptions" ADD CONSTRAINT "billing_subscriptions_userId_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "billing_charges" ADD CONSTRAINT "billing_charges_subscriptionId_fkey" FOREIGN KEY ("subscription_id") REFERENCES "billing_subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,26 @@
-- Pro billing behind a provider port: Mercado Pago (AR) or Stripe (the rest).
-- Columns are renamed, not dropped, so existing Mercado Pago rows keep their ids.
-- CreateEnum
CREATE TYPE "BillingProviderId" AS ENUM ('MERCADO_PAGO', 'STRIPE');
-- billing_subscriptions: provider + provider-neutral ids
ALTER TABLE "billing_subscriptions" ADD COLUMN "provider" "BillingProviderId" NOT NULL DEFAULT 'MERCADO_PAGO';
ALTER TABLE "billing_subscriptions" ADD COLUMN "checkout_ref" TEXT;
ALTER TABLE "billing_subscriptions" RENAME COLUMN "mp_preapproval_id" TO "external_id";
ALTER INDEX "billing_subscriptions_mpPreapprovalId_key" RENAME TO "billing_subscriptions_externalId_key";
CREATE UNIQUE INDEX "billing_subscriptions_checkoutRef_key" ON "billing_subscriptions"("checkout_ref");
-- billing_charges: provider-neutral id and normalized status
ALTER TABLE "billing_charges" RENAME COLUMN "mp_authorized_payment_id" TO "external_id";
ALTER INDEX "billing_charges_mpAuthorizedPaymentId_key" RENAME TO "billing_charges_externalId_key";
UPDATE "billing_charges"
SET "status" = CASE
WHEN "status" = 'approved' THEN 'approved'
WHEN "status" IN ('rejected', 'cancelled', 'refunded', 'charged_back') THEN 'rejected'
ELSE 'pending'
END;
-- billing_webhook_events: dedupe per sending account (`mp:<CC>` or `stripe`)
ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source";
UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source";

View File

@@ -0,0 +1,20 @@
-- CreateEnum
CREATE TYPE "StudentAlertKind" AS ENUM ('ATTENDANCE', 'PAYMENT');
-- CreateTable
CREATE TABLE "attendee_alert_resolutions" (
"id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"kind" "StudentAlertKind" NOT NULL,
"signature" TEXT NOT NULL,
"resolved_by_id" TEXT NOT NULL,
"resolved_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "attendee_alert_resolutions_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "attendee_alert_resolutions_attendee_id_kind_key" ON "attendee_alert_resolutions"("attendee_id", "kind");
-- AddForeignKey
ALTER TABLE "attendee_alert_resolutions" ADD CONSTRAINT "attendee_alert_resolutions_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -0,0 +1,248 @@
-- CreateEnum
CREATE TYPE "StudentTokenKind" AS ENUM ('INVITATION', 'RECOVERY', 'EMAIL_CONFIRMATION');
-- CreateEnum
CREATE TYPE "WebauthnChallengePurpose" AS ENUM ('REGISTER', 'LOGIN');
-- CreateEnum
CREATE TYPE "AbsenceReason" AS ENUM ('HEALTH', 'TRAVEL', 'WORK_STUDY', 'OTHER');
-- CreateEnum
CREATE TYPE "ReportedPaymentStatus" AS ENUM ('REPORTED', 'CONFIRMED', 'REJECTED');
-- AlterTable
ALTER TABLE "users" ADD COLUMN "transfer_alias" TEXT,
ADD COLUMN "transfer_holder" TEXT;
-- CreateTable
CREATE TABLE "student_accounts" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"recovery_email" TEXT,
"recovery_email_verified_at" TIMESTAMP(3),
"pending_recovery_email" TEXT,
"welcomed_at" TIMESTAMP(3),
"created_by_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "student_accounts_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "student_account_attendees" (
"account_id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "student_account_attendees_pkey" PRIMARY KEY ("account_id","attendee_id")
);
-- CreateTable
CREATE TABLE "student_access_tokens" (
"id" TEXT NOT NULL,
"token_hash" TEXT NOT NULL,
"account_id" TEXT NOT NULL,
"kind" "StudentTokenKind" NOT NULL,
"email" TEXT,
"expires_at" TIMESTAMP(3) NOT NULL,
"used_at" TIMESTAMP(3),
"revoked_at" TIMESTAMP(3),
"created_by_id" TEXT,
"used_ip" TEXT,
"used_user_agent" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "student_access_tokens_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "student_sessions" (
"id" TEXT NOT NULL,
"account_id" TEXT NOT NULL,
"token_hash" TEXT NOT NULL,
"device" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"last_used_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expires_at" TIMESTAMP(3) NOT NULL,
"revoked_at" TIMESTAMP(3),
CONSTRAINT "student_sessions_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "student_passkeys" (
"id" TEXT NOT NULL,
"account_id" TEXT NOT NULL,
"credential_id" TEXT NOT NULL,
"public_key" BYTEA NOT NULL,
"counter" INTEGER NOT NULL DEFAULT 0,
"transports" TEXT[],
"device" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"last_used_at" TIMESTAMP(3),
CONSTRAINT "student_passkeys_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "student_webauthn_challenges" (
"id" TEXT NOT NULL,
"challenge" TEXT NOT NULL,
"account_id" TEXT,
"purpose" "WebauthnChallengePurpose" NOT NULL,
"expires_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "student_webauthn_challenges_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "rate_limit_events" (
"id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "rate_limit_events_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "absence_notices" (
"id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"class_session_id" TEXT NOT NULL,
"account_id" TEXT,
"reason" "AbsenceReason",
"message" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"cancelled_at" TIMESTAMP(3),
CONSTRAINT "absence_notices_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "reported_payments" (
"id" TEXT NOT NULL,
"attendee_id" TEXT NOT NULL,
"group_id" TEXT NOT NULL,
"account_id" TEXT,
"total_amount" DECIMAL(10,2) NOT NULL,
"currency" TEXT NOT NULL,
"receipt_key" TEXT,
"receipt_mime" TEXT NOT NULL,
"receipt_name" TEXT NOT NULL,
"receipt_size" INTEGER NOT NULL,
"status" "ReportedPaymentStatus" NOT NULL DEFAULT 'REPORTED',
"reviewed_by_id" TEXT,
"reviewed_at" TIMESTAMP(3),
"rejection_reason" TEXT,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
CONSTRAINT "reported_payments_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "reported_payment_items" (
"reported_payment_id" TEXT NOT NULL,
"payment_id" TEXT NOT NULL,
CONSTRAINT "reported_payment_items_pkey" PRIMARY KEY ("reported_payment_id","payment_id")
);
-- CreateIndex
CREATE INDEX "student_accounts_recovery_email_idx" ON "student_accounts"("recovery_email");
-- CreateIndex
CREATE INDEX "student_accounts_created_by_id_idx" ON "student_accounts"("created_by_id");
-- CreateIndex
CREATE INDEX "student_account_attendees_attendee_id_idx" ON "student_account_attendees"("attendee_id");
-- CreateIndex
CREATE UNIQUE INDEX "student_access_tokens_token_hash_key" ON "student_access_tokens"("token_hash");
-- CreateIndex
CREATE INDEX "student_access_tokens_account_id_kind_idx" ON "student_access_tokens"("account_id", "kind");
-- CreateIndex
CREATE UNIQUE INDEX "student_sessions_token_hash_key" ON "student_sessions"("token_hash");
-- CreateIndex
CREATE INDEX "student_sessions_account_id_idx" ON "student_sessions"("account_id");
-- CreateIndex
CREATE UNIQUE INDEX "student_passkeys_credential_id_key" ON "student_passkeys"("credential_id");
-- CreateIndex
CREATE INDEX "student_passkeys_account_id_idx" ON "student_passkeys"("account_id");
-- CreateIndex
CREATE INDEX "student_webauthn_challenges_expires_at_idx" ON "student_webauthn_challenges"("expires_at");
-- CreateIndex
CREATE INDEX "rate_limit_events_key_created_at_idx" ON "rate_limit_events"("key", "created_at");
-- CreateIndex
CREATE INDEX "absence_notices_attendee_id_class_session_id_idx" ON "absence_notices"("attendee_id", "class_session_id");
-- CreateIndex
CREATE INDEX "absence_notices_class_session_id_idx" ON "absence_notices"("class_session_id");
-- CreateIndex
CREATE INDEX "reported_payments_group_id_status_idx" ON "reported_payments"("group_id", "status");
-- CreateIndex
CREATE INDEX "reported_payments_attendee_id_idx" ON "reported_payments"("attendee_id");
-- CreateIndex
CREATE INDEX "reported_payment_items_payment_id_idx" ON "reported_payment_items"("payment_id");
-- AddForeignKey
ALTER TABLE "student_accounts" ADD CONSTRAINT "student_accounts_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_account_attendees" ADD CONSTRAINT "student_account_attendees_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_access_tokens" ADD CONSTRAINT "student_access_tokens_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_sessions" ADD CONSTRAINT "student_sessions_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_passkeys" ADD CONSTRAINT "student_passkeys_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "student_webauthn_challenges" ADD CONSTRAINT "student_webauthn_challenges_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_class_session_id_fkey" FOREIGN KEY ("class_session_id") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "absence_notices" ADD CONSTRAINT "absence_notices_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_attendee_id_fkey" FOREIGN KEY ("attendee_id") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_group_id_fkey" FOREIGN KEY ("group_id") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "reported_payments" ADD CONSTRAINT "reported_payments_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_reported_payment_id_fkey" FOREIGN KEY ("reported_payment_id") REFERENCES "reported_payments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "reported_payment_items" ADD CONSTRAINT "reported_payment_items_payment_id_fkey" FOREIGN KEY ("payment_id") REFERENCES "payments"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- At most one active (not cancelled) absence notice per attendee and class.
-- Partial index: Prisma can't express it in the schema.
CREATE UNIQUE INDEX "absence_notices_active_attendee_class_key" ON "absence_notices"("attendee_id", "class_session_id") WHERE "cancelled_at" IS NULL;

View File

@@ -13,9 +13,10 @@ model ClassSession {
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: "class_sessions_groupId_fkey") group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey")
attendances Attendance[] attendances Attendance[]
slotReleases SlotRelease[] slotReleases SlotRelease[]
absenceNotices AbsenceNotice[]
@@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key") @@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
@@map("class_sessions") @@map("class_sessions")

View File

@@ -1,24 +1,33 @@
// Auth (Better Auth) - required tables // Auth (Better Auth) - required tables
model User { model User {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
email String @unique email String @unique
emailVerified Boolean @default(false) @map("email_verified") emailVerified Boolean @default(false) @map("email_verified")
image String? image String?
onboardingCompleted Boolean @default(false) @map("onboarding_completed") onboardingCompleted Boolean @default(false) @map("onboarding_completed")
createdAt DateTime @default(now()) @map("created_at") country String? @map("country_code")
updatedAt DateTime @updatedAt @map("updated_at") // When the professor chose Free or Pro in the onboarding (mandatory step).
planSelectedAt DateTime? @map("plan_selected_at")
// Bank transfer details shown to students when they report a payment.
transferAlias String? @map("transfer_alias")
transferHolder String? @map("transfer_holder")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
accounts Account[] accounts Account[]
sessions Session[] sessions Session[]
passkeys Passkey[] passkeys Passkey[]
groupsMember GroupMember[] groupsMember GroupMember[]
groupsOwner Group[] @relation("OwnerGroups") groupsOwner Group[] @relation("OwnerGroups")
orgMemberships Member[] orgMemberships Member[]
orgInvitations Invitation[] @relation("InvitedBy") orgInvitations Invitation[] @relation("InvitedBy")
waitlist WaitlistEntry[] waitlist WaitlistEntry[]
merchantAccount MerchantAccount? mpAccount MpAccount?
whatsappAccount WhatsappAccount?
subscription BillingSubscription?
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
@@map("users") @@map("users")
} }

View File

@@ -0,0 +1,82 @@
// Gruperly's own billing: the professor pays a monthly Pro subscription,
// collected by Mercado Pago Subscriptions (preapproval, Argentina) or Stripe
// (every other country), see `modules/billing/providers/`. Not to be confused
// with `Payment`, which is what students pay the professor.
enum BillingProviderId {
MERCADO_PAGO
STRIPE
}
enum SubscriptionStatus {
PENDING
AUTHORIZED
PAUSED
CANCELLED
}
model BillingSubscription {
id String @id @default(cuid())
userId String @unique(map: "billing_subscriptions_userId_key") @map("user_id")
country String @map("country_code")
currency String
amount Decimal @db.Decimal(12, 2)
payerEmail String @map("payer_email")
// Who collects it. Sync and cancel always follow this, never the current country.
provider BillingProviderId @default(MERCADO_PAGO)
// The provider's subscription id (MP preapproval, Stripe subscription). Null
// until the provider creates it: right after MP answers, or once the
// professor completes Stripe Checkout.
externalId String? @unique(map: "billing_subscriptions_externalId_key") @map("external_id")
// Stripe Checkout Session of the current attempt; null for Mercado Pago.
checkoutRef String? @unique(map: "billing_subscriptions_checkoutRef_key") @map("checkout_ref")
status SubscriptionStatus @default(PENDING)
// When the current attempt started: re-subscribing reuses the row.
requestedAt DateTime @default(now()) @map("requested_at")
authorizedAt DateTime? @map("authorized_at")
nextPaymentDate DateTime? @map("next_payment_date")
// Last day covered by an approved charge. Pro lasts until then plus the grace
// period, even after a cancellation or a failed renewal.
paidThrough DateTime? @map("paid_through")
lastSyncedAt DateTime? @map("last_synced_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "billing_subscriptions_userId_fkey")
charges BillingCharge[]
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
@@map("billing_subscriptions")
}
// One monthly invoice of a subscription (MP authorized payment, Stripe invoice).
model BillingCharge {
id String @id @default(cuid())
subscriptionId String @map("subscription_id")
externalId String @unique(map: "billing_charges_externalId_key") @map("external_id")
amount Decimal @db.Decimal(12, 2)
currency String
// Normalized across providers: approved, pending or rejected.
status String
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
subscription BillingSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade, map: "billing_charges_subscriptionId_fkey")
@@index([subscriptionId, createdAt], map: "billing_charges_subscriptionId_createdAt_idx")
@@map("billing_charges")
}
// Deduplication of billing webhook deliveries, per sending account: `mp:<CC>`
// (one Mercado Pago account per country) or `stripe`.
model BillingWebhookEvent {
source String @map("source")
dedupeKey String @map("dedupe_key")
receivedAt DateTime @default(now()) @map("received_at")
@@id([source, dedupeKey], map: "billing_webhook_events_pkey")
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
@@map("billing_webhook_events")
}

View File

@@ -1,19 +1,22 @@
// Domain models // Domain models
model Group { model Group {
id String @id @default(cuid()) id String @id @default(cuid())
name String name String
description String? description String?
days WeekDay[] days WeekDay[]
time String? time String?
capacity Int? capacity Int?
price Decimal? @db.Decimal(10, 2) price Decimal? @db.Decimal(10, 2)
billingType BillingType? @map("billing_type") billingType BillingType? @map("billing_type")
dueDay Int? @map("due_day") dueDay Int? @map("due_day")
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token") // Weekly WhatsApp automations, off until the teacher turns them on.
createdById String @map("created_by_id") autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
createdAt DateTime @default(now()) @map("created_at") autoReengagement Boolean @default(false) @map("auto_reengagement")
updatedAt DateTime @updatedAt @map("updated_at") inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
createdById String @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey") owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
members GroupMember[] members GroupMember[]
@@ -22,6 +25,8 @@ model Group {
waitlist GroupWaitlistEntry[] waitlist GroupWaitlistEntry[]
preRegistrations GroupPreRegistration[] preRegistrations GroupPreRegistration[]
classSessions ClassSession[] classSessions ClassSession[]
outboundMessages OutboundMessage[]
reportedPayments ReportedPayment[]
@@map("groups") @@map("groups")
} }
@@ -81,29 +86,62 @@ model Attendee {
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")
payments Payment[] payments Payment[]
attendances Attendance[] attendances Attendance[]
slotReleases SlotRelease[] slotReleases SlotRelease[]
outboundMessages OutboundMessage[]
alertResolutions AttendeeAlertResolution[]
studentAccounts StudentAccountAttendee[]
absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[]
@@index([groupId], map: "attendees_groupId_idx") @@index([groupId], map: "attendees_groupId_idx")
@@map("attendees") @@map("attendees")
} }
model Payment { enum StudentAlertKind {
id String @id @default(cuid()) ATTENDANCE
groupId String @map("group_id") PAYMENT
attendeeId String @map("attendee_id") }
amount Decimal @db.Decimal(10, 2)
currency String @default("MXN")
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
dueDate DateTime @map("due_date")
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey") // "Resuelto" on the "Requiere atención" screen. One row per attendee and kind:
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey") // it hides the alert while its signature (last absence / overdue fees) stays
// the same, so a new absence or a new overdue fee brings it back on its own.
model AttendeeAlertResolution {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
kind StudentAlertKind
signature String
resolvedById String @map("resolved_by_id")
resolvedAt DateTime @default(now()) @map("resolved_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
@@unique([attendeeId, kind])
@@map("attendee_alert_resolutions")
}
model Payment {
id String @id @default(cuid())
groupId String @map("group_id")
attendeeId String @map("attendee_id")
amount Decimal @db.Decimal(10, 2)
currency String @default("ARS")
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
dueDate DateTime @map("due_date")
description String? @map("description")
checkoutUrl String? @map("checkout_url")
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id")
paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
outboundMessages OutboundMessage[]
reportedItems ReportedPaymentItem[]
@@index([groupId], map: "payments_groupId_idx") @@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx") @@index([attendeeId], map: "payments_attendeeId_idx")
@@ -182,22 +220,49 @@ model GroupPreRegistration {
@@map("group_pre_registrations") @@map("group_pre_registrations")
} }
enum PaymentProvider { enum MpAccountStatus {
MERCADO_PAGO ACTIVE
STRIPE REQUIRES_REAUTH
REVOKED
} }
model MerchantAccount { // Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE).
id String @id @default(cuid()) // Tokens are stored encrypted (AES-256-GCM); there is a single active account per
userId String @unique(map: "merchant_accounts_userId_key") @map("user_id") // teacher and a Mercado Pago user cannot be linked to two teachers.
provider PaymentProvider model MpAccount {
accessToken String? @map("access_token") id String @id @default(cuid())
sandbox Boolean @default(true) ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id")
connectedAt DateTime @default(now()) @map("connected_at") mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id")
createdAt DateTime @default(now()) @map("created_at") accessTokenEnc String @map("access_token_enc")
updatedAt DateTime @updatedAt @map("updated_at") refreshTokenEnc String @map("refresh_token_enc")
expiresAt DateTime @map("expires_at")
scope String?
liveMode Boolean @default(false) @map("live_mode")
status MpAccountStatus @default(ACTIVE)
connectedAt DateTime @default(now()) @map("connected_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "merchant_accounts_userId_fkey") owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey")
@@map("merchant_accounts") // The daily refresh job looks for ACTIVE accounts expiring within 30 days.
@@index([status, expiresAt], map: "mp_accounts_status_expiresAt_idx")
@@map("mp_accounts")
}
// Pending OAuth authorization: the `state` sent to Mercado Pago plus the PKCE
// `code_verifier`. The `state` is the primary key because consuming it (deleting
// the row) is what makes it single use.
model MpOAuthState {
state String @id
ownerId String @map("owner_id")
codeVerifier String @map("code_verifier")
// Constrained to 'onboarding' | 'settings'; decides where the callback lands.
returnTo String @map("return_to")
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
// Expired rows are swept on every new authorization request.
@@index([expiresAt], map: "mp_oauth_states_expiresAt_idx")
@@map("mp_oauth_states")
} }

View File

@@ -0,0 +1,235 @@
// Student access (attendees or their guardians), without passwords.
//
// The teacher sends a single-use invitation link over WhatsApp; consuming it
// creates a long sliding session on that device. Passkeys and a recovery email
// are optional and let the student get back in without the teacher. None of
// this goes through Better Auth: students have no mandatory email and their
// session must never pass the teacher's endpoints (separate cookie and
// middleware under /api/v1/student).
// The person who signs in: the attendee or a guardian. Linked to one or more
// attendees (a guardian may have several children), always by the teacher.
model StudentAccount {
id String @id @default(cuid())
name String
// Verified recovery email (the student loads it, optional).
recoveryEmail String? @map("recovery_email")
recoveryEmailVerifiedAt DateTime? @map("recovery_email_verified_at")
// Email waiting for its confirmation link; never used to recover.
pendingRecoveryEmail String? @map("pending_recovery_email")
// First sign-in done: the welcome screen is shown only once.
welcomedAt DateTime? @map("welcomed_at")
createdById String @map("created_by_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
createdBy User @relation("StudentAccountsCreated", fields: [createdById], references: [id], onDelete: Cascade)
attendees StudentAccountAttendee[]
tokens StudentAccessToken[]
sessions StudentSession[]
passkeys StudentPasskey[]
challenges StudentWebauthnChallenge[]
absenceNotices AbsenceNotice[]
reportedPayments ReportedPayment[]
@@index([recoveryEmail])
@@index([createdById])
@@map("student_accounts")
}
model StudentAccountAttendee {
accountId String @map("account_id")
attendeeId String @map("attendee_id")
createdAt DateTime @default(now()) @map("created_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
@@id([accountId, attendeeId])
@@index([attendeeId])
@@map("student_account_attendees")
}
enum StudentTokenKind {
INVITATION
RECOVERY
EMAIL_CONFIRMATION
}
// Link token. Only its SHA-256 is stored. Consuming it is a conditional update
// (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now()`), so the
// first device wins and the link dies.
model StudentAccessToken {
id String @id @default(cuid())
tokenHash String @unique @map("token_hash")
accountId String @map("account_id")
kind StudentTokenKind
// EMAIL_CONFIRMATION only: the address being confirmed.
email String?
expiresAt DateTime @map("expires_at")
usedAt DateTime? @map("used_at")
// A new invitation revokes the account's pending tokens.
revokedAt DateTime? @map("revoked_at")
// Teacher who generated the invitation (null for recovery/confirmation).
createdById String? @map("created_by_id")
usedIp String? @map("used_ip")
usedUserAgent String? @map("used_user_agent")
createdAt DateTime @default(now()) @map("created_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([accountId, kind])
@@map("student_access_tokens")
}
// Long sliding session (90 days, renewed on use). The cookie carries the raw
// token; only its hash is stored.
model StudentSession {
id String @id @default(cuid())
accountId String @map("account_id")
tokenHash String @unique @map("token_hash")
// Human readable, derived from the user agent ("iPhone · Safari").
device String
createdAt DateTime @default(now()) @map("created_at")
lastUsedAt DateTime @default(now()) @map("last_used_at")
expiresAt DateTime @map("expires_at")
revokedAt DateTime? @map("revoked_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([accountId])
@@map("student_sessions")
}
model StudentPasskey {
id String @id @default(cuid())
accountId String @map("account_id")
credentialId String @unique @map("credential_id")
publicKey Bytes @map("public_key")
counter Int @default(0)
transports String[]
device String
createdAt DateTime @default(now()) @map("created_at")
lastUsedAt DateTime? @map("last_used_at")
account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([accountId])
@@map("student_passkeys")
}
enum WebauthnChallengePurpose {
REGISTER
LOGIN
}
// Pending WebAuthn challenge, single use (deleted when verified), 5 minutes.
model StudentWebauthnChallenge {
id String @id @default(cuid())
challenge String
// Registration only: the signed-in account. Login is discoverable (no account).
accountId String? @map("account_id")
purpose WebauthnChallengePurpose
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: Cascade)
@@index([expiresAt])
@@map("student_webauthn_challenges")
}
// Generic sliding-window rate limit: one row per hit, counted by key within
// the window (e.g. "recovery:email:<sha256>", "recovery:ip:<ip>").
model RateLimitEvent {
id String @id @default(cuid())
key String
createdAt DateTime @default(now()) @map("created_at")
@@index([key, createdAt])
@@map("rate_limit_events")
}
enum AbsenceReason {
HEALTH
TRAVEL
WORK_STUDY
OTHER
}
// Absence notice from the student. It only marks the attendance as EXCUSED
// (which already doesn't count for the attendance risk rules); the teacher
// sees it. At most one active (not cancelled) notice per attendee and class:
// enforced by a partial unique index in the migration.
model AbsenceNotice {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
classSessionId String @map("class_session_id")
accountId String? @map("account_id")
reason AbsenceReason?
message String?
createdAt DateTime @default(now()) @map("created_at")
cancelledAt DateTime? @map("cancelled_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
@@index([attendeeId, classSessionId])
@@index([classSessionId])
@@map("absence_notices")
}
enum ReportedPaymentStatus {
REPORTED
CONFIRMED
REJECTED
}
// Payment reported by the student with a receipt. It stays REPORTED until the
// teacher confirms it (the fees become PAID) or rejects it. `Payment.status` is
// not touched while REPORTED: the MP reconciliation and the overdue job keep
// working as before, and "Requiere atención" skips fees covered by a REPORTED
// report.
model ReportedPayment {
id String @id @default(cuid())
attendeeId String @map("attendee_id")
groupId String @map("group_id")
accountId String? @map("account_id")
totalAmount Decimal @map("total_amount") @db.Decimal(10, 2)
currency String
// Private object key in the storage; null once the retention policy deletes it.
receiptKey String? @map("receipt_key")
receiptMime String @map("receipt_mime")
receiptName String @map("receipt_name")
receiptSize Int @map("receipt_size")
status ReportedPaymentStatus @default(REPORTED)
reviewedById String? @map("reviewed_by_id")
reviewedAt DateTime? @map("reviewed_at")
rejectionReason String? @map("rejection_reason")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
account StudentAccount? @relation(fields: [accountId], references: [id], onDelete: SetNull)
items ReportedPaymentItem[]
@@index([groupId, status])
@@index([attendeeId])
@@map("reported_payments")
}
// Fees a report covers. A fee can't be in two REPORTED reports at once
// (checked in the use-case, inside the transaction).
model ReportedPaymentItem {
reportedPaymentId String @map("reported_payment_id")
paymentId String @map("payment_id")
reportedPayment ReportedPayment @relation(fields: [reportedPaymentId], references: [id], onDelete: Cascade)
payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)
@@id([reportedPaymentId, paymentId])
@@index([paymentId])
@@map("reported_payment_items")
}

View File

@@ -0,0 +1,130 @@
// WhatsApp messaging (automated payment reminders and re-engagement).
//
// Nothing here is tied to one provider: the teacher links their own number
// through whichever `MessagingProvider` the server runs (OpenWA for the MVP,
// Kapso afterwards) and the row records which one it was linked with. Changing
// `WHATSAPP_PROVIDER` leaves the old rows behind as "requires reconnect".
enum MessagingProviderId {
OPENWA
KAPSO
}
enum WhatsappAccountStatus {
PENDING
ACTIVE
DISCONNECTED
}
enum WhatsappMessageKind {
PAYMENT_REMINDER
REENGAGEMENT
}
enum OutboundMessageStatus {
QUEUED
SENT
DELIVERED
READ
FAILED
SKIPPED
}
enum WhatsappTemplateStatus {
PENDING
APPROVED
REJECTED
DISABLED
}
// The teacher's linked WhatsApp. One per teacher.
model WhatsappAccount {
id String @id @default(cuid())
ownerId String @unique(map: "whatsapp_accounts_ownerId_key") @map("owner_id")
provider MessagingProviderId
status WhatsappAccountStatus @default(PENDING)
// OpenWA: session id. Kapso: phone_number_id (null until the setup finishes).
externalId String? @map("external_id")
displayPhoneNumber String? @map("display_phone_number")
// Provider-specific identifiers (Kapso: customerId, setupLinkId, businessAccountId).
// Never secrets: API keys and webhook secrets live in the environment.
providerData Json? @map("provider_data")
connectedAt DateTime? @map("connected_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "whatsapp_accounts_ownerId_fkey")
templates WhatsappTemplate[]
// A number (or session) cannot be linked to two teachers.
@@unique([provider, externalId], map: "whatsapp_accounts_provider_externalId_key")
@@map("whatsapp_accounts")
}
// Message templates submitted to Meta for one account (Kapso only: OpenWA sends
// free text). Meta approves them per WhatsApp Business Account.
model WhatsappTemplate {
id String @id @default(cuid())
accountId String @map("account_id")
kind WhatsappMessageKind
name String
language String
metaTemplateId String? @map("meta_template_id")
status WhatsappTemplateStatus @default(PENDING)
rejectedReason String? @map("rejected_reason")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
account WhatsappAccount @relation(fields: [accountId], references: [id], onDelete: Cascade, map: "whatsapp_templates_accountId_fkey")
@@unique([accountId, kind], map: "whatsapp_templates_accountId_kind_key")
@@index([status], map: "whatsapp_templates_status_idx")
@@map("whatsapp_templates")
}
// One automated message to one member. It is the send log and the idempotency
// key at once: the row is created before calling the provider, and the unique
// (kind, attendee, week) is what stops a second run of the weekly job from
// writing to the same person twice.
model OutboundMessage {
id String @id @default(cuid())
ownerId String @map("owner_id")
groupId String @map("group_id")
attendeeId String @map("attendee_id")
paymentId String? @map("payment_id")
kind WhatsappMessageKind
provider MessagingProviderId
// ISO week the job ran for, e.g. "2026-W43".
periodKey String @map("period_key")
toPhone String @map("to_phone")
providerMessageId String? @map("provider_message_id")
status OutboundMessageStatus @default(QUEUED)
errorCode String? @map("error_code")
errorMessage String? @map("error_message")
sentAt DateTime? @map("sent_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey")
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey")
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")
// Re-engagement cooldown: "was this member written to in the last 14 days?"
@@index([attendeeId, kind, createdAt], map: "outbound_messages_attendeeId_kind_createdAt_idx")
@@index([groupId, createdAt], map: "outbound_messages_groupId_createdAt_idx")
@@map("outbound_messages")
}
// Webhook deliveries already processed. Both providers deliver at least once and
// retry, so the delivery's idempotency key is burned here before applying it.
model WhatsappWebhookEvent {
provider MessagingProviderId
dedupeKey String @map("dedupe_key")
receivedAt DateTime @default(now()) @map("received_at")
@@id([provider, dedupeKey], map: "whatsapp_webhook_events_pkey")
@@index([receivedAt], map: "whatsapp_webhook_events_receivedAt_idx")
@@map("whatsapp_webhook_events")
}

View File

@@ -10,20 +10,26 @@ import { requestLoggerMiddleware } from '@/http/request-logger';
import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers'; import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers';
import { sessionAuthMiddleware } from '@/http/session-auth'; import { sessionAuthMiddleware } from '@/http/session-auth';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { adminRoutes } from './modules/admin';
import { import {
groupsRiskOverviewRoute, groupsRiskOverviewRoute,
studentStatusRoutes, studentStatusRoutes,
} from './modules/analytics'; } from './modules/analytics';
import { attendeesRoutes } from './modules/attendees'; import { attendeesRoutes } from './modules/attendees';
import { attentionRoutes } from './modules/attention';
import { authRoutes } from './modules/auth'; import { authRoutes } from './modules/auth';
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
import { classesRoutes } from './modules/classes'; import { classesRoutes } from './modules/classes';
import { groupsRoutes } from './modules/groups'; import { groupsRoutes } from './modules/groups';
import { healthCheckRoutes } from './modules/health-check'; import { healthCheckRoutes } from './modules/health-check';
import { homeRoutes } from './modules/home'; import { homeRoutes } from './modules/home';
import { invitationsRoutes } from './modules/invitations'; import { invitationsRoutes } from './modules/invitations';
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 { studentPortalRoutes } from './modules/student-portal';
import { waitlistRoutes } from './modules/waitlist'; import { waitlistRoutes } from './modules/waitlist';
import { whatsappRoutes } from './modules/whatsapp';
const app = new Hono<BackendEnv>(); const app = new Hono<BackendEnv>();
@@ -38,18 +44,31 @@ const api = app.basePath('/api/v1');
api.use('*', sessionAuthMiddleware); api.use('*', sessionAuthMiddleware);
// Read-only accounts (Free over its limits) cannot write domain data. Billing,
// onboarding and the MP/WhatsApp links stay open: that is how they get out of it.
const planReadOnly = planReadOnlyMiddleware();
for (const prefix of ['/groups', '/attendees', '/payments', '/classes', '/students', '/waitlist']) {
api.use(`${prefix}/*`, planReadOnly);
}
api.route('/admin', adminRoutes);
api.route('/auth', authRoutes); api.route('/auth', authRoutes);
api.route('/health', healthCheckRoutes); api.route('/health', healthCheckRoutes);
api.route('/invitations', invitationsRoutes); api.route('/invitations', invitationsRoutes);
api.route('/groups', groupsRoutes); api.route('/groups', groupsRoutes);
api.route('/home', homeRoutes); api.route('/home', homeRoutes);
api.route('/onboarding', onboardingRoutes); api.route('/onboarding', onboardingRoutes);
api.route('/mp', mpRoutes);
api.route('/whatsapp', whatsappRoutes);
api.route('/attendees', attendeesRoutes); api.route('/attendees', attendeesRoutes);
api.route('/payments', paymentsRoutes); api.route('/payments', paymentsRoutes);
api.route('/billing', billingRoutes);
api.route('/waitlist', waitlistRoutes); api.route('/waitlist', waitlistRoutes);
api.route('/classes', classesRoutes); 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('/student-portal', studentPortalRoutes);
app.notFound((c) => { app.notFound((c) => {
return problemJson(c, notFoundProblem(c.req.path)); return problemJson(c, notFoundProblem(c.req.path));

View File

@@ -2,11 +2,15 @@ import type { auth } from '@/modules/auth/auth';
type AuthSession = typeof auth.$Infer.Session; type AuthSession = typeof auth.$Infer.Session;
/** Signed-in student (attendee or guardian): set only on /student-portal. */
export type StudentContext = { accountId: string; sessionId: string };
export type BackendEnv = { export type BackendEnv = {
Variables: { Variables: {
user: AuthSession['user'] | null; user: AuthSession['user'] | null;
session: AuthSession['session'] | null; session: AuthSession['session'] | null;
requestId: string; requestId: string;
student: StudentContext | null;
}; };
}; };
@@ -15,5 +19,6 @@ declare module 'hono' {
user: AuthSession['user'] | null; user: AuthSession['user'] | null;
session: AuthSession['session'] | null; session: AuthSession['session'] | null;
requestId: string; requestId: string;
student: StudentContext | null;
} }
} }

View File

@@ -71,13 +71,108 @@ export function notFoundResourceProblem(resourceName: string, id: string): Probl
return notFoundProblem(`${resourceName} ${id}`); return notFoundProblem(`${resourceName} ${id}`);
} }
export function paymentNotSetupProblem(): ProblemDetails { export function mpNotConnectedProblem(): ProblemDetails {
return conflictProblem({ return conflictProblem({
detail: 'Vinculá una cuenta de cobro antes de crear tu primer grupo.', detail: 'No tenés una cuenta de Mercado Pago vinculada.',
code: 'payment_not_setup', code: 'mp_not_connected',
}); });
} }
export function mpRequiresReauthProblem(): ProblemDetails {
return conflictProblem({
detail: 'Tu cuenta de Mercado Pago necesita volver a vincularse.',
code: 'mp_requires_reauth',
});
}
export function mpAccountInUseProblem(): ProblemDetails {
return conflictProblem({
detail: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.',
code: 'mp_account_in_use',
});
}
/** The server is missing MP_CLIENT_ID / MP_CLIENT_SECRET / MP_REDIRECT_URI. */
export function mpNotConfiguredProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/mercadopago-not-configured`,
title: 'Service Unavailable',
status: 503,
detail: 'La vinculación con Mercado Pago no está disponible en este momento.',
code: 'mp_not_configured',
};
}
/** Mercado Pago refused the request, or could not be reached. */
export function mpProviderErrorProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/mercadopago-unavailable`,
title: 'Bad Gateway',
status: 502,
detail: 'No pudimos completar la vinculación con Mercado Pago.',
code: 'mp_provider_error',
};
}
/** The server is missing the variables of the active WhatsApp provider. */
export function whatsappNotConfiguredProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/whatsapp-not-configured`,
title: 'Service Unavailable',
status: 503,
detail: 'La vinculación con WhatsApp no está disponible en este momento.',
code: 'whatsapp_not_configured',
};
}
export function whatsappNotConnectedProblem(): ProblemDetails {
return conflictProblem({
detail: 'No tenés un WhatsApp vinculado.',
code: 'whatsapp_not_connected',
});
}
export function whatsappNumberInUseProblem(): ProblemDetails {
return conflictProblem({
detail: 'Ese número de WhatsApp ya está vinculado a otro profesor.',
code: 'whatsapp_number_in_use',
});
}
export function whatsappLinkingNotStartedProblem(): ProblemDetails {
return conflictProblem({
detail: 'Empezá la vinculación de WhatsApp antes de pedir el código.',
code: 'whatsapp_linking_not_started',
});
}
/** The provider links by QR or redirect only (Kapso). */
export function whatsappPairingUnsupportedProblem(): ProblemDetails {
return conflictProblem({
detail: 'Este proveedor de WhatsApp no permite vincular con el número de teléfono.',
code: 'whatsapp_pairing_unsupported',
});
}
/** The session is not ready to hand out a code yet; retryable in seconds. */
export function whatsappPairingNotReadyProblem(): ProblemDetails {
return conflictProblem({
detail: 'WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.',
code: 'whatsapp_pairing_not_ready',
});
}
/** The WhatsApp gateway refused the request, or could not be reached. */
export function whatsappProviderErrorProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/whatsapp-unavailable`,
title: 'Bad Gateway',
status: 502,
detail: 'No pudimos comunicarnos con WhatsApp. Intentá de nuevo en unos minutos.',
code: 'whatsapp_provider_error',
};
}
export function onboardingAlreadyCompletedProblem(): ProblemDetails { export function onboardingAlreadyCompletedProblem(): ProblemDetails {
return conflictProblem({ return conflictProblem({
detail: 'Ya completaste el onboarding de Gruperly.', detail: 'Ya completaste el onboarding de Gruperly.',
@@ -106,4 +201,111 @@ export function attendeeHasPaymentsProblem(): ProblemDetails {
detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.', detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.',
code: 'attendee_has_payments', code: 'attendee_has_payments',
}); });
} }
export function groupWithoutPriceProblem(): ProblemDetails {
return conflictProblem({
detail: 'Definí el precio del grupo antes de generar los cobros.',
code: 'group_without_price',
});
}
export function noAttendeesToBillProblem(): ProblemDetails {
return conflictProblem({
detail: 'No hay miembros activos con un cobro pendiente para este grupo.',
code: 'no_attendees_to_bill',
});
}
function paymentRequiredProblem(params: { detail: string; code: string }): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/plan`,
title: 'Payment Required',
status: 402,
detail: params.detail,
code: params.code,
};
}
export type PlanLimitKind = 'groups' | 'attendees';
/** The Free plan does not allow one more group or attendee. */
export function planLimitReachedProblem(limit: PlanLimitKind, max: number): ProblemDetails {
return paymentRequiredProblem({
detail:
limit === 'groups'
? `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.`,
code: 'plan_limit_reached',
});
}
/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */
export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails {
return paymentRequiredProblem({
detail:
feature === 'mpCharges'
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
code: 'plan_feature_required',
});
}
/** Free plan with more usage than its limits: only reads and deletes. */
export function planReadOnlyProblem(): ProblemDetails {
return paymentRequiredProblem({
detail:
'Tu cuenta está en solo lectura porque superás los límites del plan Free. Pasate a Pro o reducí el uso para volver a editar.',
code: 'plan_read_only',
});
}
/** The billing provider of the professor's country is not configured. */
export function billingNotAvailableProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/billing-not-available`,
title: 'Service Unavailable',
status: 503,
detail: 'La suscripción a Pro todavía no está disponible en tu país.',
code: 'billing_not_available',
};
}
/** The billing provider (Mercado Pago or Stripe) refused the request, or could not be reached. */
export function billingProviderErrorProblem(): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/billing-provider-error`,
title: 'Bad Gateway',
status: 502,
detail: 'No pudimos comunicarnos con el procesador de pagos. Intentá de nuevo en unos minutos.',
code: 'billing_provider_error',
};
}
/** Mercado Pago makes the payer log in with this exact email, so it cannot be left out. */
export function payerEmailRequiredProblem(): ProblemDetails {
return validationProblem({
detail: 'Ingresá el email de tu cuenta de Mercado Pago.',
errors: { payerEmail: ['Ingresá el email de tu cuenta de Mercado Pago.'] },
});
}
export function subscriptionAlreadyActiveProblem(): ProblemDetails {
return conflictProblem({
detail: 'Ya tenés una suscripción a Pro activa.',
code: 'subscription_already_active',
});
}
export function noActiveSubscriptionProblem(): ProblemDetails {
return conflictProblem({
detail: 'No tenés una suscripción para cancelar.',
code: 'no_active_subscription',
});
}
export function planNotSelectedProblem(): ProblemDetails {
return conflictProblem({
detail: 'Elegí un plan antes de crear tu primer grupo.',
code: 'plan_not_selected',
});
}

View File

@@ -34,12 +34,32 @@ export function isPublicApiRequest(method: string, path: string): boolean {
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') { if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
return true; return true;
} }
// WhatsApp provider webhooks: no session, authenticated by their HMAC signature.
if (
method === 'POST'
&& (normalizedPath === '/api/v1/whatsapp/webhooks/openwa'
|| normalizedPath === '/api/v1/whatsapp/webhooks/kapso')
) {
return true;
}
// Mercado Pago notifications about Pro subscriptions, one URL per country:
// no session, authenticated by Mercado Pago's `x-signature`.
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
return true;
}
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
return true;
}
return ( return (
normalizedPath === '/api/v1/health' normalizedPath === '/api/v1/health'
|| matchesPublicPrefix(normalizedPath, '/api/v1/auth') || matchesPublicPrefix(normalizedPath, '/api/v1/auth')
|| matchesPublicPrefix(normalizedPath, '/api/auth') || matchesPublicPrefix(normalizedPath, '/api/auth')
|| matchesPublicPrefix(normalizedPath, '/api/v1/invitations') || matchesPublicPrefix(normalizedPath, '/api/v1/invitations')
// Student app: its own cookie and middleware (modules/student-portal), never
// the teacher's session.
|| matchesPublicPrefix(normalizedPath, '/api/v1/student-portal')
); );
} }

View File

@@ -4,6 +4,15 @@ import nodemailer, { type Transporter } from 'nodemailer'
type VerificationEmailData = { email: string; url: string; name?: string } type VerificationEmailData = { email: string; url: string; name?: string }
type PasswordResetEmailData = { email: string; url: string; name?: string } type PasswordResetEmailData = { email: string; url: string; name?: string }
type InvitationEmailData = { email: string; url: string; organizationName: string } type InvitationEmailData = { email: string; url: string; organizationName: string }
type StudentEmailConfirmationData = { email: string; url: string; name: string }
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
type StudentPaymentReviewedData = {
email: string
name: string
confirmed: boolean
amount: string
reason?: string | null
}
// Brand colors (same system as the web app: index.css in apps/web). // Brand colors (same system as the web app: index.css in apps/web).
const BRAND_600 = '#2544ea' const BRAND_600 = '#2544ea'
@@ -26,10 +35,27 @@ function loadLogoTypoDataUri(): string {
const LOGO_DATA_URI = loadLogoTypoDataUri() const LOGO_DATA_URI = loadLogoTypoDataUri()
interface EmailProvider { export interface EmailProvider {
sendVerificationEmail(data: VerificationEmailData): Promise<void> sendVerificationEmail(data: VerificationEmailData): Promise<void>
sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void> sendPasswordResetEmail(data: PasswordResetEmailData): Promise<void>
sendOrganizationInvitation(data: InvitationEmailData): Promise<void> sendOrganizationInvitation(data: InvitationEmailData): Promise<void>
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
}
// Names come from what teachers and students type: never raw into the HTML.
function escapeHtml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}
function button(url: string, label: string): string {
return `<a href="${escapeHtml(url)}" style="display:inline-block;background:${LINK_BG};color:${ON_ACCENT};text-decoration:none;padding:12px 24px;border-radius:12px;font-weight:600;">${escapeHtml(label)}</a>`
} }
class SMTPEmailProvider implements EmailProvider { class SMTPEmailProvider implements EmailProvider {
@@ -109,6 +135,47 @@ class SMTPEmailProvider implements EmailProvider {
), ),
) )
} }
async sendStudentEmailConfirmation({ email, url, name }: StudentEmailConfirmationData) {
await this.send(
email,
'Confirmá tu mail de recuperación en Gruperly',
this.layout(
'Confirmá tu mail',
`Hola ${escapeHtml(name)}, confirmá este mail para poder pedir un link de ingreso si perdés el acceso a la app (el enlace vence en 24 horas). Si no fuiste vos, ignorá este mail.<br/><br/>${button(url, 'Confirmar mail')}`,
),
)
}
async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) {
// A guardian may have one account per child with the same email: one button each.
const buttons = links
.map((link) =>
links.length > 1
? `<p style="margin:12px 0 4px;">${escapeHtml(link.name)}</p>${button(link.url, 'Ingresar')}`
: button(link.url, 'Ingresar'),
)
.join('<br/>')
await this.send(
email,
'Tu link para ingresar a Gruperly',
this.layout(
'Tu link de ingreso',
`Pediste un link para volver a entrar. Sirve una sola vez y vence en 15 minutos. Si no fuiste vos, ignorá este mail.<br/><br/>${buttons}`,
),
)
}
async sendStudentPaymentReviewed({ email, name, confirmed, amount, reason }: StudentPaymentReviewedData) {
const body = confirmed
? `Hola ${escapeHtml(name)}, tu profe confirmó el pago de ${escapeHtml(amount)}. ¡Gracias!`
: `Hola ${escapeHtml(name)}, tu profe no pudo confirmar el pago de ${escapeHtml(amount)}.${reason ? `<br/><br/>Motivo: ${escapeHtml(reason)}` : ''}<br/><br/>Podés volver a informarlo desde la app.`
await this.send(
email,
confirmed ? 'Tu pago fue confirmado' : 'Tu pago no fue confirmado',
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
)
}
} }
// Future: transactional providers (Resend, SendGrid, Postmark). // Future: transactional providers (Resend, SendGrid, Postmark).

View File

@@ -0,0 +1,36 @@
/* Real type of an uploaded file from its first bytes (magic numbers), never
from the name or the Content-Type the browser claims. */
export type ReceiptMime = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/heic' | 'application/pdf';
export const RECEIPT_MAX_BYTES = 10 * 1024 * 1024;
export const RECEIPT_EXTENSIONS: Record<ReceiptMime, string> = {
'image/jpeg': 'jpg',
'image/png': 'png',
'image/webp': 'webp',
'image/heic': 'heic',
'application/pdf': 'pdf',
};
// ISO-BMFF brands used by HEIC/HEIF photos (iPhone camera).
const HEIF_BRANDS = new Set(['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1']);
function ascii(bytes: Uint8Array, start: number, length: number): string {
return String.fromCharCode(...bytes.subarray(start, start + length));
}
export function detectReceiptType(bytes: Uint8Array): ReceiptMime | null {
if (bytes.length < 12) return null;
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
if (
bytes[0] === 0x89 && ascii(bytes, 1, 3) === 'PNG'
&& bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
) {
return 'image/png';
}
if (ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 4) === 'WEBP') return 'image/webp';
if (ascii(bytes, 4, 4) === 'ftyp' && HEIF_BRANDS.has(ascii(bytes, 8, 4))) return 'image/heic';
if (ascii(bytes, 0, 5) === '%PDF-') return 'application/pdf';
return null;
}

View File

@@ -0,0 +1,54 @@
import { S3Client } from 'bun';
/* Private file storage (payment receipts). Behind a port, like the WhatsApp and
billing providers: the use-cases never talk to S3 directly, and the tests
inject an in-memory fake. Objects are never public; the teacher sees them
through short-lived signed URLs. */
export interface FileStorage {
put(key: string, body: Uint8Array, contentType: string): Promise<void>;
/** GET URL valid for `expiresInSeconds`. */
signedUrl(key: string, expiresInSeconds: number): string;
remove(key: string): Promise<void>;
}
/* Any S3-compatible service (RustFS, MinIO, R2, AWS). Path-style addressing by
default, which is what self-hosted services expect; S3_VIRTUAL_HOSTED=on for
AWS-style bucket subdomains. */
class S3FileStorage implements FileStorage {
constructor(private readonly client: S3Client) {}
async put(key: string, body: Uint8Array, contentType: string): Promise<void> {
await this.client.write(key, body, { type: contentType });
}
signedUrl(key: string, expiresInSeconds: number): string {
return this.client.presign(key, { method: 'GET', expiresIn: expiresInSeconds });
}
async remove(key: string): Promise<void> {
await this.client.delete(key);
}
}
let storage: FileStorage | null | undefined;
/** null when S3 isn't configured: the endpoints that need it answer 503. */
export function getFileStorage(): FileStorage | null {
if (storage !== undefined) return storage;
const { S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY } = process.env;
if (!S3_ENDPOINT || !S3_BUCKET || !S3_ACCESS_KEY_ID || !S3_SECRET_ACCESS_KEY) {
storage = null;
return storage;
}
storage = new S3FileStorage(
new S3Client({
endpoint: S3_ENDPOINT,
bucket: S3_BUCKET,
region: process.env.S3_REGION || 'us-east-1',
accessKeyId: S3_ACCESS_KEY_ID,
secretAccessKey: S3_SECRET_ACCESS_KEY,
virtualHostedStyle: process.env.S3_VIRTUAL_HOSTED === 'on',
}),
);
return storage;
}

View File

@@ -0,0 +1,12 @@
import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details';
import { GetAccount } from './use-case';
const route = new Hono();
route.get('/accounts/:accountId', async (c) => {
const result = await new GetAccount().execute(c.req.param('accountId'));
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,95 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib';
import { accountPlan, toAccountListItem } from '../../lib';
const RECENT_CHARGES = 12;
type GetAccountDeps = {
db?: Pick<PrismaClient, 'user' | 'billingCharge'>;
enforced?: boolean;
graceDays?: number;
now?: () => Date;
};
/** One professor's account: plan, links, groups and the latest Pro charges. */
export class GetAccount {
constructor(private readonly deps: GetAccountDeps = {}) {}
async execute(userId: string): Promise<Result<AdminAccountDetail, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const context = {
now: this.deps.now?.() ?? new Date(),
graceDays: this.deps.graceDays ?? getGraceDays(),
};
const user = await db.user.findUnique({
where: { id: userId },
include: {
subscription: true,
mpAccount: { select: { status: true } },
whatsappAccount: { select: { status: true } },
groupsOwner: {
select: {
id: true,
name: true,
createdAt: true,
_count: { select: { attendees: { where: { status: 'ACTIVE' } } } },
},
orderBy: { createdAt: 'desc' },
},
},
});
if (!user) return err(notFoundResourceProblem('User', userId));
const charges = await db.billingCharge.findMany({
where: { subscription: { userId } },
orderBy: { createdAt: 'desc' },
take: RECENT_CHARGES,
});
const groups = user.groupsOwner.map((group) => ({
id: group.id,
name: group.name,
createdAt: group.createdAt.toISOString(),
attendeesCount: group._count.attendees,
}));
const usage = {
groupsCount: groups.length,
attendeesCount: groups.reduce((sum, group) => sum + group.attendeesCount, 0),
};
const summary = toAccountListItem(user, usage, context);
const { graceUntil } = accountPlan(user, context);
const enforced = this.deps.enforced ?? isBillingEnforced();
const subscription = user.subscription;
return ok({
...summary,
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
graceUntil: graceUntil?.toISOString() ?? null,
// Same rule as the PlanGuard: an account without a plan is held to Free.
readOnly:
enforced
&& exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], {
groups: usage.groupsCount,
attendees: usage.attendeesCount,
}),
subscription:
summary.subscription && subscription
? {
...summary.subscription,
payerEmail: subscription.payerEmail,
authorizedAt: subscription.authorizedAt?.toISOString() ?? null,
requestedAt: subscription.requestedAt.toISOString(),
}
: null,
mpStatus: user.mpAccount?.status ?? null,
whatsappStatus: user.whatsappAccount?.status ?? null,
groups,
charges: charges.map(toBillingChargeDto),
});
}
}

View File

@@ -0,0 +1,16 @@
import type { AdminAccountQuery } from '@gruperly/shared';
import { AdminAccountQuerySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { ListAccounts } from './use-case';
const route = new Hono();
route.get('/accounts', validate.query(AdminAccountQuerySchema), async (c) => {
const query = c.req.valid('query') as AdminAccountQuery;
const result = await new ListAccounts().execute(query);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,65 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { AdminAccountList, AdminAccountQuery, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma';
import { getGraceDays } from '@/modules/billing/lib';
import { type AccountUsage, buildAccountWhere, toAccountListItem } from '../../lib';
type ListAccountsDeps = {
db?: Pick<PrismaClient, 'user' | 'group'>;
graceDays?: number;
now?: () => Date;
};
/** Every professor's account, newest first, with plan and usage. */
export class ListAccounts {
constructor(private readonly deps: ListAccountsDeps = {}) {}
async execute(query: AdminAccountQuery): Promise<Result<AdminAccountList, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const context = {
now: this.deps.now?.() ?? new Date(),
graceDays: this.deps.graceDays ?? getGraceDays(),
};
const where = buildAccountWhere(query, context);
const [users, total] = await Promise.all([
db.user.findMany({
where,
include: { subscription: true },
skip: getPaginationOffset(query),
take: query.pageSize,
orderBy: { createdAt: 'desc' },
}),
db.user.count({ where }),
]);
// Usage of the whole page in one query, same rule as the plan limits:
// groups the professor owns and their ACTIVE attendees.
const groups = users.length
? await db.group.findMany({
where: { createdById: { in: users.map((user) => user.id) } },
select: {
createdById: true,
_count: { select: { attendees: { where: { status: 'ACTIVE' } } } },
},
})
: [];
const usage = new Map<string, AccountUsage>();
for (const group of groups) {
const current = usage.get(group.createdById) ?? { groupsCount: 0, attendeesCount: 0 };
usage.set(group.createdById, {
groupsCount: current.groupsCount + 1,
attendeesCount: current.attendeesCount + group._count.attendees,
});
}
return ok({
data: users.map((user) =>
toAccountListItem(user, usage.get(user.id) ?? { groupsCount: 0, attendeesCount: 0 }, context),
),
pagination: getPaginationMetadata(query, total),
});
}
}

View File

@@ -0,0 +1,16 @@
import type { AdminMeDto } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
import { isAdminEmail } from '../../lib';
const route = new Hono();
// Open to every signed-in user: the web asks it to decide whether to show the backoffice.
route.get('/me', (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
return c.json({ isAdmin: isAdminEmail(user.email) } satisfies AdminMeDto);
});
export default route;

View File

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

View File

@@ -0,0 +1,39 @@
import type { MiddlewareHandler } from 'hono';
import type { BackendEnv } from '@/http/env';
import { forbiddenProblem } from '@/http/problem-builders';
import { problemJson, unauthorizedProblem } from '@/http/problem-details';
/**
* The backoffice is for Gruperly's own staff, listed by email in `ADMIN_EMAILS`
* (comma separated, case-insensitive). An empty or missing list means nobody.
*/
export function isAdminEmail(
email: string | null | undefined,
env: Record<string, string | undefined> = process.env,
): boolean {
if (!email) return false;
const allowed = (env.ADMIN_EMAILS ?? '')
.split(',')
.map((entry) => entry.trim().toLowerCase())
.filter(Boolean);
return allowed.includes(email.trim().toLowerCase());
}
export function adminOnlyMiddleware(
env: Record<string, string | undefined> = process.env,
): MiddlewareHandler<BackendEnv> {
return async (c, next) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
if (!isAdminEmail(user.email, env)) {
return problemJson(
c,
forbiddenProblem({
detail: 'Solo el equipo de Gruperly puede entrar al backoffice.',
code: 'admin_required',
}),
);
}
await next();
};
}

View File

@@ -0,0 +1,94 @@
import type { BillingSubscription, Prisma } from '@generated/prisma/client';
import type { AdminAccountListItem, AdminAccountQuery, Plan } from '@gruperly/shared';
import { countryCodeSchema } from '@gruperly/shared';
import { proSubscriptionWhere, resolvePlan } from '@/modules/billing/lib';
export type AccountRecord = {
id: string;
name: string;
email: string;
country: string | null;
createdAt: Date;
onboardingCompleted: boolean;
planSelectedAt: Date | null;
subscription: BillingSubscription | null;
};
export type AccountUsage = { groupsCount: number; attendeesCount: number };
export type PlanContext = { now: Date; graceDays: number };
/** Pro by its subscription; otherwise Free once chosen, `null` while not chosen. */
export function accountPlan(
account: Pick<AccountRecord, 'planSelectedAt' | 'subscription'>,
{ now, graceDays }: PlanContext,
): { plan: Plan | null; graceUntil: Date | null } {
const resolution = resolvePlan(account.subscription, now, graceDays);
if (resolution.plan === 'PRO') return resolution;
return { plan: account.planSelectedAt ? 'FREE' : null, graceUntil: null };
}
export function toAccountListItem(
account: AccountRecord,
usage: AccountUsage,
context: PlanContext,
): AdminAccountListItem {
const country = countryCodeSchema.safeParse(account.country);
const subscription = account.subscription;
return {
id: account.id,
name: account.name,
email: account.email,
country: country.success ? country.data : null,
createdAt: account.createdAt.toISOString(),
onboardingCompleted: account.onboardingCompleted,
plan: accountPlan(account, context).plan,
subscription: subscription
? {
provider: subscription.provider,
status: subscription.status,
amount: Number(subscription.amount.toString()),
currency: subscription.currency,
paidThrough: subscription.paidThrough?.toISOString() ?? null,
nextPaymentDate:
subscription.status === 'AUTHORIZED'
? (subscription.nextPaymentDate?.toISOString() ?? null)
: null,
}
: null,
...usage,
};
}
/** The list filters as a `user` query. The plan follows `accountPlan`. */
export function buildAccountWhere(
query: Pick<AdminAccountQuery, 'search' | 'country' | 'plan' | 'subscriptionStatus'>,
{ now, graceDays }: PlanContext,
): Prisma.UserWhereInput {
const and: Prisma.UserWhereInput[] = [];
if (query.search) {
and.push({
OR: [
{ name: { contains: query.search, mode: 'insensitive' } },
{ email: { contains: query.search, mode: 'insensitive' } },
],
});
}
if (query.country) and.push({ country: query.country });
if (query.subscriptionStatus === 'NONE') {
and.push({ subscription: { is: null } });
} else if (query.subscriptionStatus) {
and.push({ subscription: { is: { status: query.subscriptionStatus } } });
}
if (query.plan) {
const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } };
if (query.plan === 'PRO') and.push(isPro);
if (query.plan === 'FREE') and.push({ planSelectedAt: { not: null }, NOT: isPro });
if (query.plan === 'NOT_SELECTED') and.push({ planSelectedAt: null, NOT: isPro });
}
return and.length > 0 ? { AND: and } : {};
}

View File

@@ -0,0 +1,9 @@
export { adminOnlyMiddleware, isAdminEmail } from './access';
export {
type AccountRecord,
type AccountUsage,
accountPlan,
buildAccountWhere,
type PlanContext,
toAccountListItem,
} from './account-summary';

View File

@@ -0,0 +1,17 @@
import { Hono } from 'hono';
import getAccountRoute from './features/get-account/route';
import listAccountsRoute from './features/list-accounts/route';
import meRoute from './features/me/route';
import { adminOnlyMiddleware } from './lib';
const routes = new Hono();
routes.route('/', meRoute);
// Everything below `/me` is the backoffice itself.
routes.use('/accounts', adminOnlyMiddleware());
routes.use('/accounts/*', adminOnlyMiddleware());
routes.route('/', listAccountsRoute);
routes.route('/', getAccountRoute);
export default routes;

View File

@@ -39,8 +39,21 @@ export class GetAttendeeHistory {
return err(notFoundResourceProblem('Attendee', attendeeId)); return err(notFoundResourceProblem('Attendee', attendeeId));
} }
// Same effective join date as the risk rule (`toMemberAttendance`): an
// attendee loaded after their first classes were already recorded starts
// at that first class, not at `createdAt`. Otherwise this screen said
// "1 de 3 clases" while the group list said "1 de 5" for the same person.
const firstAttendance = await db.attendance.findFirst({
where: { attendeeId },
orderBy: { classSession: { startsAt: 'asc' } },
select: { classSession: { select: { startsAt: true } } },
});
const firstClassAt = firstAttendance?.classSession.startsAt;
const since =
firstClassAt && firstClassAt < attendee.createdAt ? firstClassAt : attendee.createdAt;
const sessions = await db.classSession.findMany({ const sessions = await db.classSession.findMany({
where: { groupId, startsAt: { gte: attendee.createdAt } }, where: { groupId, startsAt: { gte: since } },
orderBy: { startsAt: 'desc' }, orderBy: { startsAt: 'desc' },
take: HISTORY_SESSIONS_LIMIT, take: HISTORY_SESSIONS_LIMIT,
select: { id: true, startsAt: true }, select: { id: true, startsAt: true },

View File

@@ -4,30 +4,21 @@ import type {
GroupRiskLevel, GroupRiskLevel,
GroupRiskSummary, GroupRiskSummary,
GroupsRiskOverview, GroupsRiskOverview,
MemberClassSession,
ProblemDetails, ProblemDetails,
Result, Result,
UrgentMemberSummary, UrgentMemberSummary,
} from '@gruperly/shared'; } from '@gruperly/shared';
import { getGroupAttendanceSummary, ok, URGENT_MEMBERS_LIMIT } from '@gruperly/shared'; import {
ATTENDANCE_RISK_RULES,
getGroupAttendanceSummary,
ok,
URGENT_MEMBERS_LIMIT,
} from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib'; import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
classifyRisk,
MIN_RISK_ABSENCE_STREAK,
MIN_RISK_MONTHLY_RATE,
monthlyAttendanceRate,
trailingAbsentStreak,
} from '../../lib/risk';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
/* How many classes we look back per attendee. That is the real ceiling of the
model: `class_sessions` are not created on their own, they get materialized
when someone opens "today's classes", so pulling years of rows makes no
sense. 20 classes is enough for the streak, for the 4+4 trend window and for
the attendance rate the card shows. */
const MEMBER_HISTORY_LIMIT = 20;
type GetGroupsRiskOverviewDeps = { type GetGroupsRiskOverviewDeps = {
db?: { db?: {
group: Prisma.GroupDelegate; group: Prisma.GroupDelegate;
@@ -54,10 +45,10 @@ type AttendanceRow = {
classSession: { startsAt: Date }; classSession: { startsAt: Date };
}; };
// Risk status light summary per group for the group listing. // Risk summary per group for the group listing and Home. Everything comes from
// A group is HIGH if it has at least one attendee at high risk, MEDIUM if // the domain rule (`getGroupAttendanceSummary`): the status light is the worst
// any is at medium risk and NONE otherwise. The counters state the reason // level present (riesgo_alto → HIGH, atencion → MEDIUM), the same rule the
// (consecutive absences or low attendance) so the listing can name it. // "Alumnos en riesgo" screen uses, so the listing and the stats can't disagree.
export class GetGroupsRiskOverview { export class GetGroupsRiskOverview {
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {} constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
@@ -117,75 +108,31 @@ export class GetGroupsRiskOverview {
const streamByAttendee = groupAttendanceByAttendee(attendances); const streamByAttendee = groupAttendanceByAttendee(attendances);
const worstRiskByGroup = new Map<string, GroupRiskLevel>(); const items: GroupRiskSummary[] = groups.map((group) =>
// Why there is risk, computed in the same pass: a member with an absence buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
// streak counts in the first counter and only there; the second one );
// groups the members that don't reach a streak and are still below the
// attendance minimum.
const absenceStreakCountByGroup = new Map<string, number>();
const lowAttendanceCountByGroup = new Map<string, number>();
for (const attendee of attendees) {
const groupId = attendee.groupId;
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const streak = trailingAbsentStreak(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
sessionsByGroup.get(groupId)?.length ?? 0,
);
const riskLevel = classifyRisk(streak, monthlyRate);
if (!riskLevel) {
continue;
}
if (streak >= MIN_RISK_ABSENCE_STREAK) {
bump(absenceStreakCountByGroup, groupId);
} else if (monthlyRate < MIN_RISK_MONTHLY_RATE) {
bump(lowAttendanceCountByGroup, groupId);
}
const current = worstRiskByGroup.get(groupId) ?? 'NONE';
if (
riskLevel === 'HIGH' ||
(riskLevel === 'MEDIUM' && current === 'NONE')
) {
worstRiskByGroup.set(groupId, riskLevel);
}
}
const items: GroupRiskSummary[] = groups.map((group) => ({
groupId: group.id,
groupName: group.name,
riskLevel: worstRiskByGroup.get(group.id) ?? 'NONE',
absenceStreakCount: absenceStreakCountByGroup.get(group.id) ?? 0,
lowAttendanceCount: lowAttendanceCountByGroup.get(group.id) ?? 0,
...buildSummaryFields(group, attendees, sessionsByGroup, streamByAttendee, now),
}));
return ok({ items }); return ok({ items });
} }
} }
/** /**
* The per-level summary consumed by the listing card and the Home follow-up * The per-level summary consumed by the listing card and Home. It comes from
* section. It comes from `getGroupAttendanceSummary`, the same domain function * `getGroupAttendanceSummary`, the same domain function that
* that `test/attendance-risk.test.ts` exercises, so the rule doesn't have two * `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
* copies: one here and another in the client. * copies: one here and another in the client.
* *
* `libres` and `enEspera` come from here and not from the `Attendee` count: the * `libres` and `enEspera` come from here and not from the `Attendee` count: the
* summary counts the group members and the card needs the capacity slots to * summary counts the group members and the card needs the capacity slots to
* paint the indicator. * paint the indicator.
*/ */
function buildSummaryFields( function buildSummary(
group: GroupRow, group: GroupRow,
attendees: AttendeeRow[], attendees: AttendeeRow[],
sessionsByGroup: Map<string, SessionRow[]>, sessionsByGroup: Map<string, SessionRow[]>,
attendanceByAttendee: Map<string, AttendanceRow[]>, attendanceByAttendee: Map<string, AttendanceRow[]>,
now: Date, now: Date,
) { ): GroupRiskSummary {
const resumen = getGroupAttendanceSummary({ const resumen = getGroupAttendanceSummary({
groupId: group.id, groupId: group.id,
capacity: group.capacity, capacity: group.capacity,
@@ -193,35 +140,23 @@ function buildSummaryFields(
now, now,
members: attendees members: attendees
.filter((attendee) => attendee.groupId === group.id) .filter((attendee) => attendee.groupId === group.id)
.map((attendee) => { .map((attendee) =>
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? []; toMemberAttendance(
// If the attendee has attendances before their enrollment date in the attendee,
// DB (e.g. created today but with past classes already recorded), their sessionsByGroup.get(group.id) ?? [],
// effective join date is the first class they were marked for. attendanceByAttendee.get(attendee.id) ?? [],
const earliestAttendance = attendeeAttendances.reduce<Date | null>( ),
(earliest, att) => ),
!earliest || att.classSession.startsAt < earliest
? att.classSession.startsAt
: earliest,
null,
);
const enrolledAt =
earliestAttendance && earliestAttendance < attendee.createdAt
? earliestAttendance
: attendee.createdAt;
return {
attendeeId: attendee.id,
fullName: attendee.fullName,
enrolledAt: enrolledAt.toISOString(),
sessions: memberSessions(
sessionsByGroup.get(group.id) ?? [],
attendeeAttendances,
),
};
}),
}); });
// Why there is risk, over every member and not only the urgent ones sent to
// the client. Disjoint: an absence streak counts in the first and only
// there; the second groups the rest (inactivity or a declining trend).
const atRisk = resumen.urgentes.filter((member) => member.level !== 'ok');
const absenceStreakCount = atRisk.filter(
(member) => member.consecutiveAbsences >= ATTENDANCE_RISK_RULES.attentionAbsenceStreak,
).length;
const urgentes: UrgentMemberSummary[] = resumen.urgentes const urgentes: UrgentMemberSummary[] = resumen.urgentes
.slice(0, URGENT_MEMBERS_LIMIT) .slice(0, URGENT_MEMBERS_LIMIT)
.map((urgente) => ({ .map((urgente) => ({
@@ -233,7 +168,14 @@ function buildSummaryFields(
attendanceRate: urgente.attendanceRate, attendanceRate: urgente.attendanceRate,
})); }));
const riskLevel: GroupRiskLevel = resumen.peorNivel ? (toRiskLevel(resumen.peorNivel) ?? 'NONE') : 'NONE';
return { return {
groupId: group.id,
groupName: group.name,
riskLevel,
absenceStreakCount,
lowAttendanceCount: atRisk.length - absenceStreakCount,
riesgoAlto: resumen.riesgoAlto, riesgoAlto: resumen.riesgoAlto,
atencion: resumen.atencion, atencion: resumen.atencion,
ok: resumen.ok, ok: resumen.ok,
@@ -244,10 +186,6 @@ function buildSummaryFields(
}; };
} }
function bump(counter: Map<string, number>, key: string) {
counter.set(key, (counter.get(key) ?? 0) + 1);
}
function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> { function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, AttendanceRow[]> {
const byAttendee = new Map<string, AttendanceRow[]>(); const byAttendee = new Map<string, AttendanceRow[]>();
for (const row of rows) { for (const row of rows) {
@@ -257,25 +195,3 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
} }
return byAttendee; return byAttendee;
} }
/* The universe of classes is the group's, not the `Attendance` rows'.
Attendance is recorded attendee by attendee and only when someone marks a
class, so "this class happened and this attendee has no record" is a real
and frequent state, not an absence. If the list were built from the
attendance rows those classes wouldn't exist and the streak wouldn't break:
two absences separated by an unmarked class would count as three in a row.
The domain already treats them as neutral (`status: null`), so all that is
left here is to pick the right universe and keep the criterion on one side.
`sessions` comes from most recent to oldest, so keeping the first
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
and not global, so a group with a long history doesn't steal window from
the groups listed after it. */
function memberSessions(sessions: SessionRow[], attendances: AttendanceRow[]): MemberClassSession[] {
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
sessionId: session.id,
startsAt: session.startsAt.toISOString(),
status: statusBySession.get(session.id) ?? null,
}));
}

View File

@@ -6,24 +6,21 @@ import type {
StudentAtRisk, StudentAtRisk,
StudentsAtRisk, StudentsAtRisk,
} from '@gruperly/shared'; } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { ok, summarizeMemberAttendance } from '@gruperly/shared';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access'; import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
import { import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
classifyRisk, import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
lastAttendedAt,
monthlyAttendanceRate,
trailingAbsentStreak,
} from '../../lib/risk';
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case'; import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
type GetStudentsAtRiskDeps = { type GetStudentsAtRiskDeps = {
db?: AnalyticsAccessDb & Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>; db?: AnalyticsAccessDb & StudentsAtRiskDb;
now?: Date; now?: Date;
}; };
type AttendanceStreamRow = { type AttendanceStreamRow = {
attendeeId: string; attendeeId: string;
classSessionId: string;
status: AttendanceStatus; status: AttendanceStatus;
classSession: { startsAt: Date }; classSession: { startsAt: Date };
}; };
@@ -37,72 +34,13 @@ export class GetStudentsAtRisk {
): Promise<Result<StudentsAtRisk, ProblemDetails>> { ): Promise<Result<StudentsAtRisk, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date(); const now = this.deps.now ?? new Date();
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
const access = await findGroupForUser(db, groupId, userId); const access = await findGroupForUser(db, groupId, userId);
if (!access.ok) { if (!access.ok) {
return access; return access;
} }
const [windowSessions, attendees, attendances] = await Promise.all([ const atRisk = await findStudentsAtRisk(db, groupId, now);
db.classSession.findMany({
where: { groupId, startsAt: { gte: since } },
select: { id: true },
}),
db.attendee.findMany({
where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true },
}),
db.attendance.findMany({
where: { attendee: { groupId } },
select: {
attendeeId: true,
status: true,
classSession: { select: { startsAt: true } },
},
orderBy: { classSession: { startsAt: 'desc' } },
}),
]);
const totalWindowSessions = windowSessions.length;
const streamByAttendee = groupAttendanceByAttendee(attendances);
const atRisk: StudentAtRisk[] = [];
for (const attendee of attendees) {
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
status: row.status,
occurredAt: row.classSession.startsAt,
}));
const consecutiveAbsences = trailingAbsentStreak(stream);
const attendedAt = lastAttendedAt(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
totalWindowSessions,
);
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
if (!riskLevel) {
continue;
}
atRisk.push({
attendeeId: attendee.id,
fullName: attendee.fullName,
phone: attendee.phone,
riskLevel,
consecutiveAbsences,
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
monthlyAttendanceRate: monthlyRate,
});
}
atRisk.sort((a, b) => {
if (a.riskLevel !== b.riskLevel) {
return a.riskLevel === 'HIGH' ? -1 : 1;
}
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
return b.consecutiveAbsences - a.consecutiveAbsences;
}
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
});
return ok({ return ok({
groupName: access.value.name, groupName: access.value.name,
@@ -111,6 +49,88 @@ export class GetStudentsAtRisk {
} }
} }
export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
/**
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
* the "Alumnos en riesgo" screen and the weekly re-engagement job, and judged
* with the same domain rule as the group listing and Home
* (`summarizeMemberAttendance`), so every screen agrees on who is at risk.
* Does not check access: callers do.
*/
export async function findStudentsAtRisk(
db: StudentsAtRiskDb,
groupId: string,
now: Date,
): Promise<StudentAtRisk[]> {
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
const [windowSessions, attendees, attendances] = await Promise.all([
db.classSession.findMany({
where: { groupId, startsAt: { gte: since } },
select: { id: true, startsAt: true },
orderBy: { startsAt: 'desc' },
}),
db.attendee.findMany({
where: { groupId, status: 'ACTIVE' },
select: { id: true, fullName: true, phone: true, createdAt: true },
}),
db.attendance.findMany({
where: { attendee: { groupId } },
select: {
attendeeId: true,
classSessionId: true,
status: true,
classSession: { select: { startsAt: true } },
},
orderBy: { classSession: { startsAt: 'desc' } },
}),
]);
const totalWindowSessions = windowSessions.length;
const streamByAttendee = groupAttendanceByAttendee(attendances);
const atRisk: StudentAtRisk[] = [];
for (const attendee of attendees) {
const rows = streamByAttendee.get(attendee.id) ?? [];
const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now);
const riskLevel = toRiskLevel(signals.level);
if (!riskLevel) {
continue;
}
// Display only: the verdict is the domain's. The rate keeps counting
// unrecorded classes as missed, which is what "asistencia mensual" says.
const stream = rows.map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt }));
const consecutiveAbsences = signals.consecutiveAbsences;
const attendedAt = lastAttendedAt(stream);
const monthlyRate = monthlyAttendanceRate(
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
totalWindowSessions,
);
atRisk.push({
attendeeId: attendee.id,
fullName: attendee.fullName,
phone: attendee.phone,
riskLevel,
consecutiveAbsences,
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
monthlyAttendanceRate: monthlyRate,
});
}
atRisk.sort((a, b) => {
if (a.riskLevel !== b.riskLevel) {
return a.riskLevel === 'HIGH' ? -1 : 1;
}
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
return b.consecutiveAbsences - a.consecutiveAbsences;
}
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
});
return atRisk;
}
function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> { function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> {
const byAttendee = new Map<string, AttendanceStreamRow[]>(); const byAttendee = new Map<string, AttendanceStreamRow[]>();
for (const row of rows) { for (const row of rows) {

View File

@@ -0,0 +1,81 @@
import type { AttendanceRiskLevel, AttendanceStatus, MemberAttendance, MemberClassSession, RiskLevel } from '@gruperly/shared';
/* How many classes we look back per attendee. That is the real ceiling of the
model: `class_sessions` are not created on their own, they get materialized
when someone opens "today's classes", so pulling years of rows makes no
sense. 20 classes is enough for the streak, for the 6-class window and for
the attendance rate the card shows. */
export const MEMBER_HISTORY_LIMIT = 20;
export type MemberAttendeeRow = { id: string; fullName: string; createdAt: Date };
export type MemberSessionRow = { id: string; startsAt: Date };
export type MemberAttendanceRow = {
classSessionId: string;
status: AttendanceStatus;
classSession: { startsAt: Date };
};
/**
* The input of the domain risk rule (`summarizeMemberAttendance` in shared) for
* one attendee. The group listing, Home, the "Alumnos en riesgo" screen and the
* re-engagement job all build it here, so they can't disagree on who is at risk.
*
* `groupSessions` must come most recent first (as the queries order them).
*/
export function toMemberAttendance(
attendee: MemberAttendeeRow,
groupSessions: MemberSessionRow[],
attendances: MemberAttendanceRow[],
): MemberAttendance {
// If the attendee has attendances before their enrollment date in the DB
// (e.g. created today but with past classes already recorded), their
// effective join date is the first class they were marked for.
const earliestAttendance = attendances.reduce<Date | null>(
(earliest, att) =>
!earliest || att.classSession.startsAt < earliest ? att.classSession.startsAt : earliest,
null,
);
const enrolledAt =
earliestAttendance && earliestAttendance < attendee.createdAt
? earliestAttendance
: attendee.createdAt;
return {
attendeeId: attendee.id,
fullName: attendee.fullName,
enrolledAt: enrolledAt.toISOString(),
sessions: memberSessions(groupSessions, attendances),
};
}
/** The domain level as the at-risk endpoints speak it; `null` for `ok`. */
export function toRiskLevel(level: AttendanceRiskLevel): RiskLevel | null {
if (level === 'riesgo_alto') return 'HIGH';
if (level === 'atencion') return 'MEDIUM';
return null;
}
/* The universe of classes is the group's, not the `Attendance` rows'.
Attendance is recorded attendee by attendee and only when someone marks a
class, so "this class happened and this attendee has no record" is a real
and frequent state, not an absence. If the list were built from the
attendance rows those classes wouldn't exist and the streak wouldn't break:
two absences separated by an unmarked class would count as three in a row.
The domain already treats them as neutral (`status: null`), so all that is
left here is to pick the right universe and keep the criterion on one side.
`sessions` comes from most recent to oldest, so keeping the first
`MEMBER_HISTORY_LIMIT` keeps the recent classes. The cut is per attendee
and not global, so a group with a long history doesn't steal window from
the groups listed after it. */
function memberSessions(
sessions: MemberSessionRow[],
attendances: MemberAttendanceRow[],
): MemberClassSession[] {
const statusBySession = new Map(attendances.map((row) => [row.classSessionId, row.status]));
return sessions.slice(0, MEMBER_HISTORY_LIMIT).map((session) => ({
sessionId: session.id,
startsAt: session.startsAt.toISOString(),
status: statusBySession.get(session.id) ?? null,
}));
}

View File

@@ -3,27 +3,6 @@ export type AttendanceStreamEntry = {
occurredAt: Date; occurredAt: Date;
}; };
export type RiskLevel = 'HIGH' | 'MEDIUM';
/** Minimum streak of unexcused absences that already triggers risk. */
export const MIN_RISK_ABSENCE_STREAK = 2;
/** Monthly attendance (30-day window) below which there is risk. */
export const MIN_RISK_MONTHLY_RATE = 50;
// Counts the consecutive unexcused absences from the most recent class.
// Takes the list sorted from most recent to oldest; PRESENT and EXCUSED break the chain.
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
let streak = 0;
for (const entry of entries) {
if (entry.status !== 'ABSENT') {
break;
}
streak += 1;
}
return streak;
}
// Date of the last class the attendee showed up to (PRESENT), or null. // Date of the last class the attendee showed up to (PRESENT), or null.
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null { export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
for (const entry of entries) { for (const entry of entries) {
@@ -46,17 +25,3 @@ export function monthlyAttendanceRate(
const present = entries.filter((entry) => entry.status === 'PRESENT').length; const present = entries.filter((entry) => entry.status === 'PRESENT').length;
return Math.round((present / totalSessions) * 100); return Math.round((present / totalSessions) * 100);
} }
// HIGH >= 3 consecutive absences; MEDIUM == 2 in a row or monthly attendance < 50%.
export function classifyRisk(
consecutiveAbsences: number,
monthlyRate: number,
): RiskLevel | null {
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK + 1) {
return 'HIGH';
}
if (consecutiveAbsences >= MIN_RISK_ABSENCE_STREAK || monthlyRate < MIN_RISK_MONTHLY_RATE) {
return 'MEDIUM';
}
return null;
}

View File

@@ -8,10 +8,12 @@ import type {
import { err, ok } from '@gruperly/shared'; 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 { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type BulkCreateAttendeesDeps = { type BulkCreateAttendeesDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee'>; db?: Pick<PrismaClient, 'group' | 'attendee'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
export class BulkCreateAttendeesUseCase { export class BulkCreateAttendeesUseCase {
@@ -88,6 +90,16 @@ export class BulkCreateAttendeesUseCase {
}); });
} }
// All or nothing: a partial import that stops at the limit is harder to
// reason about than a clear "your plan allows N".
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
group.createdById,
toCreateData.length,
);
if (!allowed.ok) {
return allowed;
}
const createdRecords: AttendeeRecord[] = []; const createdRecords: AttendeeRecord[] = [];
for (const data of toCreateData) { for (const data of toCreateData) {
const record = await db.attendee.create({ data }); const record = await db.attendee.create({ data });

View File

@@ -9,10 +9,12 @@ import {
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 { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers'; import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
type CreateAttendeeDeps = { type CreateAttendeeDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
type CreateAttendeeOptions = { type CreateAttendeeOptions = {
@@ -106,6 +108,12 @@ export class CreateAttendeeUseCase {
} }
} }
// The owner's plan pays for the attendee, whoever adds it.
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(group.createdById);
if (!allowed.ok) {
return allowed;
}
const attendee = await db.attendee.create({ const attendee = await db.attendee.create({
data: { data: {
groupId, groupId,

View File

@@ -0,0 +1,19 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { GetAttentionOverview } from './use-case';
const route = new Hono();
route.get('/', async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const useCase = new GetAttentionOverview();
const result = await useCase.execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,181 @@
import type { Prisma } from '@generated/prisma/client';
import type {
AttendanceStatus,
AttentionGroup,
AttentionMember,
AttentionOverview,
ProblemDetails,
Result,
StudentAlertType,
} from '@gruperly/shared';
import { applyResolutions, computeStudentAlerts, countryCodeSchema, ok, toWhatsappE164 } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
type GetAttentionOverviewDeps = {
db?: {
group: Prisma.GroupDelegate;
attendee: Prisma.AttendeeDelegate;
classSession: Prisma.ClassSessionDelegate;
attendance: Prisma.AttendanceDelegate;
payment: Prisma.PaymentDelegate;
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
user: Prisma.UserDelegate;
};
now?: Date;
};
type GroupRow = { id: string; name: string; capacity: number | null };
type AttendeeRow = {
id: string;
groupId: string;
fullName: string;
phone: string | null;
guardianPhone: string | null;
createdAt: Date;
};
type SessionRow = { id: string; groupId: string; startsAt: Date };
type AttendanceRow = {
attendeeId: string;
classSessionId: string;
status: AttendanceStatus;
classSession: { startsAt: Date };
};
type PaymentRow = {
id: string;
attendeeId: string;
amount: Prisma.Decimal;
currency: string;
dueDate: Date;
checkoutUrl: string | null;
};
type ResolutionRow = { attendeeId: string; kind: keyof typeof ALERT_KIND_TO_TYPE; signature: string };
/* Every ACTIVE member of the user's groups with their alerts ("Requiere
atención"). The list screen draws all the avatars from here, so it returns
members without alerts too. The rule is `computeStudentAlerts` (shared) over
the same attendance input the risk overview builds (`toMemberAttendance`). */
export class GetAttentionOverview {
constructor(private readonly deps: GetAttentionOverviewDeps = {}) {}
async execute(userId: string): Promise<Result<AttentionOverview, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const groups = (await db.group.findMany({
where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
select: { id: true, name: true, capacity: true },
orderBy: { createdAt: 'asc' },
})) as GroupRow[];
if (groups.length === 0) {
return ok({ groups: [] });
}
const groupIds = groups.map((group) => group.id);
const [owner, attendees, sessions, attendances, payments, resolutions] = await Promise.all([
// Phones are stored the way people write them (`11 2345-6789`): the
// professor's country settles the calling code, as in the WhatsApp jobs.
db.user.findUnique({ where: { id: userId }, select: { country: true } }),
db.attendee.findMany({
where: { groupId: { in: groupIds }, status: 'ACTIVE' },
select: { id: true, groupId: true, fullName: true, phone: true, guardianPhone: true, createdAt: true },
orderBy: { createdAt: 'asc' },
}) as Promise<AttendeeRow[]>,
// Past classes only, most recent first: `toMemberAttendance` keeps the
// last 20 per attendee, more than the 6-class window needs.
db.classSession.findMany({
where: { groupId: { in: groupIds }, startsAt: { lte: now } },
select: { id: true, groupId: true, startsAt: true },
orderBy: { startsAt: 'desc' },
}) as Promise<SessionRow[]>,
db.attendance.findMany({
where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
select: {
attendeeId: true,
classSessionId: true,
status: true,
classSession: { select: { startsAt: true } },
},
}) as Promise<AttendanceRow[]>,
db.payment.findMany({
where: {
groupId: { in: groupIds },
status: 'OVERDUE',
attendee: { status: 'ACTIVE' },
// A fee the student reported (with a receipt) is out of the alert while
// the teacher reviews it; a rejection brings it back.
reportedItems: { none: { reportedPayment: { status: 'REPORTED' } } },
},
select: { id: true, attendeeId: true, amount: true, currency: true, dueDate: true, checkoutUrl: true },
orderBy: { dueDate: 'asc' },
}) as Promise<PaymentRow[]>,
db.attendeeAlertResolution.findMany({
where: { attendee: { groupId: { in: groupIds } } },
select: { attendeeId: true, kind: true, signature: true },
}) as Promise<ResolutionRow[]>,
]);
const country = countryCodeSchema.safeParse(owner?.country);
const sessionsByGroup = groupBy(sessions, (session) => session.groupId);
const attendanceByAttendee = groupBy(attendances, (row) => row.attendeeId);
const paymentsByAttendee = groupBy(payments, (row) => row.attendeeId);
const resolutionsByAttendee = groupBy(resolutions, (row) => row.attendeeId);
const attendeesByGroup = groupBy(attendees, (attendee) => attendee.groupId);
const items: AttentionGroup[] = groups.map((group) => ({
groupId: group.id,
groupName: group.name,
capacity: group.capacity,
members: (attendeesByGroup.get(group.id) ?? []).map((attendee): AttentionMember => {
const overduePayments = (paymentsByAttendee.get(attendee.id) ?? []).map((payment) => ({
id: payment.id,
amount: Number(payment.amount),
currency: payment.currency,
dueDate: payment.dueDate.toISOString(),
checkoutUrl: payment.checkoutUrl,
}));
const alerts = computeStudentAlerts(
{
attendance: toMemberAttendance(
attendee,
sessionsByGroup.get(group.id) ?? [],
attendanceByAttendee.get(attendee.id) ?? [],
),
overduePayments,
},
now,
);
const resolved = (resolutionsByAttendee.get(attendee.id) ?? []).map((row) => ({
tipo: ALERT_KIND_TO_TYPE[row.kind] as StudentAlertType,
firma: row.signature,
}));
const phone = attendee.phone ?? attendee.guardianPhone;
return {
attendeeId: attendee.id,
fullName: attendee.fullName,
phone,
whatsappPhone: phone ? toWhatsappE164(phone, country.success ? country.data : null) : null,
alerts: applyResolutions(alerts, resolved),
overduePayments,
};
}),
}));
return ok({ groups: items });
}
}
function groupBy<T>(rows: T[], key: (row: T) => string): Map<string, T[]> {
const map = new Map<string, T[]>();
for (const row of rows) {
const list = map.get(key(row)) ?? [];
list.push(row);
map.set(key(row), list);
}
return map;
}

View File

@@ -0,0 +1,23 @@
import type { ResolveAlert } from '@gruperly/shared';
import { ResolveAlertSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { ResolveStudentAlert } from './use-case';
const route = new Hono();
route.post('/:attendeeId/resolve', validate.json(ResolveAlertSchema), async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const payload = c.req.valid('json') as ResolveAlert;
const useCase = new ResolveStudentAlert();
const result = await useCase.execute(c.req.param('attendeeId'), user.id, payload);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,49 @@
import type { Prisma } from '@generated/prisma/client';
import type { ProblemDetails, ResolveAlert, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { ALERT_TYPE_TO_KIND } from '../../lib/alert-kind';
type ResolveAlertDeps = {
db?: {
attendee: Prisma.AttendeeDelegate;
attendeeAlertResolution: Prisma.AttendeeAlertResolutionDelegate;
};
};
export type ResolveAlertResult = ResolveAlert & { attendeeId: string };
/* "Resuelto": stores the signature of the alert the professor saw. One row per
attendee and type, overwritten on each resolve, so the table never grows past
two rows per attendee. An attendee outside the user's groups is a 404, not a
403: we don't confirm that the id exists. */
export class ResolveStudentAlert {
constructor(private readonly deps: ResolveAlertDeps = {}) {}
async execute(
attendeeId: string,
userId: string,
payload: ResolveAlert,
): Promise<Result<ResolveAlertResult, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const attendee = await db.attendee.findFirst({
where: { id: attendeeId, group: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput },
select: { id: true },
});
if (!attendee) {
return err(notFoundResourceProblem('Attendee', attendeeId));
}
const kind = ALERT_TYPE_TO_KIND[payload.tipo];
await db.attendeeAlertResolution.upsert({
where: { attendeeId_kind: { attendeeId, kind } },
create: { attendeeId, kind, signature: payload.firma, resolvedById: userId },
update: { signature: payload.firma, resolvedById: userId, resolvedAt: new Date() },
});
return ok({ attendeeId, tipo: payload.tipo, firma: payload.firma });
}
}

View File

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

View File

@@ -0,0 +1,13 @@
import type { StudentAlertKind } from '@generated/prisma/client';
import type { StudentAlertType } from '@gruperly/shared';
/** The API speaks Spanish (`asistencia` / `pago`), the table speaks enums. */
export const ALERT_KIND_TO_TYPE: Record<StudentAlertKind, StudentAlertType> = {
ATTENDANCE: 'asistencia',
PAYMENT: 'pago',
};
export const ALERT_TYPE_TO_KIND: Record<StudentAlertType, StudentAlertKind> = {
asistencia: 'ATTENDANCE',
pago: 'PAYMENT',
};

View File

@@ -0,0 +1,10 @@
import { Hono } from 'hono';
import getOverviewRoute from './features/get-overview/route';
import resolveRoute from './features/resolve/route';
const routes = new Hono();
routes.route('/', getOverviewRoute);
routes.route('/', resolveRoute);
export default routes;

View File

@@ -14,6 +14,7 @@ export const auth = betterAuth({
emailAndPassword: { emailAndPassword: {
enabled: true, enabled: true,
minPasswordLength: 8, minPasswordLength: 8,
revokeSessionsOnPasswordReset: true,
sendResetPassword: async ({ user, url }) => { sendResetPassword: async ({ user, url }) => {
await emailProvider.sendPasswordResetEmail({ await emailProvider.sendPasswordResetEmail({
email: user.email, email: user.email,

View File

@@ -0,0 +1,15 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { CancelSubscription } from './use-case';
const route = new Hono();
route.post('/cancel', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const result = await new CancelSubscription().execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,49 @@
import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { noActiveSubscriptionProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { subscriptionRefOf } from '../../lib';
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
type CancelSubscriptionDeps = {
db?: Pick<PrismaClient, 'billingSubscription'>;
providers?: BillingProviderResolver;
};
/**
* Stops the monthly charge with the provider that collects it. `paidThrough`
* stays: the professor keeps Pro until the end of what they already paid
* (plus the grace period).
*/
export class CancelSubscription {
constructor(private readonly deps: CancelSubscriptionDeps = {}) {}
async execute(userId: string): Promise<Result<{ status: SubscriptionStatus }, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const subscription = await db.billingSubscription.findUnique({ where: { userId } });
if (
!subscription
|| (!subscription.externalId && !subscription.checkoutRef)
|| subscription.status === 'CANCELLED'
) {
return err(noActiveSubscriptionProblem());
}
try {
await (this.deps.providers ?? getBillingProvider)(subscription.provider).cancel(
subscriptionRefOf(subscription),
);
} catch (error) {
return err(toBillingProblem(error));
}
await db.billingSubscription.update({
where: { id: subscription.id },
data: { status: 'CANCELLED', nextPaymentDate: null },
});
return ok({ status: 'CANCELLED' });
}
}

View File

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

View File

@@ -0,0 +1,36 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { BillingChargeList, BillingChargesQuery, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma';
import { toBillingChargeDto } from '../../lib';
type ListBillingChargesDeps = { db?: Pick<PrismaClient, 'billingCharge'> };
/** The professor's own Pro charges, newest first. */
export class ListBillingCharges {
constructor(private readonly deps: ListBillingChargesDeps = {}) {}
async execute(
query: BillingChargesQuery,
userId: string,
): Promise<Result<BillingChargeList, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const where = { subscription: { userId } };
const [charges, total] = await Promise.all([
db.billingCharge.findMany({
where,
orderBy: { createdAt: 'desc' },
skip: getPaginationOffset(query),
take: query.pageSize,
}),
db.billingCharge.count({ where }),
]);
return ok({
data: charges.map(toBillingChargeDto),
pagination: getPaginationMetadata(query, total),
});
}
}

View File

@@ -0,0 +1,15 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { GetBillingStatus } from './use-case';
const route = new Hono();
route.get('/status', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const result = await new GetBillingStatus().execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,78 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import { notFoundResourceProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { countryOf, PlanGuard, SyncSubscription } from '../../lib';
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
type GetBillingStatusDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
guard?: PlanGuard;
sync?: Pick<SyncSubscription, 'execute'>;
providers?: BillingProviderResolver;
now?: () => Date;
};
export class GetBillingStatus {
constructor(private readonly deps: GetBillingStatusDeps = {}) {}
async execute(userId: string): Promise<Result<BillingStatusDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const now = this.deps.now?.() ?? new Date();
const user = await db.user.findUnique({ where: { id: userId } });
if (!user) return err(notFoundResourceProblem('User', userId));
const country = countryOf(user);
let subscription = await db.billingSubscription.findUnique({ where: { userId } });
// Coming back from the provider's checkout, the webhook may not have
// arrived yet (or may never arrive in local dev): ask directly, throttled.
if (
subscription?.status === 'PENDING'
&& (subscription.externalId || subscription.checkoutRef)
&& (!subscription.lastSyncedAt
|| now.getTime() - subscription.lastSyncedAt.getTime() > PENDING_SYNC_INTERVAL_MS)
) {
const synced = await (this.deps.sync ?? new SyncSubscription()).execute(subscription.id);
if (synced.ok && synced.value.synced) {
subscription = await db.billingSubscription.findUnique({ where: { userId } });
}
}
const entitlements = await (this.deps.guard ?? new PlanGuard()).getEntitlements(userId);
// A live subscription keeps the price it was created with; otherwise the
// current price of the country is what subscribing would cost.
const live = subscription && subscription.status !== 'CANCELLED' ? subscription : null;
// An authorized subscription stays with its provider; a new attempt (or
// retrying a PENDING one) goes to the country's current provider.
const provider = (this.deps.providers ?? getBillingProvider)(
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
);
return ok({
plan: entitlements.plan,
status: subscription?.status ?? null,
readOnly: entitlements.readOnly,
graceUntil: entitlements.graceUntil?.toISOString() ?? null,
paidThrough: subscription?.paidThrough?.toISOString() ?? null,
nextPaymentDate:
subscription?.status === 'AUTHORIZED'
? (subscription.nextPaymentDate?.toISOString() ?? null)
: null,
payerEmail: subscription?.payerEmail ?? null,
priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country],
currency: live ? live.currency : COUNTRY_CURRENCY[country],
country,
provider: provider.id,
availableInCountry: provider.isAvailable(country),
enforced: entitlements.enforced,
usage: entitlements.usage,
limits: entitlements.limits,
});
}
}

View File

@@ -0,0 +1,21 @@
import type { SubscribeInput } from '@gruperly/shared';
import { SubscribeInputSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { Subscribe } from './use-case';
const route = new Hono();
// Returns `{ checkoutUrl }`: the browser navigates there to authorize the
// subscription in Mercado Pago, the same way `/mp/connect` works.
route.post('/subscribe', validate.json(SubscribeInputSchema), async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const input = c.req.valid('json') as SubscribeInput;
const result = await new Subscribe().execute(user.id, input);
return resultJson(c, result, { status: 201 });
});
export default route;

View File

@@ -0,0 +1,115 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
import {
billingNotAvailableProblem,
notFoundResourceProblem,
payerEmailRequiredProblem,
subscriptionAlreadyActiveProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getWebOrigin } from '@/modules/mp/lib';
import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
type SubscribeDeps = {
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
providers?: BillingProviderResolver;
webOrigin?: string;
now?: () => Date;
};
/**
* Starts a monthly Pro subscription with the billing provider of the
* professor's country and returns where the browser goes to authorize it.
*
* The row is written PENDING before calling the provider (it is the source of
* truth, like `Payment` rows in the batch). A previous subscription that was
* never authorized is voided first, with whichever provider it was created, so
* the professor can fix the payer email (or switch country) by trying again.
*/
export class Subscribe {
constructor(private readonly deps: SubscribeDeps = {}) {}
async execute(userId: string, input: SubscribeInput): Promise<Result<SubscribeResultDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const providers = this.deps.providers ?? getBillingProvider;
const now = this.deps.now?.() ?? new Date();
const user = await db.user.findUnique({ where: { id: userId } });
if (!user) return err(notFoundResourceProblem('User', userId));
const country = countryOf(user);
const provider = providers(billingProviderForCountry(country));
if (!provider.isAvailable(country)) return err(billingNotAvailableProblem());
if (provider.requiresPayerEmail && !input.payerEmail) return err(payerEmailRequiredProblem());
const existing = await db.billingSubscription.findUnique({ where: { userId } });
if (existing?.status === 'AUTHORIZED') {
return err(subscriptionAlreadyActiveProblem());
}
if ((existing?.externalId || existing?.checkoutRef) && existing.status !== 'CANCELLED') {
try {
await providers(existing.provider).cancel(subscriptionRefOf(existing));
} catch {
// A stale attempt that cannot be voided is harmless: it was never
// authorized, and its notifications no longer match our row.
logger.warn({ userId }, 'Could not void the previous Pro subscription attempt');
}
}
const amount = PRO_PRICE_BY_COUNTRY[country];
const currency = COUNTRY_CURRENCY[country];
const fields = {
country,
currency,
amount,
provider: provider.id,
// Stripe asks for the email in its checkout; the sync stores the real one.
payerEmail: input.payerEmail ?? user.email,
};
const row = await db.billingSubscription.upsert({
where: { userId },
create: { userId, ...fields, status: 'PENDING', requestedAt: now },
update: {
...fields,
status: 'PENDING',
requestedAt: now,
externalId: null,
checkoutRef: null,
authorizedAt: null,
nextPaymentDate: null,
},
});
// Re-subscribing before the paid period ends: the first charge waits for it,
// so nobody pays twice for the same month.
const startDate = row.paidThrough && row.paidThrough > now ? row.paidThrough : undefined;
let started: Awaited<ReturnType<typeof provider.start>>;
try {
started = await provider.start({
userId,
country,
amount,
currency,
payerEmail: input.payerEmail ?? null,
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
startDate,
});
} catch (error) {
logger.error({ userId, provider: provider.id }, 'Could not start the Pro subscription');
return err(toBillingProblem(error));
}
await db.billingSubscription.update({
where: { id: row.id },
data: { externalId: started.externalId, checkoutRef: started.checkoutRef, lastSyncedAt: now },
});
return ok({ checkoutUrl: started.checkoutUrl });
}
}

View File

@@ -0,0 +1,41 @@
import type { BillingProviderId } from '@gruperly/shared';
import type { Context } from 'hono';
import { Hono } from 'hono';
import { logger } from '@/logger';
import { type BillingWebhookFailure, HandleBillingWebhook } from './use-case';
/**
* Public endpoints (see `isPublicApiRequest`): the providers call them, not the
* browser, so there is no session; each adapter checks its own signature.
* Mercado Pago has one URL per country, because each country is a different
* Gruperly account with its own secret; Stripe is a single account.
*/
const route = new Hono();
const FAILURE_STATUS: Record<BillingWebhookFailure, 401 | 404 | 500 | 503> = {
invalid_signature: 401,
unknown_country: 404,
not_configured: 503,
sync_failed: 500,
};
async function handle(c: Context, providerId: BillingProviderId, routeParam: string | null) {
const result = await new HandleBillingWebhook().execute(providerId, {
routeParam,
rawBody: await c.req.text(),
headers: c.req.raw.headers,
query: new URL(c.req.url).searchParams,
});
if (!result.ok) {
logger.warn({ provider: providerId, reason: result.error }, 'Billing webhook rejected');
return c.body(null, FAILURE_STATUS[result.error]);
}
return c.json({ received: true, duplicate: result.value.duplicate });
}
route.post('/webhooks/mp/:country', (c) => handle(c, 'MERCADO_PAGO', c.req.param('country')));
route.post('/webhooks/stripe', (c) => handle(c, 'STRIPE', null));
export default route;

View File

@@ -0,0 +1,82 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { BillingProviderId, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { SyncSubscription } from '../../lib';
import {
type BillingProviderResolver,
type BillingWebhookFailure,
type BillingWebhookRequest,
getBillingProvider,
} from '../../providers';
export type { BillingWebhookFailure, BillingWebhookRequest } from '../../providers';
type HandleBillingWebhookDeps = {
db?: Pick<PrismaClient, 'billingWebhookEvent'>;
providers?: BillingProviderResolver;
sync?: Pick<SyncSubscription, 'byExternalId'>;
};
/** Prisma's unique-constraint violation: this delivery was already processed. */
const UNIQUE_VIOLATION = 'P2002';
/**
* Applies one provider notification about a Pro subscription.
*
* The provider adapter checks the signature and says which subscription the
* notification is about; the subscription is then fetched again from the
* provider and synced (`SyncSubscription`). The body is never trusted for a
* status. If syncing fails the dedupe key is removed, so the provider's retry
* gets another chance (same rule as the WhatsApp webhook).
*/
export class HandleBillingWebhook {
constructor(private readonly deps: HandleBillingWebhookDeps = {}) {}
async execute(
providerId: BillingProviderId,
request: BillingWebhookRequest,
): Promise<Result<{ duplicate: boolean; applied: boolean }, BillingWebhookFailure>> {
const parsed = await (this.deps.providers ?? getBillingProvider)(providerId).parseWebhook(request);
if (!parsed.ok) return parsed;
const hint = parsed.value;
if (!hint.externalId) return ok({ duplicate: false, applied: false });
const db = this.deps.db ?? prisma;
const dedupe = hint.dedupeKey ? { source: hint.source, dedupeKey: hint.dedupeKey } : null;
if (dedupe) {
try {
await db.billingWebhookEvent.create({ data: dedupe });
} catch (error) {
if ((error as { code?: string }).code === UNIQUE_VIOLATION) {
return ok({ duplicate: true, applied: false });
}
throw error;
}
}
const unburn = async () => {
if (!dedupe) return;
await db.billingWebhookEvent
.delete({ where: { source_dedupeKey: dedupe } })
.catch(() => undefined);
};
try {
const synced = await (this.deps.sync ?? new SyncSubscription()).byExternalId(
providerId,
hint.externalId,
hint.country,
);
if (!synced.ok) {
await unburn();
return err('sync_failed');
}
return ok({ duplicate: false, applied: synced.value.synced });
} catch {
await unburn();
return err('sync_failed');
}
}
}

View File

@@ -0,0 +1,4 @@
export { startBillingJobs } from './jobs';
export { PlanGuard } from './lib/entitlements';
export { planReadOnlyMiddleware } from './lib/read-only-middleware';
export { default as billingRoutes } from './routes';

View File

@@ -0,0 +1,2 @@
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
export { startBillingJobs } from './schedule';

View File

@@ -0,0 +1,71 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { SyncSubscription } from '../lib';
const BATCH_SIZE = 50;
const DAY_MS = 24 * 60 * 60 * 1000;
/** A subscription nobody authorized within this window is given up. */
const PENDING_TTL_MS = 7 * DAY_MS;
/** Authorized subscriptions are re-checked at least daily (renewals, cancellations in MP). */
const AUTHORIZED_STALE_MS = DAY_MS;
type ReconcileSubscriptionsDeps = {
db?: Pick<PrismaClient, 'billingSubscription'>;
sync?: Pick<SyncSubscription, 'execute'>;
now?: () => Date;
};
export type ReconcileTotals = { checked: number; synced: number; failed: number; expired: number };
/**
* Polling fallback for the billing webhook: the webhook can be lost, and in
* local dev it usually never arrives. Every sync is idempotent, so the webhook
* and this job racing over the same row is harmless.
*/
export class ReconcileSubscriptions {
constructor(private readonly deps: ReconcileSubscriptionsDeps = {}) {}
async execute(): Promise<ReconcileTotals> {
const db = this.deps.db ?? prisma;
const sync = this.deps.sync ?? new SyncSubscription();
const now = this.deps.now?.() ?? new Date();
const totals: ReconcileTotals = { checked: 0, synced: 0, failed: 0, expired: 0 };
const pendingCutoff = new Date(now.getTime() - PENDING_TTL_MS);
const expired = await db.billingSubscription.updateMany({
where: { status: 'PENDING', requestedAt: { lt: pendingCutoff } },
data: { status: 'CANCELLED' },
});
totals.expired = expired.count;
const staleCutoff = new Date(now.getTime() - AUTHORIZED_STALE_MS);
const rows = await db.billingSubscription.findMany({
where: {
AND: [
{ OR: [{ externalId: { not: null } }, { checkoutRef: { not: null } }] },
{
OR: [
{ status: 'PENDING' },
{
status: { in: ['AUTHORIZED', 'PAUSED'] },
OR: [{ lastSyncedAt: null }, { lastSyncedAt: { lt: staleCutoff } }],
},
],
},
],
},
select: { id: true },
orderBy: { lastSyncedAt: { sort: 'asc', nulls: 'first' } },
take: BATCH_SIZE,
});
for (const row of rows) {
totals.checked += 1;
const result = await sync.execute(row.id);
if (result.ok && result.value.synced) totals.synced += 1;
else if (!result.ok) totals.failed += 1;
}
return totals;
}
}

View File

@@ -0,0 +1,24 @@
import { logger } from '@/logger';
import { ReconcileSubscriptions } from './reconcile-subscriptions';
const RECONCILE_CRON = '*/30 * * * *';
/**
* Registers the billing background jobs. Called once from `server.ts`, with the
* same guards as `startPaymentJobs`: a rejected promise inside Bun's cron would
* crash the process, and `unref` keeps the job from holding it alive.
*/
export function startBillingJobs(): void {
Bun.cron(
RECONCILE_CRON,
async () => {
try {
const totals = await new ReconcileSubscriptions().execute();
logger.info(totals, 'Pro subscriptions reconciliation finished');
} catch (error) {
logger.error({ err: error }, 'Pro subscriptions reconciliation failed');
}
},
{ tz: 'UTC' },
).unref();
}

View File

@@ -0,0 +1,16 @@
const DEFAULT_GRACE_DAYS = 7;
/**
* Plan limits only apply with `BILLING_ENFORCEMENT=on`. Anything else (unset
* included) treats everyone as Pro, so the module can ship before the existing
* professors are moved to a plan.
*/
export function isBillingEnforced(env: Record<string, string | undefined> = process.env): boolean {
return env.BILLING_ENFORCEMENT?.trim().toLowerCase() === 'on';
}
/** Days a lapsed Pro keeps working after its last paid period. */
export function getGraceDays(env: Record<string, string | undefined> = process.env): number {
const value = Number(env.BILLING_GRACE_DAYS);
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
}

View File

@@ -0,0 +1,173 @@
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
import {
planFeatureRequiredProblem,
planLimitReachedProblem,
planReadOnlyProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { getGraceDays, isBillingEnforced } from './config';
const DAY_MS = 24 * 60 * 60 * 1000;
export type SubscriptionSnapshot = {
status: SubscriptionStatus;
authorizedAt: Date | null;
paidThrough: Date | null;
};
export type PlanResolution = {
plan: Plan;
/** Set while Pro survives a lapse (failed renewal or cancellation) on grace. */
graceUntil: Date | null;
};
/**
* Pro lasts while a charge covers today, plus the grace period after the last
* paid day. That one rule covers a cancelled subscription (Pro until the end of
* what was paid) and a failed renewal (Mercado Pago keeps retrying meanwhile).
*
* An AUTHORIZED subscription with no approved charge yet is Pro too, for the
* grace period after the authorization: the first charge is in flight.
*/
export function resolvePlan(
subscription: SubscriptionSnapshot | null,
now: Date,
graceDays: number,
): PlanResolution {
if (!subscription) return { plan: 'FREE', graceUntil: null };
const graceMs = graceDays * DAY_MS;
if (subscription.paidThrough) {
if (subscription.paidThrough > now) return { plan: 'PRO', graceUntil: null };
const graceUntil = new Date(subscription.paidThrough.getTime() + graceMs);
return graceUntil > now ? { plan: 'PRO', graceUntil } : { plan: 'FREE', graceUntil: null };
}
if (subscription.status === 'AUTHORIZED' && subscription.authorizedAt) {
const graceUntil = new Date(subscription.authorizedAt.getTime() + graceMs);
if (graceUntil > now) return { plan: 'PRO', graceUntil: null };
}
return { plan: 'FREE', graceUntil: null };
}
/**
* `resolvePlan` written as a query, for listing accounts by plan: a
* subscription is Pro when its paid period (or, before the first charge, its
* authorization) is younger than the grace period. Keep both in step.
*/
export function proSubscriptionWhere(now: Date, graceDays: number): Prisma.BillingSubscriptionWhereInput {
const cutoff = new Date(now.getTime() - graceDays * DAY_MS);
return {
OR: [
{ paidThrough: { gt: cutoff } },
{ paidThrough: null, status: 'AUTHORIZED', authorizedAt: { gt: cutoff } },
],
};
}
export type PlanUsage = { groups: number; attendees: number };
export function exceedsLimits(limits: PlanLimits, usage: PlanUsage): boolean {
return (
(limits.maxGroups !== null && usage.groups > limits.maxGroups)
|| (limits.maxAttendees !== null && usage.attendees > limits.maxAttendees)
);
}
export type Entitlements = PlanResolution & {
limits: PlanLimits;
usage: PlanUsage;
/** Free with more usage than its limits. Always false when not enforced. */
readOnly: boolean;
enforced: boolean;
};
type PlanGuardDeps = {
db?: Pick<PrismaClient, 'billingSubscription' | 'group' | 'attendee'>;
enforced?: boolean;
graceDays?: number;
now?: () => Date;
};
/**
* What a professor's plan allows. Every check is about the **owner** of the
* group (`group.createdById`): an ADMIN acting on someone else's group spends
* the owner's plan, not their own.
*
* With enforcement off the checks pass without touching the database.
*/
export class PlanGuard {
constructor(private readonly deps: PlanGuardDeps = {}) {}
private get enforced(): boolean {
return this.deps.enforced ?? isBillingEnforced();
}
async getEntitlements(ownerId: string): Promise<Entitlements> {
const db = this.deps.db ?? prisma;
const now = this.deps.now?.() ?? new Date();
const [subscription, groups, attendees] = await Promise.all([
db.billingSubscription.findUnique({
where: { userId: ownerId },
select: { status: true, authorizedAt: true, paidThrough: true },
}),
db.group.count({ where: { createdById: ownerId } }),
db.attendee.count({ where: { status: 'ACTIVE', group: { createdById: ownerId } } }),
]);
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
const limits = PLAN_LIMITS[resolution.plan];
const usage = { groups, attendees };
const enforced = this.enforced;
return {
...resolution,
limits,
usage,
readOnly: enforced && exceedsLimits(limits, usage),
enforced,
};
}
async requireWritable(ownerId: string): Promise<Result<void, ProblemDetails>> {
if (!this.enforced) return ok(undefined);
const entitlements = await this.getEntitlements(ownerId);
return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined);
}
async canCreateGroup(ownerId: string): Promise<Result<void, ProblemDetails>> {
if (!this.enforced) return ok(undefined);
const { readOnly, limits, usage } = await this.getEntitlements(ownerId);
if (readOnly) return err(planReadOnlyProblem());
if (limits.maxGroups !== null && usage.groups + 1 > limits.maxGroups) {
return err(planLimitReachedProblem('groups', limits.maxGroups));
}
return ok(undefined);
}
async canAddAttendees(ownerId: string, count = 1): Promise<Result<void, ProblemDetails>> {
if (!this.enforced || count <= 0) return ok(undefined);
const { readOnly, limits, usage } = await this.getEntitlements(ownerId);
if (readOnly) return err(planReadOnlyProblem());
if (limits.maxAttendees !== null && usage.attendees + count > limits.maxAttendees) {
return err(planLimitReachedProblem('attendees', limits.maxAttendees));
}
return ok(undefined);
}
async requireFeature(ownerId: string, feature: PlanFeature): Promise<Result<void, ProblemDetails>> {
return (await this.hasFeature(ownerId, feature))
? ok(undefined)
: err(planFeatureRequiredProblem(feature));
}
async hasFeature(ownerId: string, feature: PlanFeature): Promise<boolean> {
if (!this.enforced) return true;
const { limits } = await this.getEntitlements(ownerId);
return limits[feature];
}
}

View File

@@ -0,0 +1,27 @@
import type { BillingCharge, BillingSubscription } from '@generated/prisma/client';
import type { BillingChargeDto, BillingReturnTo, CountryCode } from '@gruperly/shared';
import { countryCodeSchema, DEFAULT_COUNTRY } from '@gruperly/shared';
export function toBillingChargeDto(charge: BillingCharge): BillingChargeDto {
return {
id: charge.id,
amount: Number(charge.amount.toString()),
currency: charge.currency,
status: charge.status,
paidAt: charge.paidAt?.toISOString() ?? null,
createdAt: charge.createdAt.toISOString(),
};
}
/** The professor's country as stored on the user; Argentina until they pick one. */
export function countryOf(user: { country: string | null } | null): CountryCode {
const parsed = countryCodeSchema.safeParse(user?.country);
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
}
/** Where the billing provider sends the professor after authorizing (or abandoning). */
export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string {
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
}
export type SubscriptionRecord = BillingSubscription;

View File

@@ -0,0 +1,13 @@
export { getGraceDays, isBillingEnforced } from './config';
export {
type Entitlements,
exceedsLimits,
PlanGuard,
type PlanResolution,
type PlanUsage,
proSubscriptionWhere,
resolvePlan,
type SubscriptionSnapshot,
} from './entitlements';
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';

View File

@@ -0,0 +1,29 @@
import type { MiddlewareHandler } from 'hono';
import type { BackendEnv } from '@/http/env';
import { problemJson } from '@/http/problem-details';
import { PlanGuard } from './entitlements';
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
/**
* Blocks writes while the professor's account is read-only (Free with more
* usage than its limits). DELETE stays open: removing attendees is how they get
* back under the limits without paying.
*
* It checks the signed-in user. The create paths (groups, attendees) check the
* group **owner** on their own, so an ADMIN cannot add to a read-only owner's group.
*/
export function planReadOnlyMiddleware(guard: PlanGuard = new PlanGuard()): MiddlewareHandler<BackendEnv> {
return async (c, next) => {
const user = c.get('user');
if (!user || SAFE_METHODS.has(c.req.method) || c.req.method === 'DELETE') {
await next();
return;
}
const writable = await guard.requireWritable(user.id);
if (!writable.ok) return problemJson(c, writable.error);
await next();
};
}

View File

@@ -0,0 +1,164 @@
import type { BillingSubscription, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
import type { BillingProviderId, CountryCode, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
type BillingProviderResolver,
getBillingProvider,
type ProviderCharge,
type ProviderSubscription,
type SubscriptionRef,
toBillingProblem,
} from '../providers';
export type SyncSubscriptionDeps = {
db?: Pick<PrismaClient, 'billingSubscription' | 'billingCharge'>;
providers?: BillingProviderResolver;
now?: () => Date;
};
export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null };
export function subscriptionRefOf(
row: Pick<BillingSubscription, 'country' | 'externalId' | 'checkoutRef'>,
): SubscriptionRef {
return { country: row.country as CountryCode, externalId: row.externalId, checkoutRef: row.checkoutRef };
}
/**
* Brings one subscription row in line with its provider. Shared by the
* webhooks, the reconciliation job and the status endpoint (on read, while
* PENDING). It talks to `row.provider`, never to the country's current one.
*
* Never trusts what a notification says: it asks the provider for the
* subscription and its invoices, checks that the subscription is ours (it
* carries our user id) and only then writes. Re-running it is harmless; every
* write is an upsert or a monotonic `paidThrough`.
*/
export class SyncSubscription {
constructor(private readonly deps: SyncSubscriptionDeps = {}) {}
async execute(subscriptionId: string): Promise<Result<SyncOutcome, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const subscription = await db.billingSubscription.findUnique({ where: { id: subscriptionId } });
if (!subscription || (!subscription.externalId && !subscription.checkoutRef)) {
return ok({ synced: false, status: subscription?.status ?? null });
}
const provider = (this.deps.providers ?? getBillingProvider)(subscription.provider);
const ref = subscriptionRefOf(subscription);
let remote: ProviderSubscription | null;
try {
remote = await provider.fetch(ref);
} catch (error) {
return err(toBillingProblem(error));
}
// Stripe: the checkout was not completed yet, there is nothing to sync.
if (!remote) return ok({ synced: false, status: subscription.status });
if (remote.ownerUserId !== subscription.userId) {
logger.warn({ subscriptionId }, 'Provider subscription does not belong to this subscription');
return ok({ synced: false, status: subscription.status });
}
// The status is what grants Pro (an authorized subscription is Pro during
// the grace days), so failing to list the charges must not leave it
// PENDING: write the status and leave `lastSyncedAt` alone, so the charges
// are retried on the next sync.
let charges: ProviderCharge[] = [];
let chargesSynced = true;
try {
charges = await provider.listCharges({ ...ref, externalId: remote.externalId });
} catch (error) {
chargesSynced = false;
logger.warn({ subscriptionId, err: error }, 'Could not list the subscription charges; syncing the status only');
}
const now = this.deps.now?.() ?? new Date();
let paidThrough = subscription.paidThrough;
for (const charge of charges) {
await db.billingCharge.upsert({
where: { externalId: charge.externalId },
create: {
subscriptionId: subscription.id,
externalId: charge.externalId,
amount: charge.amount,
currency: charge.currency || subscription.currency,
status: charge.status,
paidAt: charge.paidAt,
},
update: { status: charge.status, paidAt: charge.paidAt },
});
if (charge.coveredUntil && (!paidThrough || charge.coveredUntil > paidThrough)) {
paidThrough = charge.coveredUntil;
}
}
const status = remote.status ?? subscription.status;
await db.billingSubscription.update({
where: { id: subscription.id },
data: {
// Stripe only creates the subscription when the checkout completes.
externalId: subscription.externalId ? undefined : remote.externalId,
status,
authorizedAt: status === 'AUTHORIZED' && !subscription.authorizedAt ? now : undefined,
nextPaymentDate: remote.nextPaymentDate,
paidThrough,
payerEmail: remote.payerEmail ?? undefined,
lastSyncedAt: chargesSynced ? now : undefined,
},
});
return ok({ synced: true, status });
}
/**
* Same as `execute`, starting from the provider's subscription id (webhooks).
* A notification can beat our own write of `externalId` (Mercado Pago: the
* professor authorizes faster than our request returns; Stripe: the checkout
* completes before anyone reads the session), so an unknown id falls back to
* the user id the provider holds, once the provider confirms it.
*/
async byExternalId(
providerId: BillingProviderId,
externalId: string,
country: CountryCode | null,
): Promise<Result<SyncOutcome, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const known = await db.billingSubscription.findUnique({ where: { externalId } });
if (known) return this.execute(known.id);
let remote: ProviderSubscription | null;
try {
remote = await (this.deps.providers ?? getBillingProvider)(providerId).fetch({
country,
externalId,
checkoutRef: null,
});
} catch (error) {
return err(toBillingProblem(error));
}
// A cancelled one is a previous attempt being replaced, never the new one.
if (!remote?.ownerUserId || remote.status === 'CANCELLED') {
return ok({ synced: false, status: null });
}
const claimed = await db.billingSubscription.updateMany({
where: {
userId: remote.ownerUserId,
provider: providerId,
externalId: null,
...(country ? { country } : {}),
},
data: { externalId },
});
if (claimed.count === 0) return ok({ synced: false, status: null });
const row = await db.billingSubscription.findUnique({ where: { externalId } });
return row ? this.execute(row.id) : ok({ synced: false, status: null });
}
}

View File

@@ -0,0 +1,124 @@
import type { SubscriptionStatus } from '@generated/prisma/client';
import type { BillingProviderId, CountryCode, ProblemDetails, Result } from '@gruperly/shared';
import { billingNotAvailableProblem, billingProviderErrorProblem } from '@/http/problem-builders';
/**
* The port every Pro billing provider implements. The domain (subscribing,
* cancelling, syncing, the webhook and the reconciliation job) only talks to
* this interface; everything that knows about Mercado Pago or Stripe lives in
* `providers/<name>/`. Same idea as WhatsApp's `MessagingProvider`.
*
* Calls that reach the provider throw on failure: `BillingProviderNotConfigured`
* when Gruperly has no credentials for it, anything else when the provider
* refused or could not be reached. `toBillingProblem` turns either into the
* Problem Details the use-cases answer with.
*/
export type { BillingProviderId };
/** What identifies one subscription at its provider. */
export type SubscriptionRef = {
/** Mercado Pago picks Gruperly's account by country; Stripe ignores it. */
country: CountryCode | null;
/** The provider's subscription id, once it exists. */
externalId: string | null;
/** A checkout started but not completed yet (Stripe Checkout Session). */
checkoutRef: string | null;
};
export type StartSubscriptionInput = {
/** Our user id: the only thing that ties the subscription back to a professor. */
userId: string;
country: CountryCode;
amount: number;
currency: string;
/** Mandatory when `requiresPayerEmail`; otherwise only a pre-fill. */
payerEmail: string | null;
/** Where the provider sends the professor back, completed or not. */
backUrl: string;
/** First charge date; omitted means right after the professor authorizes. */
startDate?: Date;
};
export type StartedSubscription = {
/** Where the browser goes to authorize the subscription. */
checkoutUrl: string;
externalId: string | null;
checkoutRef: string | null;
};
export type ProviderSubscription = {
externalId: string;
/** Our user id as the provider holds it; checked before trusting anything. */
ownerUserId: string | null;
/** `null` for a provider status we do not know: the row keeps its own. */
status: SubscriptionStatus | null;
nextPaymentDate: Date | null;
/** The email the professor actually paid with, when the provider asks for it. */
payerEmail: string | null;
};
export type ChargeStatus = 'approved' | 'pending' | 'rejected';
/** One monthly invoice of a subscription. */
export type ProviderCharge = {
externalId: string;
amount: number;
currency: string | null;
status: ChargeStatus;
paidAt: Date | null;
/** Last day this charge pays for; null unless approved. */
coveredUntil: Date | null;
};
export type BillingWebhookRequest = {
/** The `:country` of `/webhooks/mp/:country`; null for Stripe. */
routeParam: string | null;
rawBody: string;
headers: Headers;
query: URLSearchParams;
};
export type BillingWebhookFailure =
| 'unknown_country'
| 'not_configured'
| 'invalid_signature'
| 'sync_failed';
/** What a verified notification points at. The body is never trusted for a status. */
export type BillingWebhookHint = {
/** The sending account, for deduplication: `mp:<CC>` or `stripe`. */
source: string;
dedupeKey: string | null;
country: CountryCode | null;
/** The subscription to sync; null for events that do not concern one. */
externalId: string | null;
};
export interface BillingProvider {
readonly id: BillingProviderId;
/** Mercado Pago makes the payer log in with the email given up front. */
readonly requiresPayerEmail: boolean;
/** Gruperly has credentials to collect Pro in that country. */
isAvailable(country: CountryCode): boolean;
start(input: StartSubscriptionInput): Promise<StartedSubscription>;
/** `null` while the professor has not completed the checkout. */
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
/** Stops the monthly charge, or voids a checkout never completed. */
cancel(ref: SubscriptionRef): Promise<void>;
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;
}
export class BillingProviderNotConfigured extends Error {
constructor(provider: BillingProviderId) {
super(`Billing provider ${provider} is not configured`);
this.name = 'BillingProviderNotConfigured';
}
}
export function toBillingProblem(error: unknown): ProblemDetails {
return error instanceof BillingProviderNotConfigured
? billingNotAvailableProblem()
: billingProviderErrorProblem();
}

View File

@@ -0,0 +1,32 @@
import type { BillingProviderId } from '@gruperly/shared';
import type { BillingProvider } from './billing-provider';
import { MercadoPagoBillingProvider } from './mercado-pago';
import { StripeBillingProvider } from './stripe';
export type * from './billing-provider';
export { BillingProviderNotConfigured, toBillingProblem } from './billing-provider';
export { MercadoPagoBillingProvider } from './mercado-pago';
export { StripeBillingProvider } from './stripe';
/** How the domain gets a provider; use-cases take one in `deps` for tests. */
export type BillingProviderResolver = (id: BillingProviderId) => BillingProvider;
/**
* The one place that maps a provider id to its adapter. Which provider a new
* subscription uses comes from `billingProviderForCountry` (shared); an
* existing row always keeps its own `provider`. Adding a provider means
* a new `providers/<name>/` implementing `BillingProvider`, a case here and an
* entry in `BILLING_PROVIDER_BY_COUNTRY` (shared).
*
* Construction never fails: missing credentials surface as `isAvailable` false
* or as `BillingProviderNotConfigured` (503) when a call needs them.
*/
export const getBillingProvider: BillingProviderResolver = (id) => {
switch (id) {
case 'MERCADO_PAGO':
return new MercadoPagoBillingProvider();
case 'STRIPE':
return new StripeBillingProvider();
}
};

View File

@@ -0,0 +1,26 @@
import type { CountryCode } from '@gruperly/shared';
export type PlatformCredentials = {
/** Access token of Gruperly's own Mercado Pago account in that country. */
accessToken: string;
/** Secret of the webhook configured in that account's panel. */
webhookSecret: string;
};
/**
* Gruperly's Mercado Pago credentials for one country. Mercado Pago does not
* charge across countries, so each country has its own account; a country
* without both variables cannot subscribe to Pro through Mercado Pago (503, not
* a deployment crash: rolling out country by country is expected).
*
* These are platform credentials, never the professor's OAuth token.
*/
export function getPlatformCredentials(
country: CountryCode,
env: Record<string, string | undefined> = process.env,
): PlatformCredentials | null {
const accessToken = env[`MP_PLATFORM_ACCESS_TOKEN_${country}`]?.trim();
const webhookSecret = env[`MP_PLATFORM_WEBHOOK_SECRET_${country}`]?.trim();
if (!accessToken || !webhookSecret) return null;
return { accessToken, webhookSecret };
}

View File

@@ -0,0 +1,199 @@
import type { SubscriptionStatus } from '@generated/prisma/client';
import type { CountryCode, Result } from '@gruperly/shared';
import { countryCodeSchema, err, ok } from '@gruperly/shared';
import {
type BillingProvider,
BillingProviderNotConfigured,
type BillingWebhookFailure,
type BillingWebhookHint,
type BillingWebhookRequest,
type ChargeStatus,
type ProviderCharge,
type ProviderSubscription,
type StartedSubscription,
type StartSubscriptionInput,
type SubscriptionRef,
} from '../billing-provider';
import { getPlatformCredentials, type PlatformCredentials } from './config';
import { type MpAuthorizedPayment, mpPreapprovalClient, type PreapprovalClient } from './preapproval';
import { verifyMpSignature } from './webhook-signature';
export { getPlatformCredentials, type PlatformCredentials } from './config';
export {
type MpAuthorizedPayment,
type MpPreapproval,
mpPreapprovalClient,
type PreapprovalClient,
} from './preapproval';
export { verifyMpSignature } from './webhook-signature';
const SUBSCRIPTION_REASON = 'Gruperly Pro';
const MP_STATUS: Record<string, SubscriptionStatus> = {
pending: 'PENDING',
authorized: 'AUTHORIZED',
paused: 'PAUSED',
cancelled: 'CANCELLED',
};
const REJECTED_PAYMENT = new Set(['rejected', 'cancelled', 'refunded', 'charged_back']);
/** One approved monthly charge covers one month from the day it was debited. */
export function coveredUntil(paidAt: Date): Date {
const until = new Date(paidAt);
until.setUTCMonth(until.getUTCMonth() + 1);
return until;
}
export function toChargeStatus(invoice: Pick<MpAuthorizedPayment, 'status' | 'paymentStatus'>): ChargeStatus {
if (invoice.paymentStatus === 'approved') return 'approved';
if (invoice.paymentStatus && REJECTED_PAYMENT.has(invoice.paymentStatus)) return 'rejected';
return invoice.status === 'cancelled' ? 'rejected' : 'pending';
}
type MercadoPagoBillingDeps = {
client?: PreapprovalClient;
credentials?: (country: CountryCode) => PlatformCredentials | null;
};
/**
* Pro through Mercado Pago Subscriptions (preapproval), collected by
* Gruperly's own account in the professor's country. The preapproval exists as
* soon as it is created, so `externalId` is known from the start and there is
* no `checkoutRef`.
*/
export class MercadoPagoBillingProvider implements BillingProvider {
readonly id = 'MERCADO_PAGO' as const;
readonly requiresPayerEmail = true;
constructor(private readonly deps: MercadoPagoBillingDeps = {}) {}
private get client(): PreapprovalClient {
return this.deps.client ?? mpPreapprovalClient;
}
private credentialsFor(country: CountryCode | null): PlatformCredentials | null {
return country ? (this.deps.credentials ?? getPlatformCredentials)(country) : null;
}
private tokenFor(country: CountryCode | null): string {
const credentials = this.credentialsFor(country);
if (!credentials) throw new BillingProviderNotConfigured(this.id);
return credentials.accessToken;
}
isAvailable(country: CountryCode): boolean {
return this.credentialsFor(country) !== null;
}
async start(input: StartSubscriptionInput): Promise<StartedSubscription> {
if (!input.payerEmail) throw new Error('Mercado Pago needs the payer email');
const preapproval = await this.client.createPreapproval(this.tokenFor(input.country), {
reason: SUBSCRIPTION_REASON,
externalReference: input.userId,
payerEmail: input.payerEmail,
amount: input.amount,
currencyId: input.currency,
backUrl: input.backUrl,
startDate: input.startDate,
});
if (!preapproval.initPoint) throw new Error('Mercado Pago preapproval came back without init_point');
return { checkoutUrl: preapproval.initPoint, externalId: preapproval.id, checkoutRef: null };
}
async fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null> {
if (!ref.externalId) return null;
const preapproval = await this.client.getPreapproval(this.tokenFor(ref.country), ref.externalId);
return {
externalId: preapproval.id,
ownerUserId: preapproval.externalReference,
status: MP_STATUS[preapproval.status] ?? null,
nextPaymentDate: preapproval.nextPaymentDate ? new Date(preapproval.nextPaymentDate) : null,
payerEmail: null,
};
}
async listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]> {
const invoices = await this.client.searchAuthorizedPayments(this.tokenFor(ref.country), ref.externalId);
return invoices
.filter((invoice) => invoice.preapprovalId === ref.externalId)
.map((invoice) => {
const status = toChargeStatus(invoice);
const debitedAt = invoice.debitDate ?? invoice.createdAt;
const paidAt = status === 'approved' && debitedAt ? new Date(debitedAt) : null;
return {
externalId: invoice.id,
amount: invoice.amount,
currency: invoice.currencyId || null,
status,
paidAt,
coveredUntil: paidAt ? coveredUntil(paidAt) : null,
};
});
}
async cancel(ref: SubscriptionRef): Promise<void> {
if (!ref.externalId) return;
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
}
/**
* One URL per country, because each country is a different Gruperly account
* with its own secret. Mercado Pago signs a manifest of the notified id, the
* `x-request-id` and a timestamp (`x-signature`), not the body.
*/
async parseWebhook(
request: BillingWebhookRequest,
): Promise<Result<BillingWebhookHint, BillingWebhookFailure>> {
const parsedCountry = countryCodeSchema.safeParse(request.routeParam?.toUpperCase());
if (!parsedCountry.success) return err('unknown_country');
const country = parsedCountry.data;
const credentials = this.credentialsFor(country);
if (!credentials) return err('not_configured');
const body = parseBody(request.rawBody);
const dataId = request.query.get('data.id') ?? request.query.get('id') ?? body.dataId;
const type = request.query.get('type') ?? request.query.get('topic') ?? body.type;
const requestId = request.headers.get('x-request-id');
const valid = verifyMpSignature({
signature: request.headers.get('x-signature'),
requestId,
dataId,
secret: credentials.webhookSecret,
});
if (!valid) return err('invalid_signature');
const hint: BillingWebhookHint = { source: `mp:${country}`, dedupeKey: requestId, country, externalId: null };
if (!dataId || !isSubscriptionTopic(type)) return ok(hint);
if (type === 'subscription_preapproval') return ok({ ...hint, externalId: dataId });
// An invoice notification: the subscription is its preapproval.
try {
const invoice = await this.client.getAuthorizedPayment(credentials.accessToken, dataId);
return ok({ ...hint, externalId: invoice.preapprovalId });
} catch {
return err('sync_failed');
}
}
}
function isSubscriptionTopic(
type: string | null,
): type is 'subscription_preapproval' | 'subscription_authorized_payment' {
return type === 'subscription_preapproval' || type === 'subscription_authorized_payment';
}
function parseBody(rawBody: string): { dataId: string | null; type: string | null } {
try {
const payload = JSON.parse(rawBody) as { type?: unknown; data?: { id?: unknown } } | null;
return {
dataId: payload?.data?.id == null ? null : String(payload.data.id),
type: typeof payload?.type === 'string' ? payload.type : null,
};
} catch {
return { dataId: null, type: null };
}
}

View File

@@ -0,0 +1,194 @@
import { logger } from '@/logger';
import { MP_API_URL, MpApiError } from '@/modules/mp/lib';
// Mercado Pago Subscriptions (preapproval), called with Gruperly's own
// platform token of the professor's country. Plain `fetch`, like `mp-http.ts`.
export type MpPreapprovalStatus = 'pending' | 'authorized' | 'paused' | 'cancelled';
export type CreatePreapprovalInput = {
reason: string;
/** Our user id: the only thing that ties the subscription back to a professor. */
externalReference: string;
/** Mercado Pago requires the payer to log in with this exact email. */
payerEmail: string;
amount: number;
currencyId: string;
backUrl: string;
/** First charge date; omitted means right after the professor authorizes. */
startDate?: Date;
};
export type MpPreapproval = {
id: string;
status: MpPreapprovalStatus | string;
externalReference: string | null;
initPoint: string | null;
nextPaymentDate: string | null;
};
export type MpAuthorizedPayment = {
id: string;
preapprovalId: string;
/** Status of the invoice itself: scheduled, processed, recycling, cancelled. */
status: string;
/** Status of the payment Mercado Pago attempted for it, e.g. approved/rejected. */
paymentStatus: string | null;
amount: number;
currencyId: string;
/** When the charge was debited (or attempted), ISO. */
debitDate: string | null;
createdAt: string | null;
};
async function request(
accessToken: string,
path: string,
init: { method?: string; body?: unknown } = {},
): Promise<Record<string, unknown>> {
let response: Response;
try {
response = await fetch(`${MP_API_URL}${path}`, {
method: init.method ?? 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: init.body === undefined ? undefined : JSON.stringify(init.body),
});
} catch (error) {
logger.error({ err: error, path: path.split('?')[0] }, 'Mercado Pago subscriptions unreachable');
throw new MpApiError(0, null);
}
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
const reason = typeof payload?.message === 'string' ? payload.message : null;
// The path carries ids, never tokens or emails; the body is not logged.
logger.error(
{ status: response.status, reason, path: path.split('?')[0] },
'Mercado Pago subscriptions request failed',
);
throw new MpApiError(response.status, reason);
}
return (await response.json()) as Record<string, unknown>;
}
function toPreapproval(payload: Record<string, unknown>): MpPreapproval {
return {
id: String(payload.id),
status: String(payload.status),
externalReference:
typeof payload.external_reference === 'string' ? payload.external_reference : null,
initPoint: typeof payload.init_point === 'string' ? payload.init_point : null,
nextPaymentDate:
typeof payload.next_payment_date === 'string' ? payload.next_payment_date : null,
};
}
/**
* Creates a monthly subscription waiting for the professor's authorization.
* Nothing is charged until they log in to Mercado Pago through `initPoint`.
*/
export async function createPreapproval(
accessToken: string,
input: CreatePreapprovalInput,
): Promise<MpPreapproval> {
const payload = await request(accessToken, '/preapproval', {
method: 'POST',
body: {
reason: input.reason,
external_reference: input.externalReference,
payer_email: input.payerEmail,
back_url: input.backUrl,
status: 'pending',
auto_recurring: {
frequency: 1,
frequency_type: 'months',
transaction_amount: input.amount,
currency_id: input.currencyId,
...(input.startDate ? { start_date: input.startDate.toISOString() } : {}),
},
},
});
return toPreapproval(payload);
}
export async function getPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
return toPreapproval(await request(accessToken, `/preapproval/${encodeURIComponent(id)}`));
}
export async function cancelPreapproval(accessToken: string, id: string): Promise<MpPreapproval> {
return toPreapproval(
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
method: 'PUT',
body: { status: 'cancelled' },
}),
);
}
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
return {
id: String(payload.id),
preapprovalId: String(payload.preapproval_id),
status: String(payload.status),
paymentStatus: typeof payment?.status === 'string' ? payment.status : null,
amount: Number(payload.transaction_amount ?? 0),
currencyId: String(payload.currency_id ?? ''),
debitDate: typeof payload.debit_date === 'string' ? payload.debit_date : null,
createdAt: typeof payload.date_created === 'string' ? payload.date_created : null,
};
}
export async function getAuthorizedPayment(
accessToken: string,
id: string,
): Promise<MpAuthorizedPayment> {
return toAuthorizedPayment(
await request(accessToken, `/authorized_payments/${encodeURIComponent(id)}`),
);
}
/** Safety net for the paging loop: one invoice a month, this is decades. */
const MAX_INVOICE_PAGES = 20;
/**
* The invoices of one subscription, newest first as Mercado Pago returns them.
* No `limit`: Mercado Pago answers 400 "Invalid value for limit" to values it
* accepts elsewhere, so it pages with its own default and we follow `offset`.
*/
export async function searchAuthorizedPayments(
accessToken: string,
preapprovalId: string,
): Promise<MpAuthorizedPayment[]> {
const invoices: MpAuthorizedPayment[] = [];
for (let page = 0; page < MAX_INVOICE_PAGES; page++) {
const query = new URLSearchParams({ preapproval_id: preapprovalId, offset: String(invoices.length) });
const payload = await request(accessToken, `/authorized_payments/search?${query}`);
const results = Array.isArray(payload.results) ? (payload.results as Record<string, unknown>[]) : [];
invoices.push(...results.map(toAuthorizedPayment));
const total = Number((payload.paging as Record<string, unknown> | undefined)?.total);
if (results.length === 0 || !Number.isFinite(total) || invoices.length >= total) break;
}
return invoices;
}
export type PreapprovalClient = {
createPreapproval: typeof createPreapproval;
getPreapproval: typeof getPreapproval;
cancelPreapproval: typeof cancelPreapproval;
getAuthorizedPayment: typeof getAuthorizedPayment;
searchAuthorizedPayments: typeof searchAuthorizedPayments;
};
export const mpPreapprovalClient: PreapprovalClient = {
createPreapproval,
getPreapproval,
cancelPreapproval,
getAuthorizedPayment,
searchAuthorizedPayments,
};

View File

@@ -0,0 +1,40 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
/**
* Checks Mercado Pago's `x-signature` header (`ts=<ts>,v1=<hex>`).
*
* Mercado Pago does not sign the body: it signs a manifest built from the
* notified resource id (the `data.id` query parameter, lower-cased when it is
* alphanumeric), the `x-request-id` header and the timestamp. Parts that did
* not come in the request are left out of the manifest.
*/
export function verifyMpSignature(params: {
signature: string | null;
requestId: string | null;
dataId: string | null;
secret: string;
}): boolean {
if (!params.signature) return false;
let ts: string | null = null;
let v1: string | null = null;
for (const part of params.signature.split(',')) {
const [key, value] = part.split('=', 2).map((piece) => piece.trim());
if (key === 'ts') ts = value ?? null;
if (key === 'v1') v1 = value ?? null;
}
if (!ts || !v1) return false;
const dataId = params.dataId && /^[a-z0-9]+$/i.test(params.dataId)
? params.dataId.toLowerCase()
: params.dataId;
let manifest = '';
if (dataId) manifest += `id:${dataId};`;
if (params.requestId) manifest += `request-id:${params.requestId};`;
manifest += `ts:${ts};`;
const expected = Buffer.from(createHmac('sha256', params.secret).update(manifest).digest('hex'));
const received = Buffer.from(v1);
return received.length === expected.length && timingSafeEqual(received, expected);
}

View File

@@ -0,0 +1,18 @@
export type StripeConfig = {
/** Secret key of Gruperly's single Stripe account (`sk_live_…` / `sk_test_…`). */
secretKey: string;
/** Signing secret of the webhook endpoint (`whsec_…`). */
webhookSecret: string;
};
/**
* One Stripe account collects Pro in every country that is not on Mercado Pago,
* each in its own currency. Without both variables those countries see Pro as
* "no disponible" (503), the same as a Mercado Pago country without credentials.
*/
export function getStripeConfig(env: Record<string, string | undefined> = process.env): StripeConfig | null {
const secretKey = env.STRIPE_SECRET_KEY?.trim();
const webhookSecret = env.STRIPE_WEBHOOK_SECRET?.trim();
if (!secretKey || !webhookSecret) return null;
return { secretKey, webhookSecret };
}

View File

@@ -0,0 +1,300 @@
import type { SubscriptionStatus } from '@generated/prisma/client';
import type { CountryCode, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
type BillingProvider,
BillingProviderNotConfigured,
type BillingWebhookFailure,
type BillingWebhookHint,
type BillingWebhookRequest,
type ChargeStatus,
type ProviderCharge,
type ProviderSubscription,
type StartedSubscription,
type StartSubscriptionInput,
type SubscriptionRef,
} from '../billing-provider';
import { getStripeConfig, type StripeConfig } from './config';
import { createStripeRequest, type StripeObject, type StripeRequest } from './stripe-http';
import { verifyStripeSignature } from './webhook-signature';
export { getStripeConfig, type StripeConfig } from './config';
export { STRIPE_API_VERSION, StripeApiError, toForm } from './stripe-http';
export { verifyStripeSignature } from './webhook-signature';
const PRODUCT_NAME = 'Gruperly Pro';
/** Our user id on the Stripe subscription: what ties it back to a professor. */
const USER_ID_METADATA = 'gruperly_user_id';
/** Checkout only accepts a `trial_end` at least this far ahead. */
const MIN_TRIAL_MS = 48 * 60 * 60 * 1000;
// Stripe takes amounts in the currency's minor unit, except these.
const ZERO_DECIMAL_CURRENCIES = new Set([
'BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF',
]);
export function toStripeUnitAmount(amount: number, currency: string): number {
return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? Math.round(amount) : Math.round(amount * 100);
}
export function fromStripeUnitAmount(unitAmount: number, currency: string): number {
return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? unitAmount : unitAmount / 100;
}
const STRIPE_STATUS: Record<string, SubscriptionStatus> = {
incomplete: 'PENDING',
active: 'AUTHORIZED',
trialing: 'AUTHORIZED',
// Stripe is retrying the charge; Pro survives it on `paidThrough` + grace.
past_due: 'AUTHORIZED',
unpaid: 'PAUSED',
paused: 'PAUSED',
canceled: 'CANCELLED',
incomplete_expired: 'CANCELLED',
};
const INVOICE_STATUS: Record<string, ChargeStatus> = {
paid: 'approved',
open: 'pending',
uncollectible: 'rejected',
void: 'rejected',
};
type StripeBillingDeps = {
config?: () => StripeConfig | null;
fetch?: typeof fetch;
now?: () => Date;
};
/**
* Pro through Stripe Billing: a Checkout Session in subscription mode, priced
* inline in the professor's currency (`PRO_PRICE_BY_COUNTRY`), so there are no
* Prices to keep in sync in the Dashboard.
*
* The Stripe subscription only exists once the professor completes the
* checkout: until then the row carries the session id (`checkoutRef`) and
* `fetch` resolves the subscription through it.
*/
export class StripeBillingProvider implements BillingProvider {
readonly id = 'STRIPE' as const;
readonly requiresPayerEmail = false;
constructor(private readonly deps: StripeBillingDeps = {}) {}
private get config(): StripeConfig | null {
return (this.deps.config ?? getStripeConfig)();
}
private get request(): StripeRequest {
const config = this.config;
if (!config) throw new BillingProviderNotConfigured(this.id);
return createStripeRequest(config.secretKey, this.deps.fetch);
}
isAvailable(_country: CountryCode): boolean {
return this.config !== null;
}
async start(input: StartSubscriptionInput): Promise<StartedSubscription> {
const now = this.deps.now?.() ?? new Date();
// Re-subscribing within a paid period: the first charge waits for its end.
// Closer than Checkout allows, it is charged now instead (a few days overlap).
const trialEnd =
input.startDate && input.startDate.getTime() - now.getTime() >= MIN_TRIAL_MS
? Math.floor(input.startDate.getTime() / 1000)
: null;
const session = await this.request('/checkout/sessions', {
method: 'POST',
form: {
mode: 'subscription',
client_reference_id: input.userId,
customer_email: input.payerEmail,
success_url: input.backUrl,
cancel_url: input.backUrl,
line_items: [
{
quantity: 1,
price_data: {
currency: input.currency.toLowerCase(),
unit_amount: toStripeUnitAmount(input.amount, input.currency),
recurring: { interval: 'month' },
product_data: { name: PRODUCT_NAME },
},
},
],
subscription_data: {
metadata: { [USER_ID_METADATA]: input.userId },
trial_end: trialEnd,
},
},
});
const url = stringOf(session.url);
if (!url) throw new Error('Stripe checkout session came back without url');
return { checkoutUrl: url, externalId: null, checkoutRef: String(session.id) };
}
async fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null> {
const request = this.request;
let subscriptionId = ref.externalId;
let payerEmail: string | null = null;
if (!subscriptionId) {
if (!ref.checkoutRef) return null;
const session = await request(`/checkout/sessions/${encodeURIComponent(ref.checkoutRef)}`);
subscriptionId = idOf(session.subscription);
payerEmail = stringOf(objectOf(session.customer_details)?.email);
if (!subscriptionId) return null;
}
const subscription = await request(`/subscriptions/${encodeURIComponent(subscriptionId)}`, {
query: new URLSearchParams({ 'expand[]': 'customer' }),
});
const status = STRIPE_STATUS[String(subscription.status)] ?? null;
return {
externalId: String(subscription.id),
ownerUserId: stringOf(objectOf(subscription.metadata)?.[USER_ID_METADATA]),
status,
nextPaymentDate: status === 'CANCELLED' ? null : nextChargeOf(subscription),
payerEmail: payerEmail ?? stringOf(objectOf(subscription.customer)?.email),
};
}
async listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]> {
const page = await this.request('/invoices', {
query: new URLSearchParams({ subscription: ref.externalId, limit: '50' }),
});
const invoices = Array.isArray(page.data) ? (page.data as StripeObject[]) : [];
return invoices.flatMap((invoice) => {
const status = INVOICE_STATUS[String(invoice.status)];
// Drafts are not charges yet, and a zero invoice (a trial) charges nothing.
if (!status || Number(invoice.total ?? 0) === 0) return [];
const currency = String(invoice.currency ?? '').toUpperCase();
const unitAmount = Number(status === 'approved' ? invoice.amount_paid : invoice.amount_due);
const paidAt = status === 'approved' ? dateOf(objectOf(invoice.status_transitions)?.paid_at) : null;
return [
{
externalId: String(invoice.id),
amount: fromStripeUnitAmount(unitAmount || 0, currency),
currency: currency || null,
status,
paidAt,
coveredUntil: paidAt ? (periodEndOf(invoice) ?? oneMonthAfter(paidAt)) : null,
},
];
});
}
/**
* A live subscription is cancelled right away (Pro lasts on `paidThrough`).
* A checkout still open is expired, so it cannot be completed later; one that
* was completed meanwhile has a subscription, which is cancelled instead.
*/
async cancel(ref: SubscriptionRef): Promise<void> {
const request = this.request;
let subscriptionId = ref.externalId;
if (!subscriptionId && ref.checkoutRef) {
const path = `/checkout/sessions/${encodeURIComponent(ref.checkoutRef)}`;
const session = await request(path);
if (session.status === 'open') {
await request(`${path}/expire`, { method: 'POST' });
return;
}
subscriptionId = idOf(session.subscription);
}
if (subscriptionId) {
await request(`/subscriptions/${encodeURIComponent(subscriptionId)}`, { method: 'DELETE' });
}
}
/** A single endpoint for the whole account; the event id is the dedupe key. */
async parseWebhook(
request: BillingWebhookRequest,
): Promise<Result<BillingWebhookHint, BillingWebhookFailure>> {
const config = this.config;
if (!config) return err('not_configured');
const valid = verifyStripeSignature({
signature: request.headers.get('stripe-signature'),
rawBody: request.rawBody,
secret: config.webhookSecret,
now: this.deps.now?.(),
});
if (!valid) return err('invalid_signature');
let event: StripeObject;
try {
event = JSON.parse(request.rawBody) as StripeObject;
} catch {
return err('invalid_signature');
}
return ok({
source: 'stripe',
dedupeKey: stringOf(event.id),
country: null,
externalId: subscriptionOfEvent(String(event.type), objectOf(objectOf(event.data)?.object)),
});
}
}
/** The subscription an event is about, for the events that change Pro. */
function subscriptionOfEvent(type: string, object: StripeObject | null): string | null {
if (!object) return null;
if (type === 'checkout.session.completed' || type === 'checkout.session.async_payment_succeeded') {
return object.mode === 'subscription' ? idOf(object.subscription) : null;
}
if (type.startsWith('customer.subscription.')) return idOf(object.id);
if (type.startsWith('invoice.')) {
const details = objectOf(objectOf(object.parent)?.subscription_details);
return idOf(details?.subscription) ?? idOf(object.subscription);
}
return null;
}
/** Next charge: the end of the trial or of the current period. */
function nextChargeOf(subscription: StripeObject): Date | null {
if (subscription.status === 'trialing') return dateOf(subscription.trial_end);
const item = objectOf((objectOf(subscription.items)?.data as unknown[] | undefined)?.[0]);
return dateOf(item?.current_period_end ?? subscription.current_period_end);
}
/** The last day the invoice's lines pay for. */
function periodEndOf(invoice: StripeObject): Date | null {
const lines = (objectOf(invoice.lines)?.data as unknown[] | undefined) ?? [];
const ends = lines
.map((line) => dateOf(objectOf(objectOf(line)?.period)?.end))
.filter((end): end is Date => end !== null);
return ends.length > 0 ? new Date(Math.max(...ends.map((end) => end.getTime()))) : null;
}
function oneMonthAfter(date: Date): Date {
const until = new Date(date);
until.setUTCMonth(until.getUTCMonth() + 1);
return until;
}
function objectOf(value: unknown): StripeObject | null {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as StripeObject) : null;
}
function stringOf(value: unknown): string | null {
return typeof value === 'string' && value ? value : null;
}
/** An expandable field: the id, or the expanded object's id. */
function idOf(value: unknown): string | null {
return stringOf(value) ?? stringOf(objectOf(value)?.id);
}
/** Stripe timestamps are Unix seconds. */
function dateOf(value: unknown): Date | null {
return typeof value === 'number' && value > 0 ? new Date(value * 1000) : null;
}

View File

@@ -0,0 +1,82 @@
import { logger } from '@/logger';
// Stripe's REST API with plain `fetch` (no SDK, like Mercado Pago and Kapso):
// form-encoded bodies, JSON answers, and a pinned API version so a change in
// the account's default version cannot reshape the payloads under us.
export const STRIPE_API_URL = 'https://api.stripe.com/v1';
export const STRIPE_API_VERSION = '2025-03-31.basil';
export type StripeObject = Record<string, unknown>;
export class StripeApiError extends Error {
constructor(
readonly status: number,
readonly code: string | null,
) {
super(`Stripe request failed with status ${status}`);
this.name = 'StripeApiError';
}
}
type FormValue = string | number | boolean | null | undefined | FormValue[] | { [key: string]: FormValue };
/**
* Stripe's form encoding of nested params: `a[b][0][c]=1`. `null`/`undefined`
* are left out.
*/
export function toForm(params: Record<string, FormValue>): URLSearchParams {
const form = new URLSearchParams();
const add = (key: string, value: FormValue) => {
if (value === null || value === undefined) return;
if (Array.isArray(value)) {
for (const [index, item] of value.entries()) add(`${key}[${index}]`, item);
return;
}
if (typeof value === 'object') {
for (const [child, nested] of Object.entries(value)) add(`${key}[${child}]`, nested);
return;
}
form.append(key, String(value));
};
for (const [key, value] of Object.entries(params)) add(key, value);
return form;
}
export type StripeRequest = (
path: string,
init?: { method?: 'GET' | 'POST' | 'DELETE'; form?: Record<string, FormValue>; query?: URLSearchParams },
) => Promise<StripeObject>;
export function createStripeRequest(secretKey: string, fetchImpl: typeof fetch = fetch): StripeRequest {
return async (path, init = {}) => {
const method = init.method ?? 'GET';
const query = init.query?.toString();
let response: Response;
try {
response = await fetchImpl(`${STRIPE_API_URL}${path}${query ? `?${query}` : ''}`, {
method,
headers: {
Authorization: `Bearer ${secretKey}`,
'Stripe-Version': STRIPE_API_VERSION,
...(init.form ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}),
},
body: init.form ? toForm(init.form).toString() : undefined,
});
} catch (error) {
logger.error({ err: error, path }, 'Stripe unreachable');
throw new StripeApiError(0, null);
}
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as { error?: StripeObject } | null;
const code = typeof payload?.error?.code === 'string' ? payload.error.code : null;
// Only the error code: Stripe's messages can echo what we sent (emails).
// The path carries ids, never keys or emails.
logger.error({ status: response.status, code, path }, 'Stripe request failed');
throw new StripeApiError(response.status, code);
}
return (await response.json()) as StripeObject;
};
}

View File

@@ -0,0 +1,41 @@
import { createHmac, timingSafeEqual } from 'node:crypto';
/** Stripe's own default: older deliveries are treated as replays. */
const DEFAULT_TOLERANCE_SECONDS = 5 * 60;
/**
* Checks Stripe's `Stripe-Signature` header (`t=<ts>,v1=<hex>[,v1=<hex>…]`).
*
* Stripe signs `<ts>.<raw body>` with the endpoint secret (HMAC-SHA256). There
* can be several `v1` while a secret is being rolled; any of them may match.
*/
export function verifyStripeSignature(params: {
signature: string | null;
rawBody: string;
secret: string;
now?: Date;
toleranceSeconds?: number;
}): boolean {
if (!params.signature) return false;
let timestamp: string | null = null;
const candidates: string[] = [];
for (const part of params.signature.split(',')) {
const [key, value] = part.split('=', 2).map((piece) => piece.trim());
if (key === 't') timestamp = value ?? null;
if (key === 'v1' && value) candidates.push(value);
}
if (!timestamp || !/^\d+$/.test(timestamp) || candidates.length === 0) return false;
const nowSeconds = Math.floor((params.now ?? new Date()).getTime() / 1000);
const tolerance = params.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
if (Math.abs(nowSeconds - Number(timestamp)) > tolerance) return false;
const expected = Buffer.from(
createHmac('sha256', params.secret).update(`${timestamp}.${params.rawBody}`).digest('hex'),
);
return candidates.some((candidate) => {
const received = Buffer.from(candidate);
return received.length === expected.length && timingSafeEqual(received, expected);
});
}

View File

@@ -0,0 +1,16 @@
import { Hono } from 'hono';
import cancelRoute from './features/cancel/route';
import chargesRoute from './features/charges/route';
import statusRoute from './features/status/route';
import subscribeRoute from './features/subscribe/route';
import webhookRoute from './features/webhook/route';
const routes = new Hono();
routes.route('/', statusRoute);
routes.route('/', subscribeRoute);
routes.route('/', cancelRoute);
routes.route('/', chargesRoute);
routes.route('/', webhookRoute);
export default routes;

View File

@@ -7,6 +7,7 @@ import type {
import { err, ok } from '@gruperly/shared'; 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 { import {
findGroupOwnedByUser, findGroupOwnedByUser,
type GroupWaitlistEntryRecord, type GroupWaitlistEntryRecord,
@@ -18,6 +19,7 @@ import { type GroupPreRegistrationRecord } from '../../lib/helpers';
type ApproveGroupPreRegistrationDeps = { type ApproveGroupPreRegistrationDeps = {
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>; db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
unitOfWork?: UnitOfWork; unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
export class ApproveGroupPreRegistration { export class ApproveGroupPreRegistration {
@@ -51,6 +53,11 @@ export class ApproveGroupPreRegistration {
); );
} }
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
if (!allowed.ok) {
return allowed;
}
const record = entry as unknown as GroupPreRegistrationRecord; const record = entry as unknown as GroupPreRegistrationRecord;
return unitOfWork.executeResult( return unitOfWork.executeResult(

View File

@@ -3,6 +3,7 @@ import type { ProblemDetails, PromoteGroupWaitlistEntryResult, Result } from '@g
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 { default as prisma, UnitOfWork } from '@/lib/prisma'; import { default as prisma, UnitOfWork } from '@/lib/prisma';
import { PlanGuard } from '@/modules/billing/lib/entitlements';
import { import {
findGroupOwnedByUser, findGroupOwnedByUser,
type GroupWaitlistEntryRecord, type GroupWaitlistEntryRecord,
@@ -12,6 +13,7 @@ import { promoteWaitlistEntryRecord } from '../../lib/promote';
type PromoteGroupWaitlistEntryDeps = { type PromoteGroupWaitlistEntryDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>; db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
unitOfWork?: UnitOfWork; unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
}; };
export class PromoteGroupWaitlistEntry { export class PromoteGroupWaitlistEntry {
@@ -37,6 +39,11 @@ export class PromoteGroupWaitlistEntry {
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId)); return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
} }
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
if (!allowed.ok) {
return allowed;
}
return unitOfWork.executeResult( return unitOfWork.executeResult(
async (tx: Prisma.TransactionClient) => { async (tx: Prisma.TransactionClient) => {
const promoteResult = await promoteWaitlistEntryRecord( const promoteResult = await promoteWaitlistEntryRecord(

View File

@@ -1,4 +1,4 @@
import type { Prisma, PrismaClient } from '@generated/prisma/client'; import type { Prisma } from '@generated/prisma/client';
import { Role } from '@generated/prisma/client'; import { Role } from '@generated/prisma/client';
import type { import type {
CreateFirstGroup as CreateGroupInput, CreateFirstGroup as CreateGroupInput,
@@ -6,14 +6,14 @@ import type {
ProblemDetails, ProblemDetails,
Result, Result,
} from '@gruperly/shared'; } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared'; import { ok } from '@gruperly/shared';
import { paymentNotSetupProblem } 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 { type GroupRecord, toGroupDto } from '../../lib'; import { type GroupRecord, toGroupDto } from '../../lib';
type CreateGroupDeps = { type CreateGroupDeps = {
db?: Pick<PrismaClient, 'group' | 'groupMember' | 'merchantAccount'>;
unitOfWork?: UnitOfWork; unitOfWork?: UnitOfWork;
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
}; };
export class CreateGroup { export class CreateGroup {
@@ -23,12 +23,11 @@ export class CreateGroup {
data: CreateGroupInput, data: CreateGroupInput,
userId: string, userId: string,
): Promise<Result<CreateGroupResult, ProblemDetails>> { ): Promise<Result<CreateGroupResult, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma); const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } }); const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
if (!merchantAccount) { if (!allowed.ok) {
return err(paymentNotSetupProblem()); return allowed;
} }
const transaction = unitOfWork.executeResult( const transaction = unitOfWork.executeResult(

View File

@@ -19,6 +19,8 @@ export type GroupRecord = {
billingType: BillingType | null; billingType: BillingType | null;
dueDay: number | null; dueDay: number | null;
inviteToken?: string | null; inviteToken?: string | null;
autoPaymentReminders?: boolean;
autoReengagement?: boolean;
}; };
/* 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
@@ -44,6 +46,8 @@ export function toGroupDto(record: GroupRecord): GroupDto {
billingType: record.billingType, billingType: record.billingType,
dueDay: record.dueDay, dueDay: record.dueDay,
inviteToken: record.inviteToken ?? null, inviteToken: record.inviteToken ?? null,
autoPaymentReminders: record.autoPaymentReminders ?? false,
autoReengagement: record.autoReengagement ?? false,
}; };
} }

View File

@@ -9,6 +9,9 @@ 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';
import groupWaitlistRoutes from '../group-waitlist/routes'; import groupWaitlistRoutes from '../group-waitlist/routes';
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
import { studentAccessRoutes } from '../student-access';
import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route';
import createGroupRoute from './features/create/route'; import createGroupRoute from './features/create/route';
import getAllRoute from './features/get-all/route'; import getAllRoute from './features/get-all/route';
import getByIdRoute from './features/get-by-id/route'; import getByIdRoute from './features/get-by-id/route';
@@ -24,6 +27,8 @@ routes.route('/', listAttendeesRoute);
routes.route('/', createAttendeeRoute); routes.route('/', createAttendeeRoute);
routes.route('/', bulkCreateAttendeesRoute); routes.route('/', bulkCreateAttendeesRoute);
routes.route('/', getByIdRoute); routes.route('/', getByIdRoute);
routes.route('/', createPaymentsBatchRoute);
routes.route('/', updateGroupAutomationsRoute);
routes.route('/', addToGroupWaitlistRoute); routes.route('/', addToGroupWaitlistRoute);
routes.route('/', groupWaitlistRoutes); routes.route('/', groupWaitlistRoutes);
routes.route('/', groupPreRegistrationRoutes); routes.route('/', groupPreRegistrationRoutes);
@@ -32,5 +37,6 @@ routes.route('/', getAttendeeRoute);
routes.route('/', updateAttendeeRoute); routes.route('/', updateAttendeeRoute);
routes.route('/', getAttendeeStatsRoute); routes.route('/', getAttendeeStatsRoute);
routes.route('/', removeAttendeeRoute); routes.route('/', removeAttendeeRoute);
routes.route('/', studentAccessRoutes);
export default routes; export default routes;

View File

@@ -24,7 +24,7 @@ type GroupSummaryRecord = {
name: string; name: string;
days: NextClass['days']; days: NextClass['days'];
time: string | null; time: string | null;
_count: { attendees: number }; _count: { attendees: number; preRegistrations: number };
}; };
export class GetHomeSummary { export class GetHomeSummary {
@@ -42,7 +42,11 @@ export class GetHomeSummary {
name: true, name: true,
days: true, days: true,
time: true, time: true,
_count: { select: { attendees: true } }, // The pending pre-registrations ride on the same query: Home lists
// them under "Para atender" without one request per group.
_count: {
select: { attendees: true, preRegistrations: { where: { status: 'PENDING' } } },
},
}, },
}); });
@@ -51,6 +55,7 @@ export class GetHomeSummary {
stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 }, stats: { groups: 0, attendees: 0, pendingPayments: 0, pendingAmount: 0 },
nextClass: null, nextClass: null,
upcomingPayments: [], upcomingPayments: [],
pendingPreRegistrations: [],
}); });
} }
@@ -93,6 +98,13 @@ export class GetHomeSummary {
groupName: payment.group.name, groupName: payment.group.name,
attendeeName: payment.attendee.fullName, attendeeName: payment.attendee.fullName,
})), })),
pendingPreRegistrations: groups
.filter((group) => group._count.preRegistrations > 0)
.map((group) => ({
groupId: group.id,
groupName: group.name,
count: group._count.preRegistrations,
})),
}); });
} }

View File

@@ -1,6 +1,6 @@
import type { WeekDay } from '@gruperly/shared'; import type { WeekDay } from '@gruperly/shared';
export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Mexico_City'; export const DEFAULT_TIME_ZONE = process.env.APP_TIMEZONE ?? 'America/Argentina/Buenos_Aires';
// Window (in hours) during which an already started class shows as "in progress". // Window (in hours) during which an already started class shows as "in progress".
export const CLASS_WINDOW_HOURS = 2; export const CLASS_WINDOW_HOURS = 2;
@@ -185,4 +185,50 @@ export function todayOccurrence(opt: {
export function startOfDayInTimeZone(now: Date, timeZone: string): Date { export function startOfDayInTimeZone(now: Date, timeZone: string): Date {
const { year, month, day } = wallDateInTimeZone(now, timeZone); const { year, month, day } = wallDateInTimeZone(now, timeZone);
return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone); return zonedWallClockToUtc(`${year}-${pad(month)}-${pad(day)}T00:00`, timeZone);
} }
// Every class start of a group within [from, to), in `timeZone`. Empty when the
// group has no valid schedule.
export function occurrencesBetween(opt: {
days: WeekDay[];
time: string | null;
from: Date;
to: Date;
timeZone: string;
}): Date[] {
const { days, time, from, to, timeZone } = opt;
if (days.length === 0 || !time) return [];
const [hour, minute] = time.split(':').map(Number);
if (
Number.isNaN(hour) ||
Number.isNaN(minute) ||
hour < 0 ||
hour > 23 ||
minute < 0 ||
minute > 59
) {
return [];
}
const dowSet = new Set(days.map((day) => WEEKDAY_TO_DOW[day]));
const { year, month, day } = wallDateInTimeZone(from, timeZone);
const result: Date[] = [];
// One extra day on each side covers the time zone offset.
const spanDays = Math.ceil((to.getTime() - from.getTime()) / (24 * 60 * 60 * 1000)) + 1;
for (let offset = -1; offset <= spanDays; offset++) {
const candidateDay = new Date(Date.UTC(year, month - 1, day + offset));
if (!dowSet.has(candidateDay.getUTCDay())) continue;
const wall = `${candidateDay.toISOString().slice(0, 10)}T${pad(hour)}:${pad(minute)}`;
const startsAt = zonedWallClockToUtc(wall, timeZone);
if (startsAt >= from && startsAt < to) result.push(startsAt);
}
return result;
}
// Monday 00:00 of `now`'s week in `timeZone`.
export function startOfWeekInTimeZone(now: Date, timeZone: string): Date {
const { year, month, day } = wallDateInTimeZone(now, timeZone);
const date = new Date(Date.UTC(year, month - 1, day));
const sinceMonday = (date.getUTCDay() + 6) % 7;
const monday = new Date(Date.UTC(year, month - 1, day - sinceMonday));
return zonedWallClockToUtc(`${monday.toISOString().slice(0, 10)}T00:00`, timeZone);
}

View File

@@ -0,0 +1,58 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { mpNotConnectedProblem, mpRequiresReauthProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { RefreshMpAccount } from './jobs';
import { openToken } from './lib';
export type MpTokenAccount = {
accountId: string;
accessToken: string;
expiresAt: Date;
};
/**
* Below this, the on-demand path refreshes. The daily job renews much earlier
* (30 days out), so hitting this only means the job did not run, which is exactly
* when a payment link cannot be allowed to fail.
*/
const NEAR_EXPIRY_MS = 5 * 60 * 1000;
type GetMpAccessTokenDeps = {
db?: Pick<PrismaClient, 'mpAccount'>;
refresh?: RefreshMpAccount;
};
/**
* A usable access token for a teacher's Mercado Pago account.
*
* This is the entry point for payment links and webhook verification, so it fails
* explicitly instead of returning something unusable: an unlinked account and an
* account that needs re-authorization are different problems and the caller has
* to be able to tell them apart.
*/
export async function getMpAccessToken(
ownerId: string,
deps: GetMpAccessTokenDeps = {},
): Promise<Result<MpTokenAccount, ProblemDetails>> {
const db = deps.db ?? prisma;
const account = await db.mpAccount.findUnique({ where: { ownerId } });
if (!account) return err(mpNotConnectedProblem());
if (account.status !== 'ACTIVE') return err(mpRequiresReauthProblem());
if (account.expiresAt.getTime() - Date.now() > NEAR_EXPIRY_MS) {
return ok({
accountId: account.id,
accessToken: openToken(account.accessTokenEnc),
expiresAt: account.expiresAt,
});
}
const refresh = deps.refresh ?? new RefreshMpAccount();
const refreshed = await refresh.execute(account.id);
if (!refreshed.ok) return refreshed;
return ok(refreshed.value);
}

View File

@@ -0,0 +1,50 @@
import type { MpCallbackQuery, MpCallbackReason, ProblemDetails } from '@gruperly/shared';
import { MpCallbackQuerySchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { validate } from '@/http/validate';
import { logger } from '@/logger';
import { buildMpReturnUrl, getWebOrigin } from '../../lib';
import { CompleteMpAuthorization, type MpCallbackResult } from './use-case';
/**
* The browser arrives here from Mercado Pago, so this route always answers with
* a redirect back to the app and never renders or returns a problem body: there
* is nothing on the other side to render a failure into.
*/
const route = new Hono();
route.get('/', validate.query(MpCallbackQuerySchema), async (c) => {
const { code, state, error } = c.req.valid('query') as MpCallbackQuery;
const user = c.get('user');
if (!user) {
// Without a session there is nobody to credit the tokens to. The state was
// issued to whoever was signed in when the flow started, so guessing would
// be a way to attach somebody else's Mercado Pago account to this account.
logger.warn('Mercado Pago callback arrived without a session');
return c.redirect(new URL('/login', getWebOrigin()).toString());
}
const useCase = new CompleteMpAuthorization();
const result = await useCase.execute({ code, state, error });
if (!result.ok) {
logger.warn(
{ code: result.error.code, status: result.error.status },
'Mercado Pago callback failed',
);
}
const outcome = result.ok ? result.value.outcome : problemToOutcome(result.error);
const returnTo = result.ok ? result.value.returnTo : 'settings';
return c.redirect(buildMpReturnUrl(getWebOrigin(), returnTo, outcome));
});
/** Reduces an internal problem to a reason code that is safe in a URL. */
function problemToOutcome(problem: ProblemDetails): MpCallbackResult['outcome'] {
const reason: MpCallbackReason = problem.code === 'mp_account_in_use' ? 'mp_account_in_use' : 'mp_error';
return { kind: 'error', reason };
}
export default route;

View File

@@ -0,0 +1,145 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { MpCallbackReason, MpReturnTo, ProblemDetails, Result } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import {
mpAccountInUseProblem,
mpNotConfiguredProblem,
mpProviderErrorProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
exchangeAuthorizationCode,
getMpOAuthConfig,
type MpTokenResponse,
sealToken,
} from '../../lib';
type CompleteMpAuthorizationDeps = {
db?: Pick<PrismaClient, 'mpOAuthState' | 'mpAccount'>;
/** Swapped in tests; defaults to the real Mercado Pago exchange. */
exchange?: typeof exchangeAuthorizationCode;
};
export type MpCallbackResult = {
returnTo: MpReturnTo;
outcome: { kind: 'success' } | { kind: 'error'; reason: MpCallbackReason };
};
/** Prisma's unique-constraint violation on `mp_accounts_mpUserId_key`. */
const UNIQUE_VIOLATION = 'P2002';
/** Where we land if the state is gone and there is nothing to recover. */
const DEFAULT_RETURN_TO: MpReturnTo = 'settings';
export class CompleteMpAuthorization {
constructor(private readonly deps: CompleteMpAuthorizationDeps = {}) {}
async execute(input: {
code?: string;
state?: string;
error?: string;
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
let config: ReturnType<typeof getMpOAuthConfig>;
try {
config = getMpOAuthConfig();
} catch (configError) {
logger.error({ err: configError }, 'Mercado Pago is not configured');
return err(mpNotConfiguredProblem());
}
const db = this.deps.db ?? prisma;
// The teacher closed the consent screen. There is nothing to exchange, but
// the state is still burned so it cannot be replayed later.
if (input.error) {
if (input.state) {
await db.mpOAuthState.deleteMany({ where: { state: input.state } });
}
return failure('mp_denied');
}
if (!input.code || !input.state) {
return failure('invalid_state');
}
const stored = await db.mpOAuthState.findUnique({ where: { state: input.state } });
if (!stored || stored.expiresAt.getTime() <= Date.now()) {
return failure('invalid_state');
}
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
// means someone replayed a state we already consumed.
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
if (consumed.count === 0) {
return failure('invalid_state', returnTo);
}
const exchange = this.deps.exchange ?? exchangeAuthorizationCode;
let tokens: MpTokenResponse;
try {
tokens = await exchange({
clientId: config.clientId,
clientSecret: config.clientSecret,
redirectUri: config.redirectUri,
code: input.code,
codeVerifier: stored.codeVerifier,
});
} catch (exchangeError) {
// `MpApiError` already logged the status and MP's own error code. Nothing
// added here mentions the authorization code or the verifier.
logger.error({ err: exchangeError }, 'Mercado Pago authorization could not be completed');
return err(mpProviderErrorProblem());
}
const claimed = await db.mpAccount.findUnique({ where: { mpUserId: tokens.mpUserId } });
if (claimed && claimed.ownerId !== stored.ownerId) {
return err(mpAccountInUseProblem());
}
const encrypted = {
accessTokenEnc: sealToken(tokens.accessToken),
refreshTokenEnc: sealToken(tokens.refreshToken),
expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000),
scope: tokens.scope,
liveMode: tokens.liveMode,
status: 'ACTIVE' as const,
};
try {
await db.mpAccount.upsert({
where: { ownerId: stored.ownerId },
create: { ownerId: stored.ownerId, mpUserId: tokens.mpUserId, ...encrypted },
// Re-linking renews the credentials and clears a `requires_reauth`.
update: { mpUserId: tokens.mpUserId, ...encrypted, connectedAt: new Date() },
});
} catch (writeError) {
// Two teachers linked the same Mercado Pago id at the same time: the
// unique index is the real arbiter, not the read above.
if (isUniqueViolation(writeError)) {
return err(mpAccountInUseProblem());
}
throw writeError;
}
return ok({ returnTo, outcome: { kind: 'success' } });
}
}
function failure(
reason: MpCallbackReason,
returnTo: MpReturnTo = DEFAULT_RETURN_TO,
): Result<MpCallbackResult, ProblemDetails> {
return ok({ returnTo, outcome: { kind: 'error', reason } });
}
function isUniqueViolation(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
(error as { code?: unknown }).code === UNIQUE_VIOLATION
);
}

View File

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

View File

@@ -0,0 +1,71 @@
import type { PrismaClient } from '@generated/prisma/client';
import type {
MpAuthorizationUrlDto,
MpReturnTo,
ProblemDetails,
Result,
} from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
import { mpNotConfiguredProblem } from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import {
buildAuthorizationUrl,
codeChallengeFromVerifier,
getMpOAuthConfig,
newCodeVerifier,
newState,
} from '../../lib';
type StartMpAuthorizationDeps = { db?: Pick<PrismaClient, 'mpOAuthState'> };
/** The teacher has ten minutes to finish at Mercado Pago before the state dies. */
export const STATE_TTL_MS = 10 * 60 * 1000;
export class StartMpAuthorization {
constructor(private readonly deps: StartMpAuthorizationDeps = {}) {}
async execute(
ownerId: string,
returnTo: MpReturnTo,
): Promise<Result<MpAuthorizationUrlDto, ProblemDetails>> {
let config: ReturnType<typeof getMpOAuthConfig>;
try {
config = getMpOAuthConfig();
} catch (error) {
logger.error({ err: error }, 'Mercado Pago is not configured');
return err(mpNotConfiguredProblem());
}
const db = this.deps.db ?? prisma;
const now = new Date();
// Two jobs in one sweep: drop anything expired, and drop this teacher's
// previous attempt so a teacher clicking twice cannot leave rows behind.
await db.mpOAuthState.deleteMany({
where: { OR: [{ expiresAt: { lt: now } }, { ownerId }] },
});
const state = newState();
const codeVerifier = newCodeVerifier();
await db.mpOAuthState.create({
data: {
state,
ownerId,
codeVerifier,
returnTo,
expiresAt: new Date(now.getTime() + STATE_TTL_MS),
},
});
return ok({
authorizationUrl: buildAuthorizationUrl({
clientId: config.clientId,
redirectUri: config.redirectUri,
state,
codeChallenge: codeChallengeFromVerifier(codeVerifier),
}),
});
}
}

View File

@@ -0,0 +1,16 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { DisconnectMp } from './use-case';
const route = new Hono();
route.delete('/', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new DisconnectMp();
const result = await useCase.execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,39 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { MpDisconnectResultDto, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
type DisconnectMpDeps = { db?: Pick<PrismaClient, 'mpAccount'> };
/**
* Mercado Pago has no seller-side token revocation endpoint for these grants, so
* the tokens are dropped here and the row is kept as `REVOKED`. It is not
* deleted on purpose: the Mercado Pago id stays reserved for the same teacher,
* which stops someone else from claiming their account later.
*/
export class DisconnectMp {
constructor(private readonly deps: DisconnectMpDeps = {}) {}
async execute(ownerId: string): Promise<Result<MpDisconnectResultDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const account = await db.mpAccount.findUnique({ where: { ownerId } });
if (!account) {
return ok({ disconnected: false });
}
await db.mpAccount.update({
where: { ownerId },
data: {
status: 'REVOKED',
// The columns are NOT NULL, so the values are blanked rather than nulled.
// Nothing reads them: every consumer filters on `status` first.
accessTokenEnc: '',
refreshTokenEnc: '',
expiresAt: new Date(0),
},
});
return ok({ disconnected: true });
}
}

View File

@@ -0,0 +1,16 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { GetMpStatus } from './use-case';
const route = new Hono();
route.get('/', async (c) => {
const user = c.get('user');
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
const useCase = new GetMpStatus();
const result = await useCase.execute(user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,52 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { MpAccountStatus, MpStatusDto, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared';
import prisma from '@/lib/prisma';
type GetMpStatusDeps = { db?: Pick<PrismaClient, 'mpAccount'> };
/** How many trailing digits of the Mercado Pago id we show, to confirm the account. */
const SUFFIX_LENGTH = 4;
const NOT_LINKED: MpStatusDto = {
status: 'none',
liveMode: false,
expiresAt: null,
connectedAt: null,
mpUserIdSuffix: null,
};
/**
* An account the teacher unlinked stays in the table (so the Mercado Pago id
* stays reserved for them), but from the outside it is simply "not linked".
*/
function toVisibleStatus(status: 'ACTIVE' | 'REQUIRES_REAUTH' | 'REVOKED'): MpAccountStatus {
switch (status) {
case 'ACTIVE':
return 'active';
case 'REQUIRES_REAUTH':
return 'requires_reauth';
case 'REVOKED':
return 'none';
}
}
export class GetMpStatus {
constructor(private readonly deps: GetMpStatusDeps = {}) {}
async execute(ownerId: string): Promise<Result<MpStatusDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const account = await db.mpAccount.findUnique({ where: { ownerId } });
if (!account) return ok(NOT_LINKED);
// Deliberately no tokens and no scope in the response.
return ok({
status: toVisibleStatus(account.status),
liveMode: account.liveMode,
expiresAt: account.expiresAt.toISOString(),
connectedAt: account.connectedAt.toISOString(),
mpUserIdSuffix: account.mpUserId.slice(-SUFFIX_LENGTH),
});
}
}

View File

@@ -0,0 +1,3 @@
export { getMpAccessToken, type MpTokenAccount } from './access-token';
export { startMpJobs } from './jobs';
export { default as mpRoutes } from './routes';

View File

@@ -0,0 +1,7 @@
export {
RENEWAL_WINDOW_DAYS,
RefreshExpiringMpTokens,
type RefreshExpiringMpTokensResult,
} from './refresh-expiring-mp-tokens';
export { type MpAccountStore, RefreshMpAccount } from './refresh-mp-account';
export { startMpJobs } from './schedule';

View File

@@ -0,0 +1,85 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { refreshMpTokens } from '../lib';
import { RefreshMpAccount } from './refresh-mp-account';
/**
* Mercado Pago hands out access tokens valid for about six months. Renewing at
* 30 days leaves room for the job to fail a few times before a token is at risk.
*/
const RENEWAL_WINDOW_DAYS = 30;
const DAY_MS = 24 * 60 * 60 * 1000;
/**
* Keeps a bounded batch: the query below holds row locks for the life of the
* transaction, which means it holds them across the calls to Mercado Pago.
*/
const BATCH_LIMIT = 20;
const TRANSACTION_TIMEOUT_MS = 120_000;
export type RefreshExpiringMpTokensResult = {
refreshed: number;
requiresReauth: number;
failed: number;
};
type RefreshExpiringMpTokensDeps = {
db?: PrismaClient;
/** Swapped in tests; defaults to the real Mercado Pago renewal. */
refresh?: typeof refreshMpTokens;
};
type LockedAccountRow = { id: string };
export class RefreshExpiringMpTokens {
constructor(private readonly deps: RefreshExpiringMpTokensDeps = {}) {}
async execute(): Promise<RefreshExpiringMpTokensResult> {
const db = this.deps.db ?? prisma;
const now = new Date();
const totals: RefreshExpiringMpTokensResult = { refreshed: 0, requiresReauth: 0, failed: 0 };
await db.$transaction(
async (tx) => {
const horizon = new Date(now.getTime() + RENEWAL_WINDOW_DAYS * DAY_MS);
// FOR UPDATE SKIP LOCKED: two instances of the API never renew the same
// account, and a row already claimed by another instance is skipped
// instead of blocking the batch. The trade-off is that the lock stays
// held across the HTTP calls below; if MP's latency ever became a
// problem, this becomes an atomic `updateMany` claim on a
// `refresh_claimed_at` column and the rows are released immediately.
const rows = await tx.$queryRaw<LockedAccountRow[]>`
SELECT "id"
FROM "mp_accounts"
WHERE "status" = 'ACTIVE' AND "expires_at" < ${horizon}
ORDER BY "expires_at" ASC
LIMIT ${BATCH_LIMIT}
FOR UPDATE SKIP LOCKED
`;
for (const row of rows) {
// Built per row with the transaction client, so the writes join the
// transaction holding the lock. With the shared client the lock would
// protect nothing.
const result = await new RefreshMpAccount({ db: tx, refresh: this.deps.refresh }).execute(
row.id,
);
if (result.ok) {
totals.refreshed += 1;
} else if (result.error.code === 'mp_requires_reauth') {
totals.requiresReauth += 1;
} else {
totals.failed += 1;
}
}
},
{ timeout: TRANSACTION_TIMEOUT_MS },
);
return totals;
}
}
export { RENEWAL_WINDOW_DAYS };

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