Compare commits
21 Commits
a93450579a
...
feat/impro
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
060a4f09e4 | ||
|
|
b99bc4d519 | ||
|
|
90f31290d4 | ||
|
|
e6d405a71e | ||
|
|
b12ffdda37 | ||
|
|
9617447e05 | ||
|
|
cd82a1e549 | ||
|
|
f5e77c99f6 | ||
|
|
f4d2c26e29 | ||
|
|
bef4056f8e | ||
|
|
2467ebc0f6 | ||
|
|
ec65c2198d | ||
|
|
8c5caecdda | ||
| b11dd47534 | |||
|
|
21a4c69f38 | ||
| e03f510874 | |||
|
|
59a4d18ce6 | ||
|
|
faf949fc9b | ||
|
|
6d120f4b1f | ||
|
|
69275c37b4 | ||
|
|
01b35691df |
79
.env.example
79
.env.example
@@ -1,31 +1,33 @@
|
||||
# Plantilla de variables para `docker compose`.
|
||||
# Variable template for `docker compose`.
|
||||
#
|
||||
# Local: copiá este archivo a `.env` en la raíz y completá los valores.
|
||||
# Dokploy: no hace falta el archivo; definí las mismas variables en la pestaña
|
||||
# Environment del servicio Compose (Dokploy las escribe en un `.env` al lado del
|
||||
# compose, que es de donde salen los `${...}`).
|
||||
# Local: copy this file to `.env` at the root and fill in the values.
|
||||
# Dokploy: no file needed; define the same variables in the Environment tab of
|
||||
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
||||
# file, which is where the `${...}` come from).
|
||||
|
||||
# Origen público de la app, sin barra final. El mismo valor alimenta WEB_URL y
|
||||
# BETTER_AUTH_URL porque nginx hace de proxy de /api: la web y la API comparten
|
||||
# dominio y por lo tanto la cookie de sesión es first-party.
|
||||
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
||||
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
||||
# domain, so the session cookie is first-party.
|
||||
WEB_URL="http://localhost:8080"
|
||||
|
||||
# PostgreSQL de producción.
|
||||
# La password va percent-encoded: si tiene #, @, :, /, ?, % o espacio, escapala
|
||||
# (%23, %40, %3A, %2F, %3F, %25, %20). Sin eso Prisma corta la URL donde empieza
|
||||
# el fragmento y falla con P1013 "invalid port number in database URL".
|
||||
# Production PostgreSQL.
|
||||
# The password must be percent-encoded: if it has #, @, :, /, ?, % or a space,
|
||||
# escape it (%23, %40, %3A, %2F, %3F, %25, %20). Otherwise Prisma truncates the
|
||||
# URL where the fragment starts and fails with P1013 "invalid port number in
|
||||
# database URL".
|
||||
DATABASE_URL="postgresql://user:password@localhost:5432/gruperly?schema=public"
|
||||
|
||||
# Generalo con: openssl rand -base64 32
|
||||
# Generate it with: openssl rand -base64 32
|
||||
BETTER_AUTH_SECRET=""
|
||||
|
||||
# ── Opcionales ───────────────────────────────────────────────────────────────
|
||||
# ── Optional ─────────────────────────────────────────────────────────────────
|
||||
|
||||
# Login social con Google. Sin client id/secret no se registra el provider.
|
||||
# Social login with Google. Without a client id/secret the provider is not
|
||||
# registered.
|
||||
# GOOGLE_CLIENT_ID=""
|
||||
# GOOGLE_CLIENT_SECRET=""
|
||||
|
||||
# Envío de emails (mismas variables que apps/backend/.env.example).
|
||||
# Email sending (same variables as apps/backend/.env.example).
|
||||
# EMAIL_PROVIDER="smtp"
|
||||
# EMAIL_SERVER_HOST=""
|
||||
# EMAIL_SERVER_PORT="587"
|
||||
@@ -33,6 +35,47 @@ BETTER_AUTH_SECRET=""
|
||||
# EMAIL_SERVER_PASSWORD=""
|
||||
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
|
||||
# Solo si querés la API en otro dominio: se hornea en el bundle de Vite y obliga
|
||||
# a sacar el proxy /api de apps/web/nginx.conf. Vacío = mismo origen (recomendado).
|
||||
# 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
|
||||
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
|
||||
# origin (recommended).
|
||||
# VITE_API_URL=""
|
||||
|
||||
41
AGENTS.md
41
AGENTS.md
@@ -31,34 +31,69 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||
- `src/logger.ts` — pino + pino-pretty.
|
||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `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`).
|
||||
- `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).
|
||||
|
||||
## 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`.
|
||||
- **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.
|
||||
- **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).
|
||||
- **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).
|
||||
|
||||
## Convenciones repo-específicas
|
||||
|
||||
- **Frontend en español**: copy de UI, comentarios y textos en español.
|
||||
- **Base de datos**: todas las tablas usan **snake_case** vía `@@map` en `prisma/models/*.prisma` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`). Al agregar un modelo nuevo, incluir siempre `@@map("nombre_tabla")`.
|
||||
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
|
||||
- **API** responde errores en **Problem Details RFC 7807** (`application/problem+json`) y resultados como `{ data, pagination }`; los "use cases" devuelven `Result` y nunca lanzan excepciones de dominio.
|
||||
- **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 />`).
|
||||
- **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.
|
||||
- **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.
|
||||
- **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+`.
|
||||
- **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
|
||||
|
||||
|
||||
@@ -5,21 +5,21 @@ FROM oven/bun:1.4-alpine AS base
|
||||
WORKDIR /app
|
||||
ENV CI=1
|
||||
|
||||
# ─── Dependencias ────────────────────────────────────────────────────────────
|
||||
# Solo los package.json:bun no necesita el código fuente para resolver el lockfile.
|
||||
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||
# Only the package.json files: bun needs no source code to resolve the lockfile.
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY apps/web/package.json ./apps/web/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# El cache global de bun pesa ~370MB: se borra en la misma capa.
|
||||
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||
|
||||
# ─── Prisma Client ───────────────────────────────────────────────────────────
|
||||
# El generator "prisma-client" emite TypeScript, así que el cliente generado se
|
||||
# ejecuta con Bun sin compilar nada. La URL es un placeholder: `generate` no
|
||||
# necesita conexión, solo leer el schema.
|
||||
# The "prisma-client" generator emits TypeScript, so the generated client runs
|
||||
# with Bun without compilation. The URL is a placeholder: `generate` only needs
|
||||
# to read the schema, not connect to a database.
|
||||
FROM deps AS generate
|
||||
ARG DATABASE_URL=postgresql://user:password@localhost:5432/placeholder
|
||||
ENV DATABASE_URL=$DATABASE_URL
|
||||
@@ -28,7 +28,7 @@ COPY apps/backend/prisma ./apps/backend/prisma
|
||||
WORKDIR /app/apps/backend
|
||||
RUN bun run db:generate
|
||||
|
||||
# ─── Imagen de la API ────────────────────────────────────────────────────────
|
||||
# ─── API image ───────────────────────────────────────────────────────────────
|
||||
FROM base AS api
|
||||
ENV NODE_ENV=production \
|
||||
PORT=4000
|
||||
@@ -37,30 +37,30 @@ COPY package.json bun.lock bunfig.toml ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# `prisma` y `dotenv` son dependencies (no dev) porque el entrypoint corre
|
||||
# `prisma migrate deploy` en cada arranque. Con `--production` no entra el resto
|
||||
# del tooling: biome, typescript, turbo.
|
||||
# `prisma` and `dotenv` are dependencies (not dev) because the entrypoint runs
|
||||
# `prisma migrate deploy` on every boot. With `--production` the rest of the
|
||||
# tooling does not come in: biome, typescript, turbo.
|
||||
RUN bun install --frozen-lockfile --production && rm -rf /root/.bun/install
|
||||
|
||||
# El CLI de Prisma carga prisma.config.ts, que apunta al schema.
|
||||
# The Prisma CLI loads prisma.config.ts, which points to the schema.
|
||||
COPY apps/backend/prisma ./apps/backend/prisma
|
||||
COPY apps/backend/prisma.config.ts ./apps/backend/prisma.config.ts
|
||||
COPY --from=generate /app/apps/backend/generated ./apps/backend/generated
|
||||
COPY apps/backend/tsconfig.json ./apps/backend/
|
||||
COPY apps/backend/src ./apps/backend/src
|
||||
# @gruperly/shared se consume como fuente TS; @gruperly/config aporta el
|
||||
# tsconfig base del que extiende el tsconfig del backend.
|
||||
# @gruperly/shared is consumed as TS source; @gruperly/config provides the base
|
||||
# tsconfig that the backend tsconfig extends.
|
||||
COPY packages ./packages
|
||||
COPY apps/backend/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
|
||||
WORKDIR /app/apps/backend
|
||||
EXPOSE 4000
|
||||
# Sin `${...}`: el CMD corre bajo /bin/sh (ash), donde eso es un error de sintaxis.
|
||||
# No `${...}` here: the CMD runs under /bin/sh (ash), where that is a syntax error.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD bun --eval "fetch('http://127.0.0.1:4000/api/v1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||
# Bun ejecuta el TypeScript directamente y resuelve `@/*` con el tsconfig.json,
|
||||
# igual que `bun start` en local.
|
||||
# Bun runs the TypeScript directly and resolves `@/*` with the tsconfig.json,
|
||||
# same as `bun start` locally.
|
||||
CMD ["bun", "src/server.ts"]
|
||||
|
||||
@@ -5,27 +5,27 @@ FROM oven/bun:1.4-alpine AS base
|
||||
WORKDIR /app
|
||||
ENV CI=1
|
||||
|
||||
# ─── Dependencias ────────────────────────────────────────────────────────────
|
||||
# ─── Dependencies ────────────────────────────────────────────────────────────
|
||||
FROM base AS deps
|
||||
COPY package.json bun.lock bunfig.toml turbo.json ./
|
||||
COPY apps/backend/package.json ./apps/backend/
|
||||
COPY apps/web/package.json ./apps/web/
|
||||
COPY packages/config/package.json ./packages/config/
|
||||
COPY packages/shared/package.json ./packages/shared/
|
||||
# El cache global de bun pesa ~370MB: se borra en la misma capa.
|
||||
# bun's global cache weighs ~370MB: it is dropped in the same layer.
|
||||
RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
|
||||
|
||||
# ─── Build de Vite ───────────────────────────────────────────────────────────
|
||||
# ─── Vite build ──────────────────────────────────────────────────────────────
|
||||
FROM deps AS build
|
||||
# Vite reemplaza import.meta.env.* en tiempo de build, no de runtime.
|
||||
# Vacío = mismo origen: el proxy /api de nginx hace de API.
|
||||
# Vite replaces import.meta.env.* at build time, not at runtime.
|
||||
# Empty = same origin: nginx's /api proxy acts as the API.
|
||||
ARG VITE_API_URL=""
|
||||
ENV VITE_API_URL=$VITE_API_URL
|
||||
COPY apps/web ./apps/web
|
||||
COPY packages ./packages
|
||||
RUN bun --filter @gruperly/web build
|
||||
|
||||
# ─── Imagen final ────────────────────────────────────────────────────────────
|
||||
# ─── Final image ─────────────────────────────────────────────────────────────
|
||||
FROM nginx:1.27-alpine AS web
|
||||
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||
|
||||
110
README.md
110
README.md
@@ -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`.
|
||||
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)
|
||||
|
||||
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` |
|
||||
| `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`) |
|
||||
| `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 |
|
||||
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
||||
|
||||
|
||||
@@ -19,3 +19,78 @@ EMAIL_SERVER_PORT="587"
|
||||
EMAIL_SERVER_USER=""
|
||||
EMAIL_SERVER_PASSWORD=""
|
||||
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"
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
#!/bin/sh
|
||||
# Entrypoint de producción del backend: aplica las migraciones y levanta el
|
||||
# servidor en el mismo contenedor.
|
||||
# Production entrypoint for the backend: applies the migrations and starts the
|
||||
# server in the same container.
|
||||
#
|
||||
# Es POSIX sh, no bash: la imagen es alpine y no trae bash instalado (agregarlo
|
||||
# serían ~10MB por un shebang).
|
||||
# This is POSIX sh, not bash: the image is alpine and does not ship bash
|
||||
# installed (adding it would be ~10MB for a shebang).
|
||||
#
|
||||
# Setear RUN_MIGRATIONS=false para arrancar sin tocar la base (por ejemplo, una
|
||||
# base ya migrada a mano o una que se gestiona fuera de este despliegue).
|
||||
# Set RUN_MIGRATIONS=false to start without touching the database (for example,
|
||||
# a database already migrated by hand, or one managed outside this deployment).
|
||||
set -e
|
||||
|
||||
: "${DATABASE_URL:?falta DATABASE_URL}"
|
||||
@@ -18,8 +18,8 @@ else
|
||||
delay="${MIGRATE_RETRY_DELAY:-5}"
|
||||
i=1
|
||||
|
||||
# La base puede seguir arrancando cuando este contenedor ya empezó, y un
|
||||
# deploy suele convivir con un reinicio de Postgres.
|
||||
# The database may still be starting up when this container is already
|
||||
# running, and a deploy usually overlaps a Postgres restart.
|
||||
while [ "$i" -le "$attempts" ]; do
|
||||
if bun run db:deploy; then
|
||||
echo "migrate: listo"
|
||||
@@ -37,6 +37,6 @@ else
|
||||
done
|
||||
fi
|
||||
|
||||
# exec para que Bun quede como PID 1 y reciba el SIGTERM de `docker stop`
|
||||
# (el servidor lo usa para cerrar Bun.serve y desconectar Prisma).
|
||||
# exec so that Bun becomes PID 1 and receives the SIGTERM from `docker stop`
|
||||
# (the server uses it to close Bun.serve and disconnect Prisma).
|
||||
exec "$@"
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"build": "prisma generate && tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "bun test",
|
||||
"test:db": "DB_TESTS=1 bun test test/db",
|
||||
"test:watch": "bun test --watch",
|
||||
"lint": "biome check .",
|
||||
"lint:fix": "biome check . --write",
|
||||
@@ -23,6 +24,7 @@
|
||||
"@gruperly/shared": "workspace:*",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
"@simplewebauthn/server": "13.3.3",
|
||||
"better-auth": "1.7.2",
|
||||
"dotenv": "^16.4.5",
|
||||
"hono": "^4.13.3",
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
-- Rename camelCase columns to snake_case without recreating them or losing data.
|
||||
|
||||
-- accounts
|
||||
ALTER TABLE "accounts" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "providerId" TO "provider_id";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "accountId" TO "account_id";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "accessToken" TO "access_token";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "refreshToken" TO "refresh_token";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "idToken" TO "id_token";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "accessTokenExpiresAt" TO "access_token_expires_at";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "refreshTokenExpiresAt" TO "refresh_token_expires_at";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "accounts" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- attendances
|
||||
ALTER TABLE "attendances" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||
ALTER TABLE "attendances" RENAME COLUMN "classSessionId" TO "class_session_id";
|
||||
ALTER TABLE "attendances" RENAME COLUMN "markedAt" TO "marked_at";
|
||||
|
||||
-- attendees
|
||||
ALTER TABLE "attendees" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "fullName" TO "full_name";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "guardianName" TO "guardian_name";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "guardianPhone" TO "guardian_phone";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "notifyToken" TO "notify_token";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "attendees" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- class_sessions
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "startsAt" TO "starts_at";
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "class_sessions" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- group_members
|
||||
ALTER TABLE "group_members" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "group_members" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "group_members" RENAME COLUMN "joinedAt" TO "joined_at";
|
||||
|
||||
-- group_pre_registrations
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "fullName" TO "full_name";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "reviewedAt" TO "reviewed_at";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "group_pre_registrations" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- group_waitlist_entries
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "fullName" TO "full_name";
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "group_waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- groups
|
||||
ALTER TABLE "groups" RENAME COLUMN "billingType" TO "billing_type";
|
||||
ALTER TABLE "groups" RENAME COLUMN "dueDay" TO "due_day";
|
||||
ALTER TABLE "groups" RENAME COLUMN "inviteToken" TO "invite_token";
|
||||
ALTER TABLE "groups" RENAME COLUMN "createdById" TO "created_by_id";
|
||||
ALTER TABLE "groups" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "groups" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- invitations
|
||||
ALTER TABLE "invitations" RENAME COLUMN "organizationId" TO "organization_id";
|
||||
ALTER TABLE "invitations" RENAME COLUMN "inviterId" TO "inviter_id";
|
||||
ALTER TABLE "invitations" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||
ALTER TABLE "invitations" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- members
|
||||
ALTER TABLE "members" RENAME COLUMN "organizationId" TO "organization_id";
|
||||
ALTER TABLE "members" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "members" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- merchant_accounts
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "accessToken" TO "access_token";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "connectedAt" TO "connected_at";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "merchant_accounts" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- organizations
|
||||
ALTER TABLE "organizations" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "organizations" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- passkeys
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "publicKey" TO "public_key";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "credentialID" TO "credential_id";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "deviceType" TO "device_type";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "backedUp" TO "backed_up";
|
||||
ALTER TABLE "passkeys" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- payments
|
||||
ALTER TABLE "payments" RENAME COLUMN "groupId" TO "group_id";
|
||||
ALTER TABLE "payments" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||
ALTER TABLE "payments" RENAME COLUMN "dueDate" TO "due_date";
|
||||
ALTER TABLE "payments" RENAME COLUMN "paidAt" TO "paid_at";
|
||||
ALTER TABLE "payments" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "payments" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- sessions
|
||||
ALTER TABLE "sessions" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "ipAddress" TO "ip_address";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "userAgent" TO "user_agent";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "activeOrganizationId" TO "active_organization_id";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "sessions" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- slot_releases
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "attendeeId" TO "attendee_id";
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "classSessionId" TO "class_session_id";
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "isClaimed" TO "is_claimed";
|
||||
ALTER TABLE "slot_releases" RENAME COLUMN "createdAt" TO "created_at";
|
||||
|
||||
-- users
|
||||
ALTER TABLE "users" RENAME COLUMN "emailVerified" TO "email_verified";
|
||||
ALTER TABLE "users" RENAME COLUMN "onboardingCompleted" TO "onboarding_completed";
|
||||
ALTER TABLE "users" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "users" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- verifications
|
||||
ALTER TABLE "verifications" RENAME COLUMN "expiresAt" TO "expires_at";
|
||||
ALTER TABLE "verifications" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "verifications" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
|
||||
-- waitlist_entries
|
||||
ALTER TABLE "waitlist_entries" RENAME COLUMN "userId" TO "user_id";
|
||||
ALTER TABLE "waitlist_entries" RENAME COLUMN "createdAt" TO "created_at";
|
||||
ALTER TABLE "waitlist_entries" RENAME COLUMN "updatedAt" TO "updated_at";
|
||||
@@ -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";
|
||||
@@ -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");
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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";
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -8,43 +8,44 @@ enum AttendanceStatus {
|
||||
|
||||
model ClassSession {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
startsAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
groupId String @map("group_id")
|
||||
startsAt DateTime @map("starts_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "class_sessions_groupId_fkey")
|
||||
attendances Attendance[]
|
||||
slotReleases SlotRelease[]
|
||||
absenceNotices AbsenceNotice[]
|
||||
|
||||
@@unique([groupId, startsAt])
|
||||
@@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
|
||||
@@map("class_sessions")
|
||||
}
|
||||
|
||||
model Attendance {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String
|
||||
classSessionId String
|
||||
attendeeId String @map("attendee_id")
|
||||
classSessionId String @map("class_session_id")
|
||||
status AttendanceStatus
|
||||
markedAt DateTime @default(now())
|
||||
markedAt DateTime @default(now()) @map("marked_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "attendances_attendeeId_fkey")
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "attendances_classSessionId_fkey")
|
||||
|
||||
@@unique([attendeeId, classSessionId])
|
||||
@@unique([attendeeId, classSessionId], map: "attendances_attendeeId_classSessionId_key")
|
||||
@@map("attendances")
|
||||
}
|
||||
|
||||
model SlotRelease {
|
||||
id String @id @default(cuid())
|
||||
attendeeId String
|
||||
classSessionId String
|
||||
isClaimed Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
attendeeId String @map("attendee_id")
|
||||
classSessionId String @map("class_session_id")
|
||||
isClaimed Boolean @default(false) @map("is_claimed")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "slot_releases_attendeeId_fkey")
|
||||
classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "slot_releases_classSessionId_fkey")
|
||||
|
||||
@@unique([attendeeId, classSessionId])
|
||||
@@unique([attendeeId, classSessionId], map: "slot_releases_attendeeId_classSessionId_key")
|
||||
@@map("slot_releases")
|
||||
}
|
||||
|
||||
@@ -4,11 +4,17 @@ model User {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
email String @unique
|
||||
emailVerified Boolean @default(false)
|
||||
emailVerified Boolean @default(false) @map("email_verified")
|
||||
image String?
|
||||
onboardingCompleted Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
onboardingCompleted Boolean @default(false) @map("onboarding_completed")
|
||||
country String? @map("country_code")
|
||||
// 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[]
|
||||
sessions Session[]
|
||||
@@ -18,46 +24,49 @@ model User {
|
||||
orgMemberships Member[]
|
||||
orgInvitations Invitation[] @relation("InvitedBy")
|
||||
waitlist WaitlistEntry[]
|
||||
merchantAccount MerchantAccount?
|
||||
mpAccount MpAccount?
|
||||
whatsappAccount WhatsappAccount?
|
||||
subscription BillingSubscription?
|
||||
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Account {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
providerId String
|
||||
accountId String
|
||||
userId String @map("user_id")
|
||||
providerId String @map("provider_id")
|
||||
accountId String @map("account_id")
|
||||
issuer String
|
||||
accessToken String?
|
||||
refreshToken String?
|
||||
idToken String?
|
||||
accessTokenExpiresAt DateTime?
|
||||
refreshTokenExpiresAt DateTime?
|
||||
accessToken String? @map("access_token")
|
||||
refreshToken String? @map("refresh_token")
|
||||
idToken String? @map("id_token")
|
||||
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
|
||||
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
|
||||
scope String?
|
||||
password String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "accounts_userId_fkey")
|
||||
|
||||
@@unique([issuer, accountId])
|
||||
@@index([userId])
|
||||
@@unique([issuer, accountId], map: "accounts_issuer_accountId_key")
|
||||
@@index([userId], map: "accounts_userId_idx")
|
||||
@@map("accounts")
|
||||
}
|
||||
|
||||
model Session {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
userId String @map("user_id")
|
||||
token String @unique
|
||||
expiresAt DateTime
|
||||
ipAddress String?
|
||||
userAgent String?
|
||||
activeOrganizationId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime @map("expires_at")
|
||||
ipAddress String? @map("ip_address")
|
||||
userAgent String? @map("user_agent")
|
||||
activeOrganizationId String? @map("active_organization_id")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "sessions_userId_fkey")
|
||||
|
||||
@@map("sessions")
|
||||
}
|
||||
@@ -66,9 +75,9 @@ model Verification {
|
||||
id String @id @default(cuid())
|
||||
identifier String
|
||||
value String
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@unique([identifier, value])
|
||||
@@map("verifications")
|
||||
@@ -81,8 +90,8 @@ model Organization {
|
||||
slug String @unique
|
||||
logo String?
|
||||
metadata Json?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
members Member[]
|
||||
invitations Invitation[]
|
||||
@@ -92,32 +101,32 @@ model Organization {
|
||||
|
||||
model Member {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
userId String
|
||||
organizationId String @map("organization_id")
|
||||
userId String @map("user_id")
|
||||
role String @default("member")
|
||||
createdAt DateTime @default(now())
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "members_organizationId_fkey")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "members_userId_fkey")
|
||||
|
||||
@@unique([organizationId, userId])
|
||||
@@unique([organizationId, userId], map: "members_organizationId_userId_key")
|
||||
@@map("members")
|
||||
}
|
||||
|
||||
model Invitation {
|
||||
id String @id @default(cuid())
|
||||
organizationId String
|
||||
organizationId String @map("organization_id")
|
||||
email String
|
||||
role String
|
||||
status String @default("pending")
|
||||
inviterId String
|
||||
expiresAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
inviterId String @map("inviter_id")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade)
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade, map: "invitations_organizationId_fkey")
|
||||
inviter User @relation("InvitedBy", fields: [inviterId], references: [id], onDelete: Cascade, map: "invitations_inviterId_fkey")
|
||||
|
||||
@@index([organizationId])
|
||||
@@index([organizationId], map: "invitations_organizationId_idx")
|
||||
@@map("invitations")
|
||||
}
|
||||
|
||||
@@ -125,18 +134,18 @@ model Invitation {
|
||||
model Passkey {
|
||||
id String @id @default(cuid())
|
||||
name String?
|
||||
publicKey String
|
||||
credentialID String @unique
|
||||
userId String
|
||||
publicKey String @map("public_key")
|
||||
credentialID String @unique(map: "passkeys_credentialID_key") @map("credential_id")
|
||||
userId String @map("user_id")
|
||||
counter Int
|
||||
deviceType String
|
||||
backedUp Boolean
|
||||
deviceType String @map("device_type")
|
||||
backedUp Boolean @map("backed_up")
|
||||
transports String?
|
||||
createdAt DateTime @default(now())
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
aaguid String?
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "passkeys_userId_fkey")
|
||||
|
||||
@@index([userId])
|
||||
@@index([userId], map: "passkeys_userId_idx")
|
||||
@@map("passkeys")
|
||||
}
|
||||
82
apps/backend/prisma/models/billing.prisma
Normal file
82
apps/backend/prisma/models/billing.prisma
Normal 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")
|
||||
}
|
||||
@@ -8,20 +8,25 @@ model Group {
|
||||
time String?
|
||||
capacity Int?
|
||||
price Decimal? @db.Decimal(10, 2)
|
||||
billingType BillingType?
|
||||
dueDay Int?
|
||||
inviteToken String? @unique
|
||||
createdById String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
billingType BillingType? @map("billing_type")
|
||||
dueDay Int? @map("due_day")
|
||||
// Weekly WhatsApp automations, off until the teacher turns them on.
|
||||
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
|
||||
autoReengagement Boolean @default(false) @map("auto_reengagement")
|
||||
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)
|
||||
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
|
||||
members GroupMember[]
|
||||
attendees Attendee[]
|
||||
payments Payment[]
|
||||
waitlist GroupWaitlistEntry[]
|
||||
preRegistrations GroupPreRegistration[]
|
||||
classSessions ClassSession[]
|
||||
outboundMessages OutboundMessage[]
|
||||
reportedPayments ReportedPayment[]
|
||||
|
||||
@@map("groups")
|
||||
}
|
||||
@@ -43,15 +48,15 @@ enum BillingType {
|
||||
|
||||
model GroupMember {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
userId String
|
||||
groupId String @map("group_id")
|
||||
userId String @map("user_id")
|
||||
role Role @default(MEMBER) // OWNER, ADMIN, MEMBER
|
||||
joinedAt DateTime @default(now())
|
||||
joinedAt DateTime @default(now()) @map("joined_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_members_groupId_fkey")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "group_members_userId_fkey")
|
||||
|
||||
@@unique([groupId, userId])
|
||||
@@unique([groupId, userId], map: "group_members_groupId_userId_key")
|
||||
@@map("group_members")
|
||||
}
|
||||
|
||||
@@ -69,44 +74,77 @@ enum AttendeeStatus {
|
||||
|
||||
model Attendee {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
email String?
|
||||
phone String?
|
||||
guardianName String?
|
||||
guardianPhone String?
|
||||
guardianName String? @map("guardian_name")
|
||||
guardianPhone String? @map("guardian_phone")
|
||||
notes String?
|
||||
notifyToken String? @unique @default(cuid())
|
||||
notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
|
||||
status AttendeeStatus @default(ACTIVE)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
|
||||
payments Payment[]
|
||||
attendances Attendance[]
|
||||
slotReleases SlotRelease[]
|
||||
outboundMessages OutboundMessage[]
|
||||
alertResolutions AttendeeAlertResolution[]
|
||||
studentAccounts StudentAccountAttendee[]
|
||||
absenceNotices AbsenceNotice[]
|
||||
reportedPayments ReportedPayment[]
|
||||
|
||||
@@index([groupId])
|
||||
@@index([groupId], map: "attendees_groupId_idx")
|
||||
@@map("attendees")
|
||||
}
|
||||
|
||||
enum StudentAlertKind {
|
||||
ATTENDANCE
|
||||
PAYMENT
|
||||
}
|
||||
|
||||
// "Resuelto" on the "Requiere atención" screen. One row per attendee and kind:
|
||||
// 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
|
||||
attendeeId String
|
||||
groupId String @map("group_id")
|
||||
attendeeId String @map("attendee_id")
|
||||
amount Decimal @db.Decimal(10, 2)
|
||||
currency String @default("MXN")
|
||||
currency String @default("ARS")
|
||||
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
|
||||
dueDate DateTime
|
||||
paidAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
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)
|
||||
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade)
|
||||
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])
|
||||
@@index([attendeeId])
|
||||
@@index([groupId], map: "payments_groupId_idx")
|
||||
@@index([attendeeId], map: "payments_attendeeId_idx")
|
||||
@@map("payments")
|
||||
}
|
||||
|
||||
@@ -122,12 +160,12 @@ model WaitlistEntry {
|
||||
email String
|
||||
name String?
|
||||
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
userId String? @unique
|
||||
userId String? @unique(map: "waitlist_entries_userId_key") @map("user_id")
|
||||
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull, map: "waitlist_entries_userId_fkey")
|
||||
|
||||
@@unique([email])
|
||||
@@map("waitlist_entries")
|
||||
@@ -135,19 +173,19 @@ model WaitlistEntry {
|
||||
|
||||
model GroupWaitlistEntry {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
phone String
|
||||
email String?
|
||||
notes String?
|
||||
status WaitlistStatus @default(PENDING) // PENDING, INVITED, JOINED, DECLINED
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_waitlist_entries_groupId_fkey")
|
||||
|
||||
@@unique([groupId, phone])
|
||||
@@index([groupId])
|
||||
@@unique([groupId, phone], map: "group_waitlist_entries_groupId_phone_key")
|
||||
@@index([groupId], map: "group_waitlist_entries_groupId_idx")
|
||||
@@map("group_waitlist_entries")
|
||||
}
|
||||
|
||||
@@ -166,38 +204,65 @@ enum PreRegistrationStatus {
|
||||
|
||||
model GroupPreRegistration {
|
||||
id String @id @default(cuid())
|
||||
groupId String
|
||||
fullName String
|
||||
groupId String @map("group_id")
|
||||
fullName String @map("full_name")
|
||||
phone String
|
||||
email String?
|
||||
status PreRegistrationStatus @default(PENDING)
|
||||
reviewedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_pre_registrations_groupId_fkey")
|
||||
|
||||
@@unique([groupId, phone])
|
||||
@@index([groupId])
|
||||
@@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key")
|
||||
@@index([groupId], map: "group_pre_registrations_groupId_idx")
|
||||
@@map("group_pre_registrations")
|
||||
}
|
||||
|
||||
enum PaymentProvider {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
enum MpAccountStatus {
|
||||
ACTIVE
|
||||
REQUIRES_REAUTH
|
||||
REVOKED
|
||||
}
|
||||
|
||||
model MerchantAccount {
|
||||
// Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE).
|
||||
// Tokens are stored encrypted (AES-256-GCM); there is a single active account per
|
||||
// teacher and a Mercado Pago user cannot be linked to two teachers.
|
||||
model MpAccount {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique
|
||||
provider PaymentProvider
|
||||
accessToken String?
|
||||
sandbox Boolean @default(true)
|
||||
connectedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id")
|
||||
mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id")
|
||||
accessTokenEnc String @map("access_token_enc")
|
||||
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)
|
||||
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")
|
||||
}
|
||||
235
apps/backend/prisma/models/student-access.prisma
Normal file
235
apps/backend/prisma/models/student-access.prisma
Normal 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")
|
||||
}
|
||||
130
apps/backend/prisma/models/whatsapp.prisma
Normal file
130
apps/backend/prisma/models/whatsapp.prisma
Normal 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")
|
||||
}
|
||||
@@ -10,20 +10,26 @@ import { requestLoggerMiddleware } from '@/http/request-logger';
|
||||
import { corsMiddleware, securityHeadersMiddleware } from '@/http/security-headers';
|
||||
import { sessionAuthMiddleware } from '@/http/session-auth';
|
||||
import { logger } from '@/logger';
|
||||
import { adminRoutes } from './modules/admin';
|
||||
import {
|
||||
groupsRiskOverviewRoute,
|
||||
studentStatusRoutes,
|
||||
} from './modules/analytics';
|
||||
import { attendeesRoutes } from './modules/attendees';
|
||||
import { attentionRoutes } from './modules/attention';
|
||||
import { authRoutes } from './modules/auth';
|
||||
import { billingRoutes, planReadOnlyMiddleware } from './modules/billing';
|
||||
import { classesRoutes } from './modules/classes';
|
||||
import { groupsRoutes } from './modules/groups';
|
||||
import { healthCheckRoutes } from './modules/health-check';
|
||||
import { homeRoutes } from './modules/home';
|
||||
import { invitationsRoutes } from './modules/invitations';
|
||||
import { mpRoutes } from './modules/mp';
|
||||
import { onboardingRoutes } from './modules/onboarding';
|
||||
import { paymentsRoutes } from './modules/payments';
|
||||
import { studentPortalRoutes } from './modules/student-portal';
|
||||
import { waitlistRoutes } from './modules/waitlist';
|
||||
import { whatsappRoutes } from './modules/whatsapp';
|
||||
|
||||
const app = new Hono<BackendEnv>();
|
||||
|
||||
@@ -38,18 +44,31 @@ const api = app.basePath('/api/v1');
|
||||
|
||||
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('/health', healthCheckRoutes);
|
||||
api.route('/invitations', invitationsRoutes);
|
||||
api.route('/groups', groupsRoutes);
|
||||
api.route('/home', homeRoutes);
|
||||
api.route('/onboarding', onboardingRoutes);
|
||||
api.route('/mp', mpRoutes);
|
||||
api.route('/whatsapp', whatsappRoutes);
|
||||
api.route('/attendees', attendeesRoutes);
|
||||
api.route('/payments', paymentsRoutes);
|
||||
api.route('/billing', billingRoutes);
|
||||
api.route('/waitlist', waitlistRoutes);
|
||||
api.route('/classes', classesRoutes);
|
||||
api.route('/students', studentStatusRoutes);
|
||||
api.route('/groups-risk', groupsRiskOverviewRoute);
|
||||
api.route('/attention', attentionRoutes);
|
||||
api.route('/student-portal', studentPortalRoutes);
|
||||
|
||||
app.notFound((c) => {
|
||||
return problemJson(c, notFoundProblem(c.req.path));
|
||||
|
||||
@@ -2,11 +2,15 @@ import type { auth } from '@/modules/auth/auth';
|
||||
|
||||
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 = {
|
||||
Variables: {
|
||||
user: AuthSession['user'] | null;
|
||||
session: AuthSession['session'] | null;
|
||||
requestId: string;
|
||||
student: StudentContext | null;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -15,5 +19,6 @@ declare module 'hono' {
|
||||
user: AuthSession['user'] | null;
|
||||
session: AuthSession['session'] | null;
|
||||
requestId: string;
|
||||
student: StudentContext | null;
|
||||
}
|
||||
}
|
||||
@@ -71,13 +71,108 @@ export function notFoundResourceProblem(resourceName: string, id: string): Probl
|
||||
return notFoundProblem(`${resourceName} ${id}`);
|
||||
}
|
||||
|
||||
export function paymentNotSetupProblem(): ProblemDetails {
|
||||
export function mpNotConnectedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Vinculá una cuenta de cobro antes de crear tu primer grupo.',
|
||||
code: 'payment_not_setup',
|
||||
detail: 'No tenés una cuenta de Mercado Pago vinculada.',
|
||||
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 {
|
||||
return conflictProblem({
|
||||
detail: 'Ya completaste el onboarding de Gruperly.',
|
||||
@@ -107,3 +202,110 @@ export function attendeeHasPaymentsProblem(): ProblemDetails {
|
||||
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',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -27,19 +27,39 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
||||
|
||||
const normalizedPath = normalizePath(path);
|
||||
|
||||
// Aviso de ausencia con token personal del alumno (sin sesión).
|
||||
// Absence notice sent with the attendee's personal token (no session).
|
||||
if (method === 'GET' && normalizedPath === '/api/v1/classes/absence') {
|
||||
return true;
|
||||
}
|
||||
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
|
||||
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 (
|
||||
normalizedPath === '/api/v1/health'
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/v1/auth')
|
||||
|| matchesPublicPrefix(normalizedPath, '/api/auth')
|
||||
|| 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')
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,15 +4,24 @@ import nodemailer, { type Transporter } from 'nodemailer'
|
||||
type VerificationEmailData = { email: string; url: string; name?: string }
|
||||
type PasswordResetEmailData = { email: string; url: string; name?: 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
|
||||
}
|
||||
|
||||
// Colores de marca (mismo sistema que la web: index.css de apps/web).
|
||||
// Brand colors (same system as the web app: index.css in apps/web).
|
||||
const BRAND_600 = '#2544ea'
|
||||
const TEXT_STRONG = '#0f172a'
|
||||
const TEXT_MUTED = '#475569'
|
||||
const ON_ACCENT = '#ffffff'
|
||||
const LINK_BG = BRAND_600
|
||||
|
||||
// Logotipo embebido como data URI para que los mails no dependan de hosting.
|
||||
// Logo embedded as a data URI so the emails don't depend on hosting.
|
||||
function loadLogoTypoDataUri(): string {
|
||||
try {
|
||||
const base64 = readFileSync(
|
||||
@@ -26,10 +35,27 @@ function loadLogoTypoDataUri(): string {
|
||||
|
||||
const LOGO_DATA_URI = loadLogoTypoDataUri()
|
||||
|
||||
interface EmailProvider {
|
||||
export interface EmailProvider {
|
||||
sendVerificationEmail(data: VerificationEmailData): Promise<void>
|
||||
sendPasswordResetEmail(data: PasswordResetEmailData): 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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -66,7 +92,7 @@ class SMTPEmailProvider implements EmailProvider {
|
||||
}
|
||||
|
||||
private async send(to: string, subject: string, html: string) {
|
||||
// Sin SMTP configurado (dev) no rompe el flujo: solo registra un aviso
|
||||
// With no SMTP configured (dev) the flow still doesn't break: it only logs a warning
|
||||
if (!process.env.EMAIL_SERVER_HOST) {
|
||||
console.warn(`[email] SMTP no configurado. Email no enviado a ${to}: "${subject}"`)
|
||||
return
|
||||
@@ -109,10 +135,51 @@ 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')}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
|
||||
// Añadir implementaciones y alternar con EMAIL_PROVIDER.
|
||||
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).
|
||||
// Add implementations and switch between them with EMAIL_PROVIDER.
|
||||
export function createEmailProvider(): EmailProvider {
|
||||
return new SMTPEmailProvider()
|
||||
}
|
||||
|
||||
36
apps/backend/src/lib/file-type.ts
Normal file
36
apps/backend/src/lib/file-type.ts
Normal 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;
|
||||
}
|
||||
54
apps/backend/src/lib/storage.ts
Normal file
54
apps/backend/src/lib/storage.ts
Normal 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;
|
||||
}
|
||||
12
apps/backend/src/modules/admin/features/get-account/route.ts
Normal file
12
apps/backend/src/modules/admin/features/get-account/route.ts
Normal 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;
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/admin/features/me/route.ts
Normal file
16
apps/backend/src/modules/admin/features/me/route.ts
Normal 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;
|
||||
1
apps/backend/src/modules/admin/index.ts
Normal file
1
apps/backend/src/modules/admin/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as adminRoutes } from './routes';
|
||||
39
apps/backend/src/modules/admin/lib/access.ts
Normal file
39
apps/backend/src/modules/admin/lib/access.ts
Normal 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();
|
||||
};
|
||||
}
|
||||
94
apps/backend/src/modules/admin/lib/account-summary.ts
Normal file
94
apps/backend/src/modules/admin/lib/account-summary.ts
Normal 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 } : {};
|
||||
}
|
||||
9
apps/backend/src/modules/admin/lib/index.ts
Normal file
9
apps/backend/src/modules/admin/lib/index.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export { adminOnlyMiddleware, isAdminEmail } from './access';
|
||||
export {
|
||||
type AccountRecord,
|
||||
type AccountUsage,
|
||||
accountPlan,
|
||||
buildAccountWhere,
|
||||
type PlanContext,
|
||||
toAccountListItem,
|
||||
} from './account-summary';
|
||||
17
apps/backend/src/modules/admin/routes.ts
Normal file
17
apps/backend/src/modules/admin/routes.ts
Normal 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;
|
||||
@@ -33,14 +33,27 @@ export class GetAttendeeHistory {
|
||||
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
select: { id: true, fullName: true },
|
||||
select: { id: true, fullName: true, createdAt: true },
|
||||
});
|
||||
if (!attendee) {
|
||||
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({
|
||||
where: { groupId },
|
||||
where: { groupId, startsAt: { gte: since } },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
take: HISTORY_SESSIONS_LIMIT,
|
||||
select: { id: true, startsAt: true },
|
||||
|
||||
@@ -4,30 +4,21 @@ import type {
|
||||
GroupRiskLevel,
|
||||
GroupRiskSummary,
|
||||
GroupsRiskOverview,
|
||||
MemberClassSession,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
UrgentMemberSummary,
|
||||
} 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 { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||
import {
|
||||
classifyRisk,
|
||||
MIN_RISK_ABSENCE_STREAK,
|
||||
MIN_RISK_MONTHLY_RATE,
|
||||
monthlyAttendanceRate,
|
||||
trailingAbsentStreak,
|
||||
} from '../../lib/risk';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
|
||||
/* Cuántas clases se miran hacia atrás por alumno. Es el techo real del modelo:
|
||||
los `class_sessions` no se crean solos, se materializan cuando alguien entra
|
||||
a "clases de hoy", así que no tiene sentido traer años de filas. Con 20
|
||||
clases alcanza para la racha, para la ventana de tendencia de 4+4 y para el
|
||||
porcentaje de asistencia que muestra la tarjeta. */
|
||||
const MEMBER_HISTORY_LIMIT = 20;
|
||||
|
||||
type GetGroupsRiskOverviewDeps = {
|
||||
db?: {
|
||||
group: Prisma.GroupDelegate;
|
||||
@@ -42,7 +33,7 @@ type GroupRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
capacity: number | null;
|
||||
/** Los que todavía esperan cupo (`GroupWaitlistEntry` en PENDING). */
|
||||
/** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */
|
||||
_count: { waitlist: number };
|
||||
};
|
||||
type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
|
||||
@@ -54,10 +45,10 @@ type AttendanceRow = {
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
|
||||
// Resumen de semáforo de riesgo por grupo para la lista de grupos.
|
||||
// Un grupo es HIGH si tiene al menos un alumno en riesgo alto, MEDIUM si
|
||||
// alguno en riesgo moderado y NONE en caso contrario. Los contadores dicen el
|
||||
// motivo (faltas seguidas o asistencia baja) para que la lista pueda nombrarlo.
|
||||
// Risk summary per group for the group listing and Home. Everything comes from
|
||||
// the domain rule (`getGroupAttendanceSummary`): the status light is the worst
|
||||
// level present (riesgo_alto → HIGH, atencion → MEDIUM), the same rule the
|
||||
// "Alumnos en riesgo" screen uses, so the listing and the stats can't disagree.
|
||||
export class GetGroupsRiskOverview {
|
||||
constructor(private readonly deps: GetGroupsRiskOverviewDeps = {}) {}
|
||||
|
||||
@@ -92,10 +83,10 @@ export class GetGroupsRiskOverview {
|
||||
select: { id: true, groupId: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}) as Promise<SessionRow[]>,
|
||||
/* Sin filtro de fecha, como antes: la racha del semáforo cuenta sobre el
|
||||
historial completo del alumno, no sobre la ventana mensual. Sin recorte
|
||||
tampoco: el corte a las últimas 20 clases lo hace `memberSessions`,
|
||||
sobre las clases del grupo y no sobre estas filas. */
|
||||
/* No date filter, as before: the status light streak counts over the
|
||||
attendee's full history, not over the monthly window. No cap either:
|
||||
the cut to the last 20 classes is done by `memberSessions`, over the
|
||||
group's classes and not over these rows. */
|
||||
db.attendance.findMany({
|
||||
where: { attendee: { groupId: { in: groupIds } } },
|
||||
select: {
|
||||
@@ -117,74 +108,31 @@ export class GetGroupsRiskOverview {
|
||||
|
||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
||||
|
||||
const worstRiskByGroup = new Map<string, GroupRiskLevel>();
|
||||
// Por qué hay riesgo, en la misma pasada: un miembro con racha de faltas
|
||||
// cuenta en el primero y solo en ese; el segundo agrupa a los que no llegan
|
||||
// a racha y aun así quedan por debajo del mínimo de asistencia.
|
||||
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 items: GroupRiskSummary[] = groups.map((group) =>
|
||||
buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
|
||||
);
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* El resumen por nivel que consumen la tarjeta del listado y la sección de
|
||||
* seguimiento del Inicio. Sale de `getGroupAttendanceSummary`, la misma función
|
||||
* de dominio que se prueba en `test/attendance-risk.test.ts`, para que la regla
|
||||
* no tenga dos copias: una acá y otra en el cliente.
|
||||
* The per-level summary consumed by the listing card and Home. It comes from
|
||||
* `getGroupAttendanceSummary`, the same domain function that
|
||||
* `test/attendance-risk.test.ts` exercises, so the rule doesn't have two
|
||||
* copies: one here and another in the client.
|
||||
*
|
||||
* `libres` y `enEspera` salen de acá y no del conteo de `Attendee`: el resumen
|
||||
* cuenta los miembros del grupo y la tarjeta necesita los lugares del cupo
|
||||
* para pintar el indicador.
|
||||
* `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
|
||||
* paint the indicator.
|
||||
*/
|
||||
function buildSummaryFields(
|
||||
function buildSummary(
|
||||
group: GroupRow,
|
||||
attendees: AttendeeRow[],
|
||||
sessionsByGroup: Map<string, SessionRow[]>,
|
||||
attendanceByAttendee: Map<string, AttendanceRow[]>,
|
||||
now: Date,
|
||||
) {
|
||||
): GroupRiskSummary {
|
||||
const resumen = getGroupAttendanceSummary({
|
||||
groupId: group.id,
|
||||
capacity: group.capacity,
|
||||
@@ -192,35 +140,23 @@ function buildSummaryFields(
|
||||
now,
|
||||
members: attendees
|
||||
.filter((attendee) => attendee.groupId === group.id)
|
||||
.map((attendee) => {
|
||||
const attendeeAttendances = attendanceByAttendee.get(attendee.id) ?? [];
|
||||
// Si el alumno tiene asistencias previas a su fecha de alta en la BD (ej.
|
||||
// creado hoy pero con clases pasadas registradas), su fecha efectiva de
|
||||
// incorporación es la de la primera clase a la que se le tomó asistencia.
|
||||
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(
|
||||
.map((attendee) =>
|
||||
toMemberAttendance(
|
||||
attendee,
|
||||
sessionsByGroup.get(group.id) ?? [],
|
||||
attendeeAttendances,
|
||||
attendanceByAttendee.get(attendee.id) ?? [],
|
||||
),
|
||||
),
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
// 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
|
||||
.slice(0, URGENT_MEMBERS_LIMIT)
|
||||
.map((urgente) => ({
|
||||
@@ -232,7 +168,14 @@ function buildSummaryFields(
|
||||
attendanceRate: urgente.attendanceRate,
|
||||
}));
|
||||
|
||||
const riskLevel: GroupRiskLevel = resumen.peorNivel ? (toRiskLevel(resumen.peorNivel) ?? 'NONE') : 'NONE';
|
||||
|
||||
return {
|
||||
groupId: group.id,
|
||||
groupName: group.name,
|
||||
riskLevel,
|
||||
absenceStreakCount,
|
||||
lowAttendanceCount: atRisk.length - absenceStreakCount,
|
||||
riesgoAlto: resumen.riesgoAlto,
|
||||
atencion: resumen.atencion,
|
||||
ok: resumen.ok,
|
||||
@@ -243,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[]> {
|
||||
const byAttendee = new Map<string, AttendanceRow[]>();
|
||||
for (const row of rows) {
|
||||
@@ -256,25 +195,3 @@ function groupAttendanceByAttendee(rows: AttendanceRow[]): Map<string, Attendanc
|
||||
}
|
||||
return byAttendee;
|
||||
}
|
||||
|
||||
/* El universo de clases es el del grupo, no el de las filas de `Attendance`.
|
||||
La asistencia se carga alumno por alumno y solo cuando alguien la marca, así
|
||||
que "esta clase pasó y no hay registro de este alumno" es un estado real y
|
||||
frecuente, no una falta. Si la lista se armara desde las filas de asistencia
|
||||
esas clases no existirían y la racha no se cortaría: dos faltas separadas por
|
||||
una clase sin marcar se contarían como tres seguidas.
|
||||
El dominio ya las trata como neutras (`status: null`), así que acá solo hay
|
||||
que elegir bien el universo y dejar el criterio en un solo lado.
|
||||
`sessions` viene de más reciente a más antigua, así que quedarse con las
|
||||
primeras `MEMBER_HISTORY_LIMIT` es quedarse con las clases recientes. El
|
||||
recorte va por alumno y no global para que un grupo con mucha historia no le
|
||||
robe ventana a los grupos que se listan después. */
|
||||
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,
|
||||
}));
|
||||
}
|
||||
@@ -6,24 +6,21 @@ import type {
|
||||
StudentAtRisk,
|
||||
StudentsAtRisk,
|
||||
} from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||
import {
|
||||
classifyRisk,
|
||||
lastAttendedAt,
|
||||
monthlyAttendanceRate,
|
||||
trailingAbsentStreak,
|
||||
} from '../../lib/risk';
|
||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||
|
||||
type GetStudentsAtRiskDeps = {
|
||||
db?: AnalyticsAccessDb & Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
|
||||
db?: AnalyticsAccessDb & StudentsAtRiskDb;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
type AttendanceStreamRow = {
|
||||
attendeeId: string;
|
||||
classSessionId: string;
|
||||
status: AttendanceStatus;
|
||||
classSession: { startsAt: Date };
|
||||
};
|
||||
@@ -37,26 +34,52 @@ export class GetStudentsAtRisk {
|
||||
): Promise<Result<StudentsAtRisk, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = this.deps.now ?? new Date();
|
||||
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) {
|
||||
return access;
|
||||
}
|
||||
|
||||
const atRisk = await findStudentsAtRisk(db, groupId, now);
|
||||
|
||||
return ok({
|
||||
groupName: access.value.name,
|
||||
data: atRisk,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 },
|
||||
select: { id: true, startsAt: true },
|
||||
orderBy: { startsAt: 'desc' },
|
||||
}),
|
||||
db.attendee.findMany({
|
||||
where: { groupId, status: 'ACTIVE' },
|
||||
select: { id: true, fullName: true, phone: true },
|
||||
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 } },
|
||||
},
|
||||
@@ -69,20 +92,21 @@ export class GetStudentsAtRisk {
|
||||
|
||||
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 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,
|
||||
);
|
||||
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
|
||||
if (!riskLevel) {
|
||||
continue;
|
||||
}
|
||||
atRisk.push({
|
||||
attendeeId: attendee.id,
|
||||
fullName: attendee.fullName,
|
||||
@@ -104,11 +128,7 @@ export class GetStudentsAtRisk {
|
||||
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
|
||||
});
|
||||
|
||||
return ok({
|
||||
groupName: access.value.name,
|
||||
data: atRisk,
|
||||
});
|
||||
}
|
||||
return atRisk;
|
||||
}
|
||||
|
||||
function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> {
|
||||
|
||||
@@ -12,7 +12,7 @@ type GroupWithAccess = {
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo. Devuelve el grupo si tiene acceso.
|
||||
// Verifies the user is the group owner or a member. Returns the group if they have access.
|
||||
export async function findGroupForUser(
|
||||
db: AnalyticsAccessDb,
|
||||
groupId: string,
|
||||
|
||||
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal file
81
apps/backend/src/modules/analytics/lib/member-attendance.ts
Normal 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,
|
||||
}));
|
||||
}
|
||||
@@ -3,28 +3,7 @@ export type AttendanceStreamEntry = {
|
||||
occurredAt: Date;
|
||||
};
|
||||
|
||||
export type RiskLevel = 'HIGH' | 'MEDIUM';
|
||||
|
||||
/** Racha mínima de faltas sin justificar que ya dispara riesgo. */
|
||||
export const MIN_RISK_ABSENCE_STREAK = 2;
|
||||
|
||||
/** Asistencia mensual (ventana de 30 días) por debajo de la cual hay riesgo. */
|
||||
export const MIN_RISK_MONTHLY_RATE = 50;
|
||||
|
||||
// Cuenta las ausencias consecutivas sin justificar desde la clase más reciente.
|
||||
// Recibe la lista ordenada de más reciente a más antigua; PRESENT y EXCUSED rompen la cadena.
|
||||
export function trailingAbsentStreak(entries: AttendanceStreamEntry[]): number {
|
||||
let streak = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.status !== 'ABSENT') {
|
||||
break;
|
||||
}
|
||||
streak += 1;
|
||||
}
|
||||
return streak;
|
||||
}
|
||||
|
||||
// Fecha de la última clase a la que el alumno asistió (PRESENT), o null.
|
||||
// Date of the last class the attendee showed up to (PRESENT), or null.
|
||||
export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
for (const entry of entries) {
|
||||
if (entry.status === 'PRESENT') {
|
||||
@@ -34,8 +13,8 @@ export function lastAttendedAt(entries: AttendanceStreamEntry[]): Date | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Porcentaje de asistencia sobre el total de sesiones del período.
|
||||
// Las sesiones sin registrar cuentan como no asistidas.
|
||||
// Attendance rate over the total number of sessions in the period.
|
||||
// Sessions with no record count as not attended.
|
||||
export function monthlyAttendanceRate(
|
||||
entries: AttendanceStreamEntry[],
|
||||
totalSessions: number,
|
||||
@@ -46,17 +25,3 @@ export function monthlyAttendanceRate(
|
||||
const present = entries.filter((entry) => entry.status === 'PRESENT').length;
|
||||
return Math.round((present / totalSessions) * 100);
|
||||
}
|
||||
|
||||
// HIGH >= 3 ausencias consecutivas; MEDIUM == 2 consecutivas o asistencia mensual < 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;
|
||||
}
|
||||
@@ -8,10 +8,12 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type BulkCreateAttendeesDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
export class BulkCreateAttendeesUseCase {
|
||||
@@ -41,7 +43,7 @@ export class BulkCreateAttendeesUseCase {
|
||||
return err(noGroupAccessProblem());
|
||||
}
|
||||
|
||||
// Cargar teléfonos existentes del grupo
|
||||
// Load the group's existing phone numbers
|
||||
const existingAttendees = await db.attendee.findMany({
|
||||
where: { groupId },
|
||||
select: { phone: true },
|
||||
@@ -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[] = [];
|
||||
for (const data of toCreateData) {
|
||||
const record = await db.attendee.create({ data });
|
||||
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
notFoundResourceProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type AttendeeRecord, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type CreateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
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({
|
||||
data: {
|
||||
groupId,
|
||||
|
||||
@@ -18,18 +18,18 @@ export class ListAttendees {
|
||||
const where = query.groupId ? { groupId: query.groupId } : undefined;
|
||||
|
||||
const [records, total] = await Promise.all([
|
||||
/* El resumen de cada fila viaja en la misma consulta en vez de armarse con
|
||||
una petición por miembro. Ambas relaciones vienen acotadas a propósito:
|
||||
la tabla de pagos crece un renglón por mes y para siempre, y el listado
|
||||
solo necesita el estado actual de cada persona. */
|
||||
/* Each row's summary travels in the same query instead of being built
|
||||
with one request per member. Both relations are capped on purpose:
|
||||
the payments table grows one row per month forever, and the listing
|
||||
only needs each person's current state. */
|
||||
db.attendee.findMany({
|
||||
...(where ? { where } : {}),
|
||||
skip: getPaginationOffset(query),
|
||||
take: query.pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
// Por fecha de la clase, no por `markedAt`: marcar la asistencia
|
||||
// tarde no debe cambiar qué clase cuenta como reciente.
|
||||
// By class date, not by `markedAt`: marking attendance late must not
|
||||
// change which class counts as recent.
|
||||
attendances: {
|
||||
orderBy: { classSession: { startsAt: 'desc' } },
|
||||
take: RECENT_ATTENDANCE_LIMIT,
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import type { AttendeeDetailDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
|
||||
import { toAttendeeDto } from '../../lib/helpers';
|
||||
import { toAttendeeDetailDto } from '../../lib/helpers';
|
||||
|
||||
type GetAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
now?: () => Date;
|
||||
};
|
||||
|
||||
export class GetAttendee {
|
||||
@@ -18,7 +19,7 @@ export class GetAttendee {
|
||||
groupId: string,
|
||||
attendeeId: string,
|
||||
userId: string,
|
||||
): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
): Promise<Result<AttendeeDetailDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
@@ -26,11 +27,32 @@ export class GetAttendee {
|
||||
return access;
|
||||
}
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
const billingPeriod = currentMonthRange((this.deps.now ?? (() => new Date()))());
|
||||
const attendee = await db.attendee.findFirst({
|
||||
where: { id: attendeeId, groupId },
|
||||
include: {
|
||||
payments: {
|
||||
where: {
|
||||
status: { not: 'CANCELLED' },
|
||||
dueDate: { gte: billingPeriod.start, lt: billingPeriod.end },
|
||||
},
|
||||
orderBy: { dueDate: 'desc' },
|
||||
take: 1,
|
||||
select: { status: true, dueDate: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!attendee) {
|
||||
return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
}
|
||||
|
||||
return ok(toAttendeeDto(attendee));
|
||||
return ok(toAttendeeDetailDto(attendee));
|
||||
}
|
||||
}
|
||||
|
||||
function currentMonthRange(now: Date) {
|
||||
return {
|
||||
start: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)),
|
||||
end: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)),
|
||||
};
|
||||
}
|
||||
|
||||
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal file
24
apps/backend/src/modules/attendees/features/update/route.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { UpdateAttendee } from '@gruperly/shared';
|
||||
import { UpdateAttendeeSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { UpdateAttendeeDetails } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.patch('/:groupId/attendees/:attendeeId', validate.json(UpdateAttendeeSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new UpdateAttendeeDetails();
|
||||
const result = await useCase.execute({
|
||||
groupId: c.req.param('groupId'),
|
||||
attendeeId: c.req.param('attendeeId'),
|
||||
userId: user.id,
|
||||
input: c.req.valid('json') as UpdateAttendee,
|
||||
});
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { AttendeeDto, ProblemDetails, Result, UpdateAttendee } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||
import { toAttendeeDto } from '../../lib/helpers';
|
||||
|
||||
type UpdateAttendeeDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||
};
|
||||
|
||||
type UpdateAttendeeCommand = {
|
||||
groupId: string;
|
||||
attendeeId: string;
|
||||
userId: string;
|
||||
input: UpdateAttendee;
|
||||
};
|
||||
|
||||
export class UpdateAttendeeDetails {
|
||||
constructor(private readonly deps: UpdateAttendeeDeps = {}) {}
|
||||
|
||||
async execute(command: UpdateAttendeeCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||
const { groupId, attendeeId, userId, input } = command;
|
||||
const db = this.deps.db ?? prisma;
|
||||
const access = await findGroupForUser(db, groupId, userId);
|
||||
if (!access.ok) return access;
|
||||
|
||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
|
||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||
|
||||
const updated = await db.attendee.update({
|
||||
where: { id: attendeeId },
|
||||
data: normalizeEditableFields(input),
|
||||
});
|
||||
return ok(toAttendeeDto(updated));
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
|
||||
return Object.fromEntries(
|
||||
Object.entries(input).map(([key, value]) => [key, value === '' ? null : value]),
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||
|
||||
export type AttendeeRecord = {
|
||||
id: string;
|
||||
@@ -14,7 +14,7 @@ export type AttendeeRecord = {
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
/** Item del listado con el resumen de asistencia y cobro ya resuelto. */
|
||||
/** Listing item with the attendance and payment summary already resolved. */
|
||||
export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
|
||||
payments: {
|
||||
@@ -23,6 +23,10 @@ export type AttendeeListItemRecord = AttendeeRecord & {
|
||||
}[];
|
||||
};
|
||||
|
||||
export type AttendeeDetailRecord = AttendeeRecord & {
|
||||
payments: AttendeeListItemRecord['payments'];
|
||||
};
|
||||
|
||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
return {
|
||||
id: record.id,
|
||||
@@ -39,15 +43,15 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||
};
|
||||
}
|
||||
|
||||
/* El renglón que resume el cobro vigente. Si hay algo impago manda el de
|
||||
vencimiento más antiguo: quien arrastra un cargo viejo tiene que ver cuántos
|
||||
días lleva atras, no el vencimiento de un cargo nuevo. Si no queda nada
|
||||
impago, el último pago cerrado sirve para marcar la fila como al día. */
|
||||
/* The row that summarizes the current charge. If something is unpaid the
|
||||
oldest due date wins: someone carrying an old charge has to see how many
|
||||
days late they are, not the due date of a new charge. If nothing is left
|
||||
unpaid, the last closed payment serves to mark the row as ok. */
|
||||
function pickRelevantPayment(
|
||||
payments: AttendeeListItemRecord['payments'],
|
||||
): AttendeeListItem['payment'] {
|
||||
// CANCELLED no es un cobro. La consulta ya los deja fuera, pero descartarlos
|
||||
// acá también evita que un cargo anulado gane la fila por ser el más antiguo.
|
||||
// CANCELLED is not a charge. The query already filters them out, but dropping
|
||||
// them here too keeps a voided charge from winning the row for being the oldest.
|
||||
const byDueDate = payments
|
||||
.filter((payment) => payment.status !== 'CANCELLED')
|
||||
.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime());
|
||||
@@ -60,8 +64,15 @@ function pickRelevantPayment(
|
||||
return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
|
||||
}
|
||||
|
||||
/* La consulta viene en orden descendente; la fila los muestra de más antigua a
|
||||
más reciente para que el punto de la derecha sea el último hecho. */
|
||||
export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetailDto {
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
payment: pickRelevantPayment(record.payments),
|
||||
};
|
||||
}
|
||||
|
||||
/* The query comes in descending order; the row shows them from oldest to most
|
||||
recent so the dot on the right is the latest event. */
|
||||
export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeListItem {
|
||||
return {
|
||||
...toAttendeeDto(record),
|
||||
@@ -71,8 +82,8 @@ export function toAttendeeListItemDto(record: AttendeeListItemRecord): AttendeeL
|
||||
}
|
||||
|
||||
/**
|
||||
* Normaliza números de teléfono eliminando espacios, guiones, paréntesis y puntos.
|
||||
* Conserva el '+' si lo tiene al inicio para números internacionales.
|
||||
* Normalizes phone numbers by stripping spaces, dashes, parentheses and dots.
|
||||
* Keeps a leading '+' for international numbers.
|
||||
*/
|
||||
export function normalizePhone(rawPhone: string): string {
|
||||
const trimmed = rawPhone.trim();
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
}
|
||||
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal file
23
apps/backend/src/modules/attention/features/resolve/route.ts
Normal 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;
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
1
apps/backend/src/modules/attention/index.ts
Normal file
1
apps/backend/src/modules/attention/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as attentionRoutes } from './routes';
|
||||
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal file
13
apps/backend/src/modules/attention/lib/alert-kind.ts
Normal 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',
|
||||
};
|
||||
10
apps/backend/src/modules/attention/routes.ts
Normal file
10
apps/backend/src/modules/attention/routes.ts
Normal 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;
|
||||
@@ -14,6 +14,7 @@ export const auth = betterAuth({
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
minPasswordLength: 8,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await emailProvider.sendPasswordResetEmail({
|
||||
email: user.email,
|
||||
|
||||
15
apps/backend/src/modules/billing/features/cancel/route.ts
Normal file
15
apps/backend/src/modules/billing/features/cancel/route.ts
Normal 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;
|
||||
49
apps/backend/src/modules/billing/features/cancel/use-case.ts
Normal file
49
apps/backend/src/modules/billing/features/cancel/use-case.ts
Normal 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' });
|
||||
}
|
||||
}
|
||||
19
apps/backend/src/modules/billing/features/charges/route.ts
Normal file
19
apps/backend/src/modules/billing/features/charges/route.ts
Normal 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;
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
}
|
||||
15
apps/backend/src/modules/billing/features/status/route.ts
Normal file
15
apps/backend/src/modules/billing/features/status/route.ts
Normal 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;
|
||||
78
apps/backend/src/modules/billing/features/status/use-case.ts
Normal file
78
apps/backend/src/modules/billing/features/status/use-case.ts
Normal 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
21
apps/backend/src/modules/billing/features/subscribe/route.ts
Normal file
21
apps/backend/src/modules/billing/features/subscribe/route.ts
Normal 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;
|
||||
115
apps/backend/src/modules/billing/features/subscribe/use-case.ts
Normal file
115
apps/backend/src/modules/billing/features/subscribe/use-case.ts
Normal 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 });
|
||||
}
|
||||
}
|
||||
41
apps/backend/src/modules/billing/features/webhook/route.ts
Normal file
41
apps/backend/src/modules/billing/features/webhook/route.ts
Normal 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;
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
4
apps/backend/src/modules/billing/index.ts
Normal file
4
apps/backend/src/modules/billing/index.ts
Normal 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';
|
||||
2
apps/backend/src/modules/billing/jobs/index.ts
Normal file
2
apps/backend/src/modules/billing/jobs/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
|
||||
export { startBillingJobs } from './schedule';
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
24
apps/backend/src/modules/billing/jobs/schedule.ts
Normal file
24
apps/backend/src/modules/billing/jobs/schedule.ts
Normal 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();
|
||||
}
|
||||
16
apps/backend/src/modules/billing/lib/config.ts
Normal file
16
apps/backend/src/modules/billing/lib/config.ts
Normal 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;
|
||||
}
|
||||
173
apps/backend/src/modules/billing/lib/entitlements.ts
Normal file
173
apps/backend/src/modules/billing/lib/entitlements.ts
Normal 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];
|
||||
}
|
||||
}
|
||||
27
apps/backend/src/modules/billing/lib/helpers.ts
Normal file
27
apps/backend/src/modules/billing/lib/helpers.ts
Normal 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;
|
||||
13
apps/backend/src/modules/billing/lib/index.ts
Normal file
13
apps/backend/src/modules/billing/lib/index.ts
Normal 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';
|
||||
29
apps/backend/src/modules/billing/lib/read-only-middleware.ts
Normal file
29
apps/backend/src/modules/billing/lib/read-only-middleware.ts
Normal 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();
|
||||
};
|
||||
}
|
||||
164
apps/backend/src/modules/billing/lib/sync.ts
Normal file
164
apps/backend/src/modules/billing/lib/sync.ts
Normal 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 });
|
||||
}
|
||||
}
|
||||
124
apps/backend/src/modules/billing/providers/billing-provider.ts
Normal file
124
apps/backend/src/modules/billing/providers/billing-provider.ts
Normal 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();
|
||||
}
|
||||
32
apps/backend/src/modules/billing/providers/index.ts
Normal file
32
apps/backend/src/modules/billing/providers/index.ts
Normal 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();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
199
apps/backend/src/modules/billing/providers/mercado-pago/index.ts
Normal file
199
apps/backend/src/modules/billing/providers/mercado-pago/index.ts
Normal 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 };
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
18
apps/backend/src/modules/billing/providers/stripe/config.ts
Normal file
18
apps/backend/src/modules/billing/providers/stripe/config.ts
Normal 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 };
|
||||
}
|
||||
300
apps/backend/src/modules/billing/providers/stripe/index.ts
Normal file
300
apps/backend/src/modules/billing/providers/stripe/index.ts
Normal 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;
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
16
apps/backend/src/modules/billing/routes.ts
Normal file
16
apps/backend/src/modules/billing/routes.ts
Normal 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;
|
||||
@@ -7,7 +7,7 @@ import { GetAbsenceDetails } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno entra con su token personal.
|
||||
// Public route (whitelisted in session-auth): the attendee gets in with their personal token.
|
||||
route.get('/absence', validate.query(AbsenceQuerySchema), async (c) => {
|
||||
const query = c.req.valid('query') as AbsenceQuery;
|
||||
const useCase = new GetAbsenceDetails();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PublicNotifyAbsenceUseCase } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
// Ruta pública (whitelistada en session-auth): el alumno avisa su ausencia con token.
|
||||
// Public route (whitelisted in session-auth): the attendee reports an absence with a token.
|
||||
route.post('/notify-absence', validate.json(PublicNotifyAbsenceSchema), async (c) => {
|
||||
const payload = c.req.valid('json') as PublicNotifyAbsence;
|
||||
const useCase = new PublicNotifyAbsenceUseCase();
|
||||
|
||||
@@ -18,8 +18,8 @@ type PaymentLike = {
|
||||
dueDate: Date;
|
||||
};
|
||||
|
||||
// Estado de cobro calculado en tiempo real (sin columna denormalizada):
|
||||
// PENDIENTE si hay un pago vencido (OVERDUE) o un PENDING cuyo vencimiento ya pasó.
|
||||
// Payment status computed in real time (no denormalized column):
|
||||
// PENDING if there is an overdue payment (OVERDUE) or a PENDING whose due date has passed.
|
||||
export function resolvePaymentStatus(
|
||||
payments: PaymentLike[],
|
||||
startOfToday: Date,
|
||||
@@ -52,7 +52,7 @@ type GroupWithAccess = {
|
||||
members: { userId: string }[];
|
||||
};
|
||||
|
||||
// Verifica que el usuario sea owner o miembro del grupo dueño de la sesión.
|
||||
// Verifies the user is the owner or a member of the group that owns the session.
|
||||
export function ensureSessionAccess(
|
||||
session: ClassSessionRecord & { group: GroupWithAccess },
|
||||
userId: string,
|
||||
|
||||
@@ -17,9 +17,9 @@ type RegisterAbsenceInput = {
|
||||
releaseHours: number;
|
||||
};
|
||||
|
||||
// Núcleo compartido del aviso de ausencia (profesor autenticado y alumno con token):
|
||||
// - Marca la asistencia como EXCUSED (upsert idempotente).
|
||||
// - Si la anticipación alcanza `releaseHours`, crea/conserva un SlotRelease para liberar el cupo.
|
||||
// Shared core of the absence notice (authenticated teacher and attendee with a token):
|
||||
// - Marks the attendance as EXCUSED (idempotent upsert).
|
||||
// - If the notice comes early enough to meet `releaseHours`, creates/keeps a SlotRelease to free the spot.
|
||||
export async function registerAbsence(
|
||||
deps: RegisterAbsenceDeps,
|
||||
input: RegisterAbsenceInput,
|
||||
|
||||
@@ -13,7 +13,7 @@ type ScheduledGroup = {
|
||||
time: string | null;
|
||||
};
|
||||
|
||||
// Calcula qué grupos tienen clase hoy (según days/time y la zona horaria del profesor).
|
||||
// Computes which groups have a class today (from days/time and the teacher's time zone).
|
||||
export function buildTodayCandidates(
|
||||
groups: ScheduledGroup[],
|
||||
now: Date,
|
||||
@@ -37,7 +37,7 @@ export function buildTodayCandidates(
|
||||
return candidates;
|
||||
}
|
||||
|
||||
// Materializa (upsert idempotente) las ClassSession del día y devuelve sus ids.
|
||||
// Materializes (idempotent upsert) today's ClassSession rows and returns their ids.
|
||||
export async function ensureTodaySessions(
|
||||
db: Pick<ClassesDb, 'classSession'>,
|
||||
candidates: TodaySessionCandidate[],
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -18,6 +19,7 @@ import { type GroupPreRegistrationRecord } from '../../lib/helpers';
|
||||
type ApproveGroupPreRegistrationDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupPreRegistration'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ProblemDetails, PromoteGroupWaitlistEntryResult, Result } from '@g
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import {
|
||||
findGroupOwnedByUser,
|
||||
type GroupWaitlistEntryRecord,
|
||||
@@ -12,6 +13,7 @@ import { promoteWaitlistEntryRecord } from '../../lib/promote';
|
||||
type PromoteGroupWaitlistEntryDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'groupWaitlistEntry'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canAddAttendees'>;
|
||||
};
|
||||
|
||||
export class PromoteGroupWaitlistEntry {
|
||||
@@ -37,6 +39,11 @@ export class PromoteGroupWaitlistEntry {
|
||||
return err(notFoundResourceProblem('GroupWaitlistEntry', entryId));
|
||||
}
|
||||
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(userId);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
return unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const promoteResult = await promoteWaitlistEntryRecord(
|
||||
|
||||
@@ -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 type {
|
||||
CreateFirstGroup as CreateGroupInput,
|
||||
@@ -6,14 +6,14 @@ import type {
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { paymentNotSetupProblem } from '@/http/problem-builders';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||
import { type GroupRecord, toGroupDto } from '../../lib';
|
||||
|
||||
type CreateGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupMember' | 'merchantAccount'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
||||
};
|
||||
|
||||
export class CreateGroup {
|
||||
@@ -23,12 +23,11 @@ export class CreateGroup {
|
||||
data: CreateGroupInput,
|
||||
userId: string,
|
||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } });
|
||||
if (!merchantAccount) {
|
||||
return err(paymentNotSetupProblem());
|
||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
|
||||
if (!allowed.ok) {
|
||||
return allowed;
|
||||
}
|
||||
|
||||
const transaction = unitOfWork.executeResult(
|
||||
|
||||
@@ -24,9 +24,9 @@ type ListGroupsDeps = {
|
||||
const OCCUPANCY_COUNT_INCLUDE = {
|
||||
_count: {
|
||||
select: {
|
||||
// Miembros del grupo. Sin filtro de estado, igual que cuenta el detalle.
|
||||
// Group members. No status filter, same as the detail page counts.
|
||||
attendees: true,
|
||||
// Lista de espera: los que todavía esperan cupo (los revisados salen).
|
||||
// Waitlist: the ones still waiting for a spot (the reviewed ones drop out).
|
||||
waitlist: { where: { status: 'PENDING' as const } },
|
||||
},
|
||||
},
|
||||
@@ -43,10 +43,10 @@ export class ListGroups {
|
||||
const now = this.deps.now ?? new Date();
|
||||
const where = buildGroupWhereForUser(userId) as Prisma.GroupWhereInput;
|
||||
|
||||
// Traemos los grupos del usuario con sus contadores y los ordenamos acá:
|
||||
// la próxima clase se deriva de días + hora, no hay columna por la que
|
||||
// ordenar en la base. Es el mismo motor que usa el resumen de home, con la
|
||||
// zona horaria de la persona (o la del servidor si no viaja).
|
||||
// We fetch the user's groups with their counters and sort them here: the next
|
||||
// class is derived from days + time, there is no column to sort on in the
|
||||
// database. It's the same engine the home summary uses, with the person's
|
||||
// time zone (or the server's if it doesn't come along).
|
||||
const records: GroupListRecord[] = await db.group.findMany({
|
||||
where,
|
||||
include: OCCUPANCY_COUNT_INCLUDE,
|
||||
@@ -58,9 +58,9 @@ export class ListGroups {
|
||||
nextAt: nextOccurrenceAt(record, now, timeZone),
|
||||
}));
|
||||
|
||||
/* Un grupo sin horario no tiene clase que comparar, así que va al final;
|
||||
entre grupos con la misma clase (o sin horario) desempata el más nuevo,
|
||||
que era el criterio anterior de la lista. */
|
||||
/* A group with no schedule has no class to compare, so it goes last;
|
||||
between groups with the same class (or with no schedule) the newest one
|
||||
breaks the tie, which was the listing's previous criterion. */
|
||||
const ordered = withNextClass.sort((a, b) => {
|
||||
if (a.nextAt !== null && b.nextAt !== null) {
|
||||
return a.nextAt - b.nextAt || b.record.createdAt.getTime() - a.record.createdAt.getTime();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user