` 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 `` 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). **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
- `stack.md` — arquitectura y spec técnica de referencia (UI tokens exactos, stack por app).
-- `README.md` — setup de la base de datos y comandos generales.
\ No newline at end of file
+- `README.md` — setup de la base de datos y comandos generales.
diff --git a/Dockerfile.backend b/Dockerfile.backend
new file mode 100644
index 0000000..a5662a9
--- /dev/null
+++ b/Dockerfile.backend
@@ -0,0 +1,66 @@
+# syntax=docker/dockerfile:1
+
+# ─── Base ────────────────────────────────────────────────────────────────────
+FROM oven/bun:1.4-alpine AS base
+WORKDIR /app
+ENV CI=1
+
+# ─── 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/
+# 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 ───────────────────────────────────────────────────────────
+# 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
+COPY apps/backend/prisma.config.ts ./apps/backend/
+COPY apps/backend/prisma ./apps/backend/prisma
+WORKDIR /app/apps/backend
+RUN bun run db:generate
+
+# ─── API image ───────────────────────────────────────────────────────────────
+FROM base AS api
+ENV NODE_ENV=production \
+ PORT=4000
+
+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` 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
+
+# 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 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
+# 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 runs the TypeScript directly and resolves `@/*` with the tsconfig.json,
+# same as `bun start` locally.
+CMD ["bun", "src/server.ts"]
diff --git a/Dockerfile.web b/Dockerfile.web
new file mode 100644
index 0000000..d7509c9
--- /dev/null
+++ b/Dockerfile.web
@@ -0,0 +1,35 @@
+# syntax=docker/dockerfile:1
+
+# ─── Base ────────────────────────────────────────────────────────────────────
+FROM oven/bun:1.4-alpine AS base
+WORKDIR /app
+ENV CI=1
+
+# ─── 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/
+# bun's global cache weighs ~370MB: it is dropped in the same layer.
+RUN bun install --frozen-lockfile && rm -rf /root/.bun/install
+
+# ─── Vite build ──────────────────────────────────────────────────────────────
+FROM deps AS build
+# 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
+
+# ─── 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
+EXPOSE 80
+HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
+ CMD wget --quiet --tries=1 --spider http://127.0.0.1/ || exit 1
+CMD ["nginx", "-g", "daemon off;"]
diff --git a/README.md b/README.md
index 87cfb83..2bcc883 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@ Monorepo de Gruperly. Consulta [stack.md](./stack.md) para arquitectura y especi
- Package manager: [Bun](https://bun.sh/) 1.4
- Monorepo: bun workspaces + Turborepo
- Backend (`apps/backend`): Bun + Hono (`Bun.serve`) + Prisma + PostgreSQL + Better Auth
-- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4
+- Frontend (`apps/web`): React 19 + TypeScript + TanStack Router + TanStack Query + Tailwind v4 + PWA (vite-plugin-pwa / Workbox)
- Shared (`packages/shared`): esquemas Zod, tipos, `Result` y Problem Details compartidos
## Estructura
@@ -31,9 +31,202 @@ bun run lint # biome check (backend y shared)
bun --filter @gruperly/backend test # bun test (backend)
bun --filter @gruperly/backend db:push # Aplica el esquema de Prisma a la base de datos
bun --filter @gruperly/backend db:studio # Abre Prisma Studio
+bun --filter @gruperly/web icons # Regenera los iconos PWA de public/ desde el isotipo SVG
```
+## PWA
+
+La web es instalable y abre sin conexión el shell de la app (rutas, JS, CSS, tipografía e iconos). Los datos de la API **no** se cachean: son cobros y una respuesta vieja sería peor que un error, así que offline la app carga pero las consultas fallan.
+
+- **Manifest y service worker**: `apps/web/vite.config.ts` (`VitePWA`, `generateSW`, `registerType: 'autoUpdate'`). El registro se hace desde `apps/web/src/features/pwa/PwaProvider.tsx` (`injectRegister: null`) para poder avisar con un toast cuando la app ya quedó lista para offline.
+- **`workbox-window` es dependencia directa de `apps/web` a propósito**: `virtual:pwa-register` la importa desde el grafo de la app, pero llega como dependencia transitiva de `vite-plugin-pwa`. Localmente bun la hoistea a la raíz y todo anda; en la imagen de Docker bun usa el layout aislado y la deja solo en `node_modules/.bun/`, así que Rollup falla con `failed to resolve import "workbox-window"` y el build de Dokploy se cae. Declararla en `apps/web/package.json` la hace resoluble desde `apps/web/node_modules/`. **No la borres por "no estar imports en el código".**
+- **Iconos**: se generan con sharp desde `apps/web/src/assets/brand/isotipo-y-organica.svg` y se versionan en `apps/web/public/` (`pwa-192x192`, `pwa-512x512`, `pwa-maskable-512x512`, `apple-touch-icon-180`). El build **no** los regenera; corré `bun --filter @gruperly/web icons` cuando cambie el isotipo.
+- **Tipografía**: Inter variable auto-hospedada vía `@fontsource-variable/inter`, declarada a mano en `apps/web/src/index.css`. No hay `` a `fonts.googleapis.com`: era una dependencia de red en runtime.
+- **Aviso de instalación**: la lógica de *cuándo* se ofrece vive en `apps/web/src/features/pwa/PwaProvider.tsx` (captura `beforeinstallprompt`, gate de sesión, dwell y descarte) y el dibujo en `InstallPrompt.tsx` → `InstallBanner.tsx` (Chromium) o `IosInstallHint.tsx` (Safari en iOS, que no dispara el evento y hay que instruir con Compartir → Agregar a pantalla de inicio).
+ - Se ofrece solo con **sesión iniciada**, **fuera del onboarding** y después de **20 s seguidos en la misma ruta**; `beforeinstallprompt` llega a los segundos y sin ese margen el aviso cae en medio de la primera tarea de la visita. Navegar antes de que se cumpla el tiempo reinicia la cuenta; una vez cumplido no se oculta más al navegar.
+ - El descarte es definitivo: se guarda en `localStorage['pwa-install-dismissed']` y no vuelve a preguntar en ese navegador.
+ - El timer vive en el provider y no en el componente que dibuja el aviso a propósito: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un timer en el hijo se perdería en cada navegación. El provider, en cambio, sigue montado y se suscribe al router (`router.subscribe('onResolved')`) porque está fuera del `RouterProvider`.
+ - Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` sin usuario—, así que el gate se chequea en el provider y no se puede inferir de dónde se monte el prompt.
+- **nginx**: `apps/web/nginx.conf` sirve `sw.js`, `workbox-*.js` y `manifest.webmanifest` con `Cache-Control: no-cache` y `=404` (no el fallback del SPA), para que una versión vieja no quede cacheada para siempre.
+
+### Requisitos para que funcione
+
+El service worker necesita un **contexto seguro**: HTTPS, o `http://localhost`. Probar por IP de LAN sobre `http://` no registra el SW en silencio, sin error visible. En producción el TLS lo termina Traefik adelante de nginx.
+
+### Verificar
+
+```bash
+bun --filter @gruperly/web build
+bun --filter @gruperly/web preview # http://localhost:4173
+```
+
+En DevTools → Application: el manifest sin warnings, el service worker `activated`, y en Network → Offline un reload de `/` o `/groups` tiene que seguir pintando la app. `bun dev` también registra el SW (está en `devOptions`), así que se puede probar sin build, pero `dev-dist/` queda gitignoreado.
+
## Setup de base de datos
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).
\ No newline at end of file
+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: ' | 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).
+
+- `api` corre Bun sobre el TypeScript fuente (`bun src/server.ts`), igual que en local: el cliente de Prisma se genera como TS y el tsconfig resuelve los aliases `@/*`.
+- Al arrancar, `apps/backend/docker-entrypoint.sh` aplica `prisma migrate deploy` y recién después levanta el servidor. Si la migración falla, el contenedor no levanta y el error queda en los logs del servicio. Reintenta hasta 30 veces (5s) porque la base puede seguir arrancando.
+- `web` compila con Vite y lo sirve nginx, que además hace de proxy de `/api` hacia `api`. Así el navegador siempre pega al mismo origen: la cookie de sesión es first-party y el CORS del backend no se activa.
+- Ambos servicios se enchufan a `dokploy-network`, la red donde Dokploy deja las bases de datos que administra. Dokploy solo agrega esa red al servicio al que le asociás el dominio, así que está declarada a mano en el compose: sin ella, `api` no alcanza a la base y Prisma falla con `P1001 Can't reach database server`.
+
+### Variables de entorno
+
+El compose las interpola desde el entorno. En Dokploy van en la pestaña **Environment** del servicio Compose (Dokploy las guarda en un `.env` al lado del `docker-compose.yml`); en local, copiá `.env.example` → `.env` en la raíz.
+
+| Variable | ¿Obligatoria? | Descripción |
+| --- | --- | --- |
+| `DATABASE_URL` | sí | `postgresql://user:pass@host:5432/gruperly?schema=public`. La password va percent-encoded: `#` → `%23`, `@` → `%40`, `:` → `%3A`, `/` → `%2F`, `?` → `%3F`, `%` → `%25`, espacio → `%20`. Sin eso, Prisma corta la URL en el fragmento y falla con `P1013 invalid port number` |
+| `WEB_URL` | sí | Origen público de la app, sin barra final (`https://gruperly.com`). Alimenta `WEB_URL` y `BETTER_AUTH_URL` del contenedor, porque el proxy de nginx deja web y API en el mismo dominio |
+| `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 |
+
+Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre de la variable en el mensaje.
+
+### Pasos en Dokploy
+
+1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
+2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
+3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway.
+4. Deploy.
+
+En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
+
+Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
+
+### Correr las migraciones a mano
+
+```bash
+docker compose exec api bun run db:deploy
+```
+
+### Comprobar el compose en local
+
+Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la declara como externa:
+
+```bash
+docker network create dokploy-network # una sola vez
+cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
+docker compose up --build -d
+docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
+curl http://localhost:8080/api/v1/health
+```
diff --git a/apps/backend/.agents/skills/prisma-cli/SKILL.md b/apps/backend/.agents/skills/prisma-cli/SKILL.md
new file mode 100644
index 0000000..b2b770e
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/SKILL.md
@@ -0,0 +1,265 @@
+---
+name: prisma-cli
+description: Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, complete, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not the Prisma Platform CLI. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma complete", "prisma studio", "prisma mcp".
+license: MIT
+metadata:
+ author: prisma
+ version: "7.9.1"
+---
+
+# Prisma CLI Reference
+
+Reference for Prisma ORM CLI commands. This skill provides guidance on command usage, options, and best practices for current Prisma ORM releases.
+
+## Boundary: Platform and Compute
+
+Do not confuse the stable ORM command (`prisma`) with the public-beta Platform package (`@prisma/cli`, binary `prisma-cli`). Use `prisma-compute` for Compute apps and workspace auth, and `prisma-postgres` for Platform projects and databases.
+
+## When to Apply
+
+Reference this skill when:
+- Setting up a new Prisma project (`prisma init`)
+- Generating Prisma Client (`prisma generate`)
+- Running database migrations (`prisma migrate`)
+- Managing database state (`prisma db push/pull`)
+- Using local development database (`prisma dev`)
+- Debugging Prisma issues (`prisma debug`)
+- Generating shell completions (`prisma complete`)
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Setup | HIGH | `init` |
+| 2 | Generation | HIGH | `generate` |
+| 3 | Development | HIGH | `dev` |
+| 4 | Database | HIGH | `db-` |
+| 5 | Migrations | CRITICAL | `migrate-` |
+| 6 | Utility | MEDIUM | `complete`, `studio`, `validate`, `format`, `debug`, `mcp` |
+
+## Command Categories
+
+| Category | Commands | Purpose |
+|----------|----------|---------|
+| Setup | `init` | Initialize a Prisma project |
+| Generation | `generate` | Generate Prisma Client |
+| Validation | `validate`, `format` | Schema validation and formatting |
+| Development | `dev` | Local Prisma Postgres for development |
+| Database | `db pull`, `db push`, `db seed`, `db execute` | Direct database operations |
+| Migrations | `migrate dev`, `migrate deploy`, `migrate reset`, `migrate status`, `migrate diff`, `migrate resolve` | Schema migrations |
+| Utility | `complete`, `studio`, `mcp`, `version`, `debug` | Shell, development, and AI tooling |
+
+## Quick Reference
+
+### Project Setup
+
+```bash
+# Initialize new project (creates prisma/ folder and prisma.config.ts)
+prisma init
+
+# Initialize with specific database
+prisma init --datasource-provider postgresql
+prisma init --datasource-provider mysql
+prisma init --datasource-provider sqlite
+
+# Initialize with Prisma Postgres (cloud)
+prisma init --db
+
+# Initialize with an example model
+prisma init --with-model
+
+```
+
+### Client Generation
+
+```bash
+# Generate Prisma Client
+prisma generate
+
+# Watch mode for development
+prisma generate --watch
+
+# Generate specific generator only
+prisma generate --generator client
+```
+
+### Bun Runtime
+
+When using Bun, always add the `--bun` flag so Prisma runs with the Bun runtime (otherwise it falls back to Node.js because of the CLI shebang):
+
+```bash
+bunx --bun prisma init
+bunx --bun prisma generate
+```
+
+### Local Development Database
+
+```bash
+# Start local Prisma Postgres
+prisma dev
+
+# Start with specific name
+prisma dev --name myproject
+
+# Start in background (detached)
+prisma dev --detach
+
+# List all local instances
+prisma dev ls
+
+# Stop instance
+prisma dev stop myproject
+
+# Remove instance data
+prisma dev rm myproject
+```
+
+### Database Operations
+
+```bash
+# Pull schema from existing database
+prisma db pull
+
+# Push schema to database (no migrations)
+prisma db push
+
+# Seed database
+prisma db seed
+
+# Execute raw SQL
+prisma db execute --file ./script.sql
+```
+
+### Migrations (Development)
+
+```bash
+# Create and apply migration
+prisma migrate dev
+
+# Create migration with name
+prisma migrate dev --name add_users_table
+
+# Create migration without applying
+prisma migrate dev --create-only
+
+# Reset database and apply all migrations
+prisma migrate reset
+```
+
+### Migrations (Production)
+
+```bash
+# Apply pending migrations (CI/CD)
+prisma migrate deploy
+
+# Check migration status
+prisma migrate status
+
+# Compare schemas and generate diff
+prisma migrate diff --from-config-datasource --to-schema schema.prisma --script
+```
+
+### Utility Commands
+
+```bash
+# Open Prisma Studio (database GUI)
+prisma studio
+
+# Start Prisma's MCP server for AI tools
+prisma mcp
+
+# Show version info
+prisma version
+prisma -v
+
+# Debug information
+prisma debug
+
+# Validate schema
+prisma validate
+
+# Format schema
+prisma format
+
+# Generate shell completion code
+prisma complete zsh
+```
+
+## AI Safety Checkpoint
+
+Prisma blocks destructive commands when it detects an AI agent until the agent has obtained explicit user consent. This covers `migrate reset`, `db push --force-reset`, and `db push --accept-data-loss`.
+
+- Explain the exact data-loss impact and ask for consent immediately before running the command.
+- Do not infer consent from earlier or unrelated messages.
+- If automation needs the consent variable, set `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` to the user's exact consent message. Do not invent the text.
+- The Prisma MCP server deliberately has no `migrate-reset` tool.
+
+Read `references/agent-safety.md` before any destructive Prisma command.
+
+## Current Prisma CLI Setup
+
+### New Configuration File
+
+Use `prisma.config.ts` for CLI configuration:
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ migrations: {
+ path: 'prisma/migrations',
+ seed: 'tsx prisma/seed.ts',
+ },
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+### Current Command Behavior
+
+- Run `prisma generate` explicitly after `migrate dev`, `db push`, or other schema syncs when you need fresh client output
+- Run `prisma db seed` explicitly after `migrate dev` or `migrate reset` when you need seed data
+- Use `prisma db execute --file ...` for raw SQL scripts
+
+### Environment Variables
+
+Load environment variables explicitly in `prisma.config.ts`, commonly with `dotenv`:
+
+```typescript
+// prisma.config.ts
+import 'dotenv/config'
+```
+
+## Rule Files
+
+See individual rule files for detailed command documentation:
+
+```
+references/init.md - Project initialization
+references/generate.md - Client generation
+references/dev.md - Local development database
+references/db-pull.md - Database introspection
+references/db-push.md - Schema push
+references/db-seed.md - Database seeding
+references/db-execute.md - Raw SQL execution
+references/migrate-dev.md - Development migrations
+references/migrate-deploy.md - Production migrations
+references/migrate-reset.md - Database reset
+references/migrate-status.md - Migration status
+references/migrate-resolve.md - Migration resolution
+references/migrate-diff.md - Schema diffing
+references/studio.md - Database GUI
+references/mcp.md - Prisma MCP server
+references/complete.md - Shell completion generation
+references/agent-safety.md - AI consent checkpoint for destructive commands
+references/validate.md - Schema validation
+references/format.md - Schema formatting
+references/debug.md - Debug info
+```
+
+## How to Use
+
+Use the command categories above for navigation, then open the specific command reference file you need.
diff --git a/apps/backend/.agents/skills/prisma-cli/references/agent-safety.md b/apps/backend/.agents/skills/prisma-cli/references/agent-safety.md
new file mode 100644
index 0000000..651c6c3
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/agent-safety.md
@@ -0,0 +1,27 @@
+# AI safety checkpoint for destructive commands
+
+Prisma detects common AI-agent environments and blocks these commands until the user gives explicit consent:
+
+- `prisma migrate reset`
+- `prisma db push --force-reset`
+- `prisma db push --accept-data-loss`
+
+## Required workflow
+
+1. Inspect the target database/config and explain exactly what can be deleted or reset.
+2. Ask the user for explicit consent immediately before the action.
+3. Run the command only after that consent.
+
+For an agent-run subprocess, Prisma accepts the exact consent text through:
+
+```bash
+PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION='' prisma migrate reset --force
+```
+
+The value must match the user's message exactly and must not contain added quotes or newlines. Never fabricate consent, reuse an old unrelated approval, or bypass the checkpoint by hiding agent-detection environment variables.
+
+The MCP server has no `migrate-reset` tool. Use the shell command only after consent.
+
+## Reference
+
+- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)
diff --git a/apps/backend/.agents/skills/prisma-cli/references/complete.md b/apps/backend/.agents/skills/prisma-cli/references/complete.md
new file mode 100644
index 0000000..7332440
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/complete.md
@@ -0,0 +1,22 @@
+# prisma complete
+
+Prints a shell completion script.
+
+```bash
+prisma complete zsh
+prisma complete bash
+prisma complete fish
+prisma complete powershell
+```
+
+For a direct global CLI installation, load the output using the shell's normal startup mechanism. For example, in zsh:
+
+```bash
+source <(prisma complete zsh)
+```
+
+Prisma also integrates with supported package-manager completion flows. `npx` and `bunx` do not themselves provide completion; invoke the installed binary or the package manager's supported execution form such as `npm exec` or `bun x`.
+
+## Reference
+
+- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)
diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-execute.md b/apps/backend/.agents/skills/prisma-cli/references/db-execute.md
new file mode 100644
index 0000000..c966f23
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/db-execute.md
@@ -0,0 +1,78 @@
+# prisma db execute
+
+Execute native commands (SQL) to your database.
+
+## Command
+
+```bash
+prisma db execute [options]
+```
+
+## What It Does
+
+- Connects to your database using the configured datasource
+- Executes a script provided via file (`--file`) or stdin (`--stdin`)
+- Useful for running raw SQL, maintenance tasks, or applying diffs from `migrate diff`
+- Not supported on MongoDB
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--file` | Path to a file containing the script to execute |
+| `--stdin` | Use terminal standard input as the script |
+| `--config` | Custom path to your Prisma config file |
+
+## Current Option Surface
+
+`prisma db execute` uses the datasource configured in `prisma.config.ts`. Use `--config` if you need a separate config file for another environment.
+
+## Examples
+
+### Execute from file
+
+```bash
+prisma db execute --file ./script.sql
+```
+
+### Execute from stdin
+
+```bash
+echo "TRUNCATE TABLE User;" | prisma db execute --stdin
+```
+
+### Execute `migrate diff` output
+
+Pipe the output of `migrate diff` directly to the database:
+
+```bash
+prisma migrate diff \
+ --from-empty \
+ --to-schema prisma/schema.prisma \
+ --script \
+| prisma db execute --stdin
+```
+
+## Configuration
+
+Uses `datasource` from `prisma.config.ts`:
+
+```typescript
+export default defineConfig({
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Use Cases
+
+- **Manual Migrations**: Applying raw SQL changes
+- **Data Maintenance**: Truncating tables, cleaning up data
+- **Schema Synchronization**: Applying `migrate diff` scripts
+- **Debugging**: Running test queries (though typically not for fetching data)
+
+## Limitations
+
+- **No Data Return**: The command reports success/failure, not query results (rows). Use Prisma Client or `prisma studio` to view data.
+- **SQL Only**: Primarily for SQL databases.
diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-pull.md b/apps/backend/.agents/skills/prisma-cli/references/db-pull.md
new file mode 100644
index 0000000..58a6e47
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/db-pull.md
@@ -0,0 +1,185 @@
+# prisma db pull
+
+Introspects an existing database and updates your Prisma schema to reflect its structure.
+
+## Command
+
+```bash
+prisma db pull [options]
+```
+
+## What It Does
+
+- Connects to your database
+- Reads the database schema (tables, columns, relations, indexes)
+- Updates `schema.prisma` with corresponding Prisma models
+- For MongoDB, samples data to infer schema
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--force` | Ignore current Prisma schema file |
+| `--print` | Print the introspected Prisma schema to stdout |
+| `--schema` | Custom path to your Prisma schema |
+| `--config` | Custom path to your Prisma config file |
+| `--url` | Override the datasource URL from the Prisma config file |
+| `--composite-type-depth` | Specify the depth for introspecting composite types (default: -1 for infinite, 0 = off) |
+| `--schemas` | Specify the database schemas to introspect |
+| `--local-d1` | Generate a Prisma schema from a local Cloudflare D1 database |
+
+## Examples
+
+### Basic introspection
+
+```bash
+prisma db pull
+```
+
+### Preview without writing
+
+```bash
+prisma db pull --print
+```
+
+Outputs schema to terminal for review.
+
+### Force overwrite
+
+```bash
+prisma db pull --force
+```
+
+Replaces schema file, losing any manual customizations.
+
+## Prerequisites
+
+Configure database connection in `prisma.config.ts`:
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Workflow
+
+### Starting from existing database
+
+1. Initialize Prisma:
+ ```bash
+ prisma init
+ ```
+
+2. Configure database URL
+
+3. Pull schema:
+ ```bash
+ prisma db pull
+ ```
+
+4. Review and customize generated schema
+
+5. Generate client:
+ ```bash
+ prisma generate
+ ```
+
+### Syncing changes from database
+
+When database changes are made outside Prisma:
+
+```bash
+prisma db pull
+prisma generate
+```
+
+## Generated Schema Example
+
+Database tables become Prisma models:
+
+```sql
+-- Database tables
+CREATE TABLE users (
+ id SERIAL PRIMARY KEY,
+ email VARCHAR(255) UNIQUE NOT NULL,
+ name VARCHAR(100)
+);
+
+CREATE TABLE posts (
+ id SERIAL PRIMARY KEY,
+ title VARCHAR(255) NOT NULL,
+ author_id INTEGER REFERENCES users(id)
+);
+```
+
+Becomes:
+
+```prisma
+model users {
+ id Int @id @default(autoincrement())
+ email String @unique @db.VarChar(255)
+ name String? @db.VarChar(100)
+ posts posts[]
+}
+
+model posts {
+ id Int @id @default(autoincrement())
+ title String @db.VarChar(255)
+ author_id Int?
+ users users? @relation(fields: [author_id], references: [id])
+}
+```
+
+## Post-Introspection Cleanup
+
+After `db pull`, consider:
+
+1. **Rename models** to PascalCase:
+ ```prisma
+ model User { // Was: users
+ @@map("users")
+ }
+ ```
+
+2. **Rename fields** to camelCase:
+ ```prisma
+ authorId Int? @map("author_id")
+ ```
+
+3. **Add relation names** for clarity:
+ ```prisma
+ author User? @relation("PostAuthor", fields: [authorId], references: [id])
+ ```
+
+4. **Add documentation**:
+ ```prisma
+ /// User account information
+ model User {
+ /// Primary email for authentication
+ email String @unique
+ }
+ ```
+
+## MongoDB Introspection
+
+For MongoDB, `db pull` samples documents to infer schema:
+
+```bash
+prisma db pull
+```
+
+May require manual refinement since MongoDB is schemaless.
+
+## Warning
+
+`db pull` overwrites your schema file. Always:
+- Commit current schema before pulling
+- Use `--print` to preview first
+- Backup customizations you want to keep
diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-push.md b/apps/backend/.agents/skills/prisma-cli/references/db-push.md
new file mode 100644
index 0000000..74da0cf
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/db-push.md
@@ -0,0 +1,150 @@
+# prisma db push
+
+Pushes schema changes directly to database without creating migrations. Ideal for prototyping.
+
+## Command
+
+```bash
+prisma db push [options]
+```
+
+## What It Does
+
+- Syncs your Prisma schema to the database
+- Creates database if it doesn't exist
+- Does NOT create migration files
+- Does NOT track migration history
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--force-reset` | Force a reset of the database before push |
+| `--accept-data-loss` | Ignore data loss warnings |
+| `--schema` | Custom path to your Prisma schema |
+| `--config` | Custom path to your Prisma config file |
+| `--url` | Override the datasource URL from the Prisma config file |
+
+When Prisma detects an AI agent, `--force-reset` and `--accept-data-loss` require explicit user consent. Follow `agent-safety.md`; never infer or fabricate the consent text.
+
+### Follow-up Command
+
+- Run `prisma generate` explicitly when you need refreshed client output
+
+## Examples
+
+### Basic push
+
+```bash
+prisma db push
+```
+
+### Accept data loss
+
+```bash
+prisma db push --accept-data-loss
+```
+
+Required when changes would delete data (dropping columns, etc.)
+
+### Force reset
+
+```bash
+prisma db push --force-reset
+```
+
+Completely resets database and applies schema.
+
+### Full workflow
+
+```bash
+prisma db push
+prisma generate
+```
+
+## When to Use
+
+- **Prototyping** - Rapid schema iteration
+- **Local development** - Quick schema changes
+- **MongoDB** - Primary workflow (migrations not supported)
+- **Testing** - Setting up test databases
+
+## When NOT to Use
+
+- **Production** - Use `migrate deploy`
+- **Team collaboration** - Use migrations for trackable changes
+- **When you need rollback** - Migrations provide history
+
+## Comparison with migrate dev
+
+| Feature | db push | migrate dev |
+|---------|---------|-------------|
+| Creates migration files | No | Yes |
+| Tracks history | No | Yes |
+| Requires shadow database | No | Yes |
+| Speed | Faster | Slower |
+| Rollback capability | No | Yes |
+| Best for | Prototyping | Development |
+
+## MongoDB Workflow
+
+MongoDB doesn't support migrations. Use `db push` exclusively:
+
+```bash
+# Schema changes for MongoDB
+prisma db push
+prisma generate
+```
+
+## Common Patterns
+
+### Prototyping workflow
+
+```bash
+# Make schema changes
+# ...
+
+# Push to database
+prisma db push
+
+# Generate client
+prisma generate
+
+# Test your changes
+# Repeat as needed
+```
+
+### Reset and start fresh
+
+```bash
+prisma db push --force-reset
+prisma db seed
+```
+
+### Handling conflicts
+
+If `db push` can't apply changes safely:
+
+```
+Error: The following changes cannot be applied:
+ - Removing field `email` would cause data loss
+
+Use --accept-data-loss to proceed
+```
+
+Decide whether data loss is acceptable, then:
+
+```bash
+prisma db push --accept-data-loss
+```
+
+## Transition to Migrations
+
+When ready for production, switch to migrations:
+
+```bash
+# Create baseline migration from current schema
+prisma migrate dev --name init
+```
+
+Then use `migrate dev` for future changes.
diff --git a/apps/backend/.agents/skills/prisma-cli/references/db-seed.md b/apps/backend/.agents/skills/prisma-cli/references/db-seed.md
new file mode 100644
index 0000000..7657cff
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/db-seed.md
@@ -0,0 +1,188 @@
+# prisma db seed
+
+Runs your database seed script to populate data.
+
+## Command
+
+```bash
+prisma db seed [options]
+```
+
+## What It Does
+
+- Executes your configured seed script
+- Populates database with initial/test data
+- Runs independently (not auto-run by migrations in v7)
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--config` | Custom path to your Prisma config file |
+| `--` | Pass custom arguments to seed script |
+
+## Configuration
+
+Configure seed script in `prisma.config.ts`:
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ migrations: {
+ path: 'prisma/migrations',
+ seed: 'tsx prisma/seed.ts', // Your seed command
+ },
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+### Common seed commands
+
+```typescript
+// TypeScript with tsx
+seed: 'tsx prisma/seed.ts'
+
+// TypeScript with ts-node
+seed: 'ts-node prisma/seed.ts'
+
+// JavaScript
+seed: 'node prisma/seed.js'
+```
+
+## Seed Script Example
+
+```typescript
+// prisma/seed.ts
+import { PrismaClient } from '../generated/client'
+
+const prisma = new PrismaClient()
+
+async function main() {
+ // Create users
+ const alice = await prisma.user.upsert({
+ where: { email: 'alice@prisma.io' },
+ update: {},
+ create: {
+ email: 'alice@prisma.io',
+ name: 'Alice',
+ posts: {
+ create: {
+ title: 'Hello World',
+ published: true,
+ },
+ },
+ },
+ })
+
+ const bob = await prisma.user.upsert({
+ where: { email: 'bob@prisma.io' },
+ update: {},
+ create: {
+ email: 'bob@prisma.io',
+ name: 'Bob',
+ },
+ })
+
+ console.log({ alice, bob })
+}
+
+main()
+ .then(async () => {
+ await prisma.$disconnect()
+ })
+ .catch(async (e) => {
+ console.error(e)
+ await prisma.$disconnect()
+ process.exit(1)
+ })
+```
+
+## Examples
+
+### Run seed
+
+```bash
+prisma db seed
+```
+
+### With custom arguments
+
+```bash
+prisma db seed -- --environment development
+```
+
+Arguments after `--` are passed to your seed script.
+
+## Current Workflow
+
+Run seeding explicitly after migrations when you need seed data:
+
+```bash
+prisma migrate dev --name init
+prisma generate
+prisma db seed # Must run explicitly
+```
+
+## Idempotent Seeding
+
+Use `upsert` to make seeds re-runnable:
+
+```typescript
+// Good: Can run multiple times
+await prisma.user.upsert({
+ where: { email: 'alice@prisma.io' },
+ update: {}, // Don't change existing
+ create: { email: 'alice@prisma.io', name: 'Alice' },
+})
+
+// Bad: Fails on second run
+await prisma.user.create({
+ data: { email: 'alice@prisma.io', name: 'Alice' },
+})
+```
+
+## Common Patterns
+
+### Development reset
+
+```bash
+prisma migrate reset --force
+prisma db seed
+```
+
+### Conditional seeding
+
+```typescript
+// prisma/seed.ts
+const count = await prisma.user.count()
+if (count === 0) {
+ // Only seed if empty
+ await seedUsers()
+}
+```
+
+### Environment-specific seeds
+
+```typescript
+// prisma/seed.ts
+const env = process.env.NODE_ENV || 'development'
+
+if (env === 'development') {
+ await seedDevData()
+} else if (env === 'test') {
+ await seedTestData()
+}
+```
+
+## Best Practices
+
+1. Use `upsert` for idempotent seeds
+2. Keep seeds focused and minimal
+3. Use realistic but fake data
+4. Document required seed data
+5. Version control your seed scripts
diff --git a/apps/backend/.agents/skills/prisma-cli/references/debug.md b/apps/backend/.agents/skills/prisma-cli/references/debug.md
new file mode 100644
index 0000000..1c2b0af
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/debug.md
@@ -0,0 +1,46 @@
+# prisma debug
+
+Prints information helpful for debugging and bug reports.
+
+## Command
+
+```bash
+prisma debug [options]
+```
+
+## What It Does
+
+Outputs details about your Prisma environment, including:
+- Prisma CLI version
+- Prisma Client version (if installed)
+- Engine binaries (Query Engine, Migration Engine, etc.)
+- Platform information (OS, Architecture)
+- Node.js version
+- Configured datasource provider
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--schema` | Path to schema file |
+| `--config` | Custom path to your Prisma config file |
+
+## Example Output
+
+```
+prisma : 7.3.0
+@prisma/client : 7.3.0
+Operating System : darwin
+Architecture : arm64
+Node.js : v20.10.0
+TypeScript : 5.3.3
+Query Compiler : enabled
+PSL : ...
+Schema Engine : ...
+```
+
+## When to Use
+
+- **Troubleshooting**: Checking version mismatches
+- **Reporting Issues**: Including environment info in GitHub issues
+- **Verifying Installation**: Ensuring correct binaries are downloaded
diff --git a/apps/backend/.agents/skills/prisma-cli/references/dev.md b/apps/backend/.agents/skills/prisma-cli/references/dev.md
new file mode 100644
index 0000000..870efb9
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/dev.md
@@ -0,0 +1,157 @@
+# prisma dev
+
+Starts a local Prisma Postgres database for development. Provides a PostgreSQL-compatible database that runs entirely on your machine.
+
+## Command
+
+```bash
+prisma dev [options]
+```
+
+## What It Does
+
+- Starts a local PostgreSQL-compatible database
+- Runs in your terminal or as a background process
+- Perfect for development and testing
+- Easy migration to Prisma Postgres cloud in production
+
+## Options
+
+| Option | Description | Default |
+|--------|-------------|---------|
+| `--name` / `-n` | Name for the database instance | `default` |
+| `--port` / `-p` | HTTP server port | `51213` |
+| `--db-port` / `-P` | Database server port | `51214` |
+| `--shadow-db-port` | Shadow database port (for migrations) | `51215` |
+| `--detach` / `-d` | Run in background | `false` |
+| `--debug` | Enable debug logging | `false` |
+
+## Examples
+
+### Start local database
+
+```bash
+prisma dev
+```
+
+Interactive mode with keyboard shortcuts:
+- `q` - Quit
+- `h` - Show HTTP URL
+- `t` - Show TCP URLs
+
+### Named instance
+
+```bash
+prisma dev --name myproject
+```
+
+Useful for multiple projects.
+
+### Background mode
+
+```bash
+prisma dev --detach
+```
+
+Frees your terminal for other commands.
+
+### Custom ports
+
+```bash
+prisma dev --port 5000 --db-port 5432
+```
+
+## Instance Management
+
+### List all instances
+
+```bash
+prisma dev ls
+```
+
+Shows all local Prisma Postgres instances with status.
+
+### Start existing instance
+
+```bash
+prisma dev start myproject
+```
+
+Starts a previously created instance in background.
+
+### Stop instance
+
+```bash
+prisma dev stop myproject
+```
+
+### Stop with glob pattern
+
+```bash
+prisma dev stop "myproject*"
+```
+
+Stops all instances matching pattern.
+
+### Remove instance
+
+```bash
+prisma dev rm myproject
+```
+
+Removes instance data from filesystem.
+
+### Force remove (stops first)
+
+```bash
+prisma dev rm myproject --force
+```
+
+## Configuration
+
+Configure your `prisma.config.ts` to use local Prisma Postgres:
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ migrations: {
+ path: 'prisma/migrations',
+ },
+ datasource: {
+ // Local Prisma Postgres URL (from prisma dev output)
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Workflow
+
+1. Start local database:
+ ```bash
+ prisma dev
+ ```
+
+2. In another terminal, run migrations:
+ ```bash
+ prisma migrate dev
+ ```
+
+3. Generate client:
+ ```bash
+ prisma generate
+ ```
+
+4. Run your application
+
+## Production Migration
+
+When ready for production, switch to Prisma Postgres cloud:
+
+```bash
+prisma init --db
+```
+
+Update your `DATABASE_URL` to the cloud connection string.
diff --git a/apps/backend/.agents/skills/prisma-cli/references/format.md b/apps/backend/.agents/skills/prisma-cli/references/format.md
new file mode 100644
index 0000000..896b1ec
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/format.md
@@ -0,0 +1,48 @@
+# prisma format
+
+Formats your Prisma schema file.
+
+## Command
+
+```bash
+prisma format [options]
+```
+
+## What It Does
+
+- Fixes formatting (indentation, spacing)
+- Adds missing back-relations (e.g., adds the other side of a relation)
+- Adds missing relation arguments (e.g., `fields`, `references`)
+- Sorts fields and attributes (opinionated)
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--schema` | Path to schema file |
+| `--config` | Custom path to your Prisma config file |
+
+## Examples
+
+### Format default schema
+
+```bash
+prisma format
+```
+
+### Format specific schema
+
+```bash
+prisma format --schema=./custom/schema.prisma
+```
+
+## Behavior
+
+`prisma format` modifies the file in place. It is equivalent to "Prettier for Prisma schemas" but also has semantic understanding to fix/add missing schema definitions.
+
+## Use in Editor
+
+Most Prisma editor extensions (VS Code, WebStorm) run `prisma format` automatically on save. This command is useful for:
+- CI pipelines (check formatting)
+- CLI-based workflows
+- Fixing large schema refactors
diff --git a/apps/backend/.agents/skills/prisma-cli/references/generate.md b/apps/backend/.agents/skills/prisma-cli/references/generate.md
new file mode 100644
index 0000000..3d371cf
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/generate.md
@@ -0,0 +1,173 @@
+# prisma generate
+
+Generates assets based on the generator blocks in your Prisma schema, most commonly Prisma Client.
+
+## Command
+
+```bash
+prisma generate [options]
+```
+
+## Bun Runtime
+
+If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js:
+
+```bash
+bunx --bun prisma generate
+```
+
+## What It Does
+
+1. Reads your `schema.prisma` file
+2. Generates a customized Prisma Client based on your models
+3. Outputs to the directory specified in the generator block
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--schema` | Custom path to your Prisma schema |
+| `--config` | Custom path to your Prisma config file |
+| `--sql` | Generate typed sql module |
+| `--watch` | Watch the Prisma schema and rerun after a change |
+| `--generator` | Generator to use (may be provided multiple times) |
+| `--no-hints` | Hides the hint messages but still outputs errors and warnings |
+| `--require-models` | Do not allow generating a client without models |
+
+## Examples
+
+### Basic generation
+
+```bash
+prisma generate
+```
+
+### Watch mode (development)
+
+```bash
+prisma generate --watch
+```
+
+Auto-regenerates when `schema.prisma` changes.
+
+### Specific generator
+
+```bash
+prisma generate --generator client
+```
+
+### Multiple generators
+
+```bash
+prisma generate --generator client --generator zod_schemas
+```
+
+### Typed SQL generation
+
+```bash
+prisma generate --sql
+```
+
+## Schema Configuration
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+### Current Generator Behavior
+
+- `prisma-client` is the standard generator
+- `output` is required when using `prisma-client`
+- `prisma-client` supports both ESM and CommonJS via `moduleFormat`
+- `compilerBuild` supports `fast` and `small` query compiler artifacts
+- Use TypeScript `satisfies` for typed query fragments with `prisma-client`
+- Import Prisma Client from your generated output path, for example:
+
+```typescript
+import { PrismaClient } from '../generated/prisma/client'
+```
+
+### Compiler Build Tuning
+
+Use `compilerBuild` when you need to trade artifact size against the default build:
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+ compilerBuild = "small"
+}
+```
+
+- `fast` is the default build for most targets
+- `small` is useful for size-constrained targets
+- Prisma defaults `vercel-edge` targets to `small`
+
+## Common Patterns
+
+### After schema changes
+
+```bash
+prisma migrate dev --name my_migration
+prisma generate
+```
+
+Run `prisma generate` whenever you need refreshed client code after schema-changing commands.
+
+### CI/CD pipeline
+
+```bash
+prisma generate
+```
+
+Run before building your application.
+
+### Multiple generators
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+
+generator zod {
+ provider = "zod-prisma-types"
+ output = "../generated/zod"
+}
+```
+
+```bash
+prisma generate # Runs all generators
+```
+
+## Output Structure
+
+After running `prisma generate`, your output directory contains:
+
+```
+generated/
+├── browser.ts
+├── client.ts
+├── commonInputTypes.ts
+├── models/
+├── enums.ts
+├── models.ts
+└── ...
+```
+
+Import the client:
+
+```typescript
+import { PrismaClient, Prisma } from '../generated/prisma/client'
+```
+
+Import browser-safe types:
+
+```typescript
+import { Prisma } from '../generated/prisma/browser'
+import { Role } from '../generated/prisma/enums'
+import type { UserModel } from '../generated/prisma/models/User'
+```
diff --git a/apps/backend/.agents/skills/prisma-cli/references/init.md b/apps/backend/.agents/skills/prisma-cli/references/init.md
new file mode 100644
index 0000000..c4390ed
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/init.md
@@ -0,0 +1,139 @@
+# prisma init
+
+Bootstraps a fresh Prisma ORM project in the current directory.
+
+## Command
+
+```bash
+prisma init [options]
+```
+
+## Bun Runtime
+
+If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js:
+
+```bash
+bunx --bun prisma init
+```
+
+## What It Creates
+
+- `prisma/schema.prisma` - Your Prisma schema file
+- `prisma.config.ts` - TypeScript configuration for Prisma CLI
+- `.env` - Environment variables (DATABASE_URL)
+- `.gitignore` - Ensures `.env` is ignored and appends the generated client path
+
+## Options
+
+| Option | Description | Default |
+|--------|-------------|---------|
+| `--datasource-provider` | Database provider: `postgresql`, `mysql`, `sqlite`, `sqlserver`, `mongodb`, `cockroachdb` | `postgresql` |
+| `--db` | Provisions a fully managed Prisma Postgres database on the Prisma Data Platform | - |
+| `--url` | Define a custom datasource url | - |
+| `--generator-provider` | Define the generator provider to use | `prisma-client` |
+| `--output` | Define Prisma Client generator output path to use | - |
+| `--preview-feature` | Define a preview feature to use | - |
+| `--with-model` | Add example model to created schema file | - |
+| `--no-skills` | Skip the best-effort installation of Prisma agent skills | - |
+
+`prisma init` attempts to install `prisma/skills` for detected agents. This is best-effort and does not make project initialization fail. Use `--no-skills` in minimal or controlled environments.
+
+## Examples
+
+### Basic initialization
+
+```bash
+prisma init
+```
+
+Creates a PostgreSQL project setup.
+
+### SQLite project
+
+```bash
+prisma init --datasource-provider sqlite
+```
+
+### MySQL with custom URL
+
+```bash
+prisma init --datasource-provider mysql --url "mysql://user:password@localhost:3306/mydb"
+```
+
+### Prisma Postgres (cloud)
+
+```bash
+prisma init --db
+```
+
+Opens browser for authentication, creates cloud database instance.
+
+### Add an example model
+
+```bash
+prisma init --with-model
+```
+
+Adds a starter model to the generated schema.
+
+### With preview features
+
+```bash
+prisma init --preview-feature relationJoins --preview-feature fullTextSearch
+```
+
+## Generated Schema
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+}
+
+datasource db {
+ provider = "postgresql"
+}
+```
+
+## Generated Config (Node.js default)
+
+```typescript
+// prisma.config.ts
+import "dotenv/config";
+import { defineConfig } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ migrations: {
+ path: 'prisma/migrations',
+ },
+ datasource: {
+ url: process.env['DATABASE_URL'],
+ },
+})
+```
+
+## Generated Config (Bun)
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ migrations: {
+ path: 'prisma/migrations',
+ },
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Next Steps After Init
+
+1. Configure `DATABASE_URL` in `.env` (and let `prisma.config.ts` read it)
+2. Define your models in `prisma/schema.prisma`
+3. Run `prisma dev` for local development or connect to remote DB
+4. Run `prisma migrate dev` to create migrations
+5. Run `prisma generate` to generate Prisma Client
+6. Run `prisma db seed` explicitly if you want seed data
diff --git a/apps/backend/.agents/skills/prisma-cli/references/mcp.md b/apps/backend/.agents/skills/prisma-cli/references/mcp.md
new file mode 100644
index 0000000..284130f
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/mcp.md
@@ -0,0 +1,39 @@
+# prisma mcp
+
+Starts Prisma's MCP server for AI development tools.
+
+## Command
+
+```bash
+prisma mcp
+```
+
+## What It Does
+
+- Starts a Model Context Protocol (MCP) server for your Prisma project
+- Exposes Prisma schema and database context to compatible AI tools
+- Helps AI assistants understand models, generate queries, and suggest migrations
+
+## Usage
+
+```bash
+prisma mcp
+```
+
+## Typical Use Cases
+
+- Connect Prisma to ChatGPT, Claude, or other MCP-aware tools
+- Give an AI assistant access to your Prisma schema structure
+- Help an agent propose queries, schema updates, and migration steps with project context
+
+## Notes
+
+- Run this from the project that contains your Prisma schema and `prisma.config.ts`
+- The command is separate from Prisma Studio and does not open a browser UI
+- The MCP server exposes `migrate-status`, `migrate-dev`, and Prisma Studio tooling. It does not expose the destructive `migrate-reset` tool; do not claim it is available or try to bypass that safety boundary.
+- For destructive shell commands, follow `agent-safety.md` and obtain explicit user consent.
+
+## References
+
+- [Prisma CLI `mcp` command](https://docs.prisma.io/docs/cli/mcp)
+- [Prisma MCP Server](https://www.prisma.io/docs/ai/tools/chatgpt)
diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-deploy.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-deploy.md
new file mode 100644
index 0000000..2132075
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-deploy.md
@@ -0,0 +1,127 @@
+# prisma migrate deploy
+
+Applies pending migrations in production/staging environments.
+
+## Command
+
+```bash
+prisma migrate deploy
+```
+
+## What It Does
+
+- Applies all pending migrations from `prisma/migrations/`
+- Updates `_prisma_migrations` table
+- Does NOT generate new migrations
+- Does NOT run seed scripts
+- Safe for CI/CD and production
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--schema` | Custom path to your Prisma schema |
+| `--config` | Custom path to your Prisma config file |
+
+## When to Use
+
+- Production deployments
+- Staging environments
+- CI/CD pipelines
+- Any non-development environment
+
+## Examples
+
+### Basic deployment
+
+```bash
+prisma migrate deploy
+```
+
+### In CI/CD pipeline
+
+```yaml
+# GitHub Actions example
+- name: Apply migrations
+ run: npx prisma migrate deploy
+ env:
+ DATABASE_URL: ${{ secrets.DATABASE_URL }}
+```
+
+### Docker deployment
+
+```dockerfile
+# Run migrations before starting app
+CMD npx prisma migrate deploy && node dist/index.js
+```
+
+## Comparison with migrate dev
+
+| Feature | migrate dev | migrate deploy |
+|---------|-------------|----------------|
+| Creates migrations | Yes | No |
+| Applies migrations | Yes | Yes |
+| Detects drift | Yes | No |
+| Prompts for input | Yes | No |
+| Uses shadow database | Yes | No |
+| Safe for production | No | Yes |
+| Resets on issues | Prompts | Fails |
+
+## Production Workflow
+
+1. **Development**: Create migrations locally
+ ```bash
+ prisma migrate dev --name add_feature
+ ```
+
+2. **Commit**: Include migration files in version control
+ ```bash
+ git add prisma/migrations
+ git commit -m "Add feature migration"
+ ```
+
+3. **Deploy**: Apply in production
+ ```bash
+ prisma migrate deploy
+ ```
+
+## Error Handling
+
+### Failed migration
+
+If a migration fails, `migrate deploy` exits with error. The failed migration is marked as failed in `_prisma_migrations`.
+
+To fix:
+1. Resolve the issue (fix SQL, database state, etc.)
+2. Mark as resolved: `prisma migrate resolve --applied `
+3. Re-run: `prisma migrate deploy`
+
+### Check status first
+
+```bash
+prisma migrate status
+```
+
+Shows pending and applied migrations before deploying.
+
+## Configuration
+
+Ensure `prisma.config.ts` has the production database URL:
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Best Practices
+
+1. Always run `migrate status` before `migrate deploy` in CI
+2. Have a rollback plan (backup before migrations)
+3. Test migrations in staging first
+4. Never use `migrate dev` in production
diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md
new file mode 100644
index 0000000..48643b6
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-dev.md
@@ -0,0 +1,145 @@
+# prisma migrate dev
+
+Creates and applies migrations during development. Requires a shadow database.
+
+## Command
+
+```bash
+prisma migrate dev [options]
+```
+
+## What It Does
+
+1. Runs existing migrations in shadow database to detect drift
+2. Applies any pending migrations
+3. Generates new migration from schema changes
+4. Applies new migration to development database
+5. Updates `_prisma_migrations` table
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--name` / `-n` | Name the migration |
+| `--create-only` | Create a new migration but do not apply it |
+| `--schema` | Custom path to your Prisma schema |
+| `--config` | Custom path to your Prisma config file |
+| `--url` | Override the datasource URL from the Prisma config file |
+
+### Follow-up Commands
+
+- Run `prisma generate` explicitly when you need refreshed client output
+- Run `prisma db seed` explicitly when you need seed data
+
+Run `prisma generate` as an explicit follow-up when you need refreshed generated artifacts. Do not rely on historical CLI help that described generators as part of `migrate dev`.
+
+## Examples
+
+### Create and apply migration
+
+```bash
+prisma migrate dev
+```
+
+Prompts for migration name if schema changed.
+
+### Named migration
+
+```bash
+prisma migrate dev --name add_users_table
+```
+
+### Create without applying
+
+```bash
+prisma migrate dev --create-only
+```
+
+Useful for reviewing migration SQL before applying.
+
+### Full workflow
+
+```bash
+prisma migrate dev --name my_migration
+prisma generate
+prisma db seed
+```
+
+## Migration Files
+
+Created in `prisma/migrations/`:
+
+```
+prisma/migrations/
+├── 20240115120000_add_users_table/
+│ └── migration.sql
+├── 20240116090000_add_posts/
+│ └── migration.sql
+└── migration_lock.toml
+```
+
+## Schema Drift Detection
+
+If `migrate dev` detects drift (manual database changes or edited migrations), it prompts to reset:
+
+```
+Drift detected: Your database schema is not in sync.
+
+Do you want to reset your database? All data will be lost.
+```
+
+## When to Use
+
+- Local development
+- Adding new models/fields
+- Changing relations
+- Creating indexes
+
+## When NOT to Use
+
+- Production deployments (use `migrate deploy`)
+- CI/CD pipelines (use `migrate deploy`)
+- MongoDB (use `db push` instead)
+
+## Common Patterns
+
+### After schema changes
+
+```prisma
+// schema.prisma - Add new field
+model User {
+ id Int @id @default(autoincrement())
+ email String @unique
+ name String?
+ createdAt DateTime @default(now()) // New field
+}
+```
+
+```bash
+prisma migrate dev --name add_created_at
+```
+
+### Handling data loss warnings
+
+When a migration would cause data loss:
+
+```bash
+prisma migrate dev --name remove_field
+# Warning: You are about to delete data...
+# Accept with: --accept-data-loss
+```
+
+## Shadow Database
+
+`migrate dev` requires a shadow database for drift detection. Configure in `prisma.config.ts`:
+
+```typescript
+export default defineConfig({
+ datasource: {
+ url: env('DATABASE_URL'),
+ shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
+ },
+})
+```
+
+For local Prisma Postgres (`prisma dev`), shadow database is handled automatically.
diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-diff.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-diff.md
new file mode 100644
index 0000000..873107e
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-diff.md
@@ -0,0 +1,89 @@
+# prisma migrate diff
+
+Compares database schemas and generates diffs (SQL or summary).
+
+## Command
+
+```bash
+prisma migrate diff [options]
+```
+
+## What It Does
+
+- Compares two sources (`--from-...` and `--to-...`)
+- Sources can be:
+ - Empty (`empty`)
+ - Schema file (`schema`)
+ - Migrations directory (`migrations`)
+ - Database URL (`url`) or Configured Datasource (`config-datasource`)
+- Outputs the difference:
+ - Human-readable summary (default)
+ - SQL script (`--script`)
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--script` | Render SQL script to stdout |
+| `--exit-code` | Exit 2 if changes detected, 0 if empty, 1 if error |
+| `--config` | Custom path to your Prisma config file |
+
+### Sources (Must provide one `from` and one `to`)
+
+- `--from-empty`, `--to-empty`
+- `--from-schema `, `--to-schema `
+- `--from-migrations `, `--to-migrations `
+- `--from-url `, `--to-url `
+- `--from-config-datasource`, `--to-config-datasource` (uses `prisma.config.ts`)
+
+## Examples
+
+### Generate SQL for a schema change
+
+Compare current production DB to your local schema:
+
+```bash
+prisma migrate diff \
+ --from-url "$PROD_DB_URL" \
+ --to-schema ./prisma/schema.prisma \
+ --script
+```
+
+### Review pending migrations
+
+Compare database state to migrations directory:
+
+```bash
+prisma migrate diff \
+ --from-config-datasource \
+ --to-migrations ./prisma/migrations
+```
+
+### Create baseline migration
+
+Compare empty state to current schema:
+
+```bash
+prisma migrate diff \
+ --from-empty \
+ --to-schema ./prisma/schema.prisma \
+ --script > prisma/migrations/0_init/migration.sql
+```
+
+### Check for drift (CI)
+
+Check if database matches schema:
+
+```bash
+prisma migrate diff \
+ --from-config-datasource \
+ --to-schema ./prisma/schema.prisma \
+ --exit-code
+```
+
+## Use Cases
+
+- **Forward-generating migrations**: Creating SQL without `migrate dev`.
+- **Drift detection**: Checking if DB is in sync.
+- **Baselining**: Creating initial migration from existing DB.
+- **Debugging**: Understanding what `migrate dev` would do.
diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-reset.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-reset.md
new file mode 100644
index 0000000..900e288
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-reset.md
@@ -0,0 +1,80 @@
+# prisma migrate reset
+
+Resets your database and re-applies all migrations.
+
+## Command
+
+```bash
+prisma migrate reset [options]
+```
+
+## What It Does
+
+1. **Drops** the database (if possible) or deletes all data/tables
+2. **Re-creates** the database
+3. **Applies** all migrations from `prisma/migrations/`
+4. Stops there - run seed and generate explicitly if needed
+
+**Warning: All data will be lost.**
+
+When Prisma detects an AI agent, this command is blocked until the user gives explicit consent. Follow `agent-safety.md`; `--force` skips the ordinary prompt but does not constitute user consent for an agent.
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--force` / `-f` | Skip confirmation prompt |
+| `--schema` | Path to schema file |
+| `--config` | Custom path to your Prisma config file |
+
+## Examples
+
+### Basic reset
+
+```bash
+prisma migrate reset
+```
+
+Prompts for confirmation in interactive terminals.
+
+### Force reset (CI/Automation)
+
+```bash
+prisma migrate reset --force
+```
+
+### With custom schema
+
+```bash
+prisma migrate reset --schema=./custom/schema.prisma
+```
+
+## When to Use
+
+- **Development**: When you want a fresh start
+- **Testing**: Resetting test database before suites
+- **Drift Recovery**: When the database is out of sync and you can't migrate
+
+## Follow-up Steps
+
+Run `prisma generate` and `prisma db seed` explicitly when you need refreshed client output or seed data after a reset.
+
+## Configuration
+
+Configure the seed script in `prisma.config.ts`, then run it explicitly after reset:
+
+```typescript
+export default defineConfig({
+ migrations: {
+ seed: 'tsx prisma/seed.ts',
+ },
+})
+```
+
+Typical workflow:
+
+```bash
+prisma migrate reset --force
+prisma generate
+prisma db seed
+```
diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-resolve.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-resolve.md
new file mode 100644
index 0000000..6b65f65
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-resolve.md
@@ -0,0 +1,57 @@
+# prisma migrate resolve
+
+Resolves issues with database migrations, such as failed migrations or baselining.
+
+## Command
+
+```bash
+prisma migrate resolve [options]
+```
+
+## What It Does
+
+Updates the `_prisma_migrations` table to manually change the state of a migration. This is a recovery tool.
+
+## Options
+
+You must provide exactly one of `--applied` or `--rolled-back`.
+
+| Option | Description |
+|--------|-------------|
+| `--applied ` | Mark a migration as **applied** (success) |
+| `--rolled-back ` | Mark a migration as **rolled back** (ignored/failed) |
+| `--schema` | Path to schema file |
+| `--config` | Custom path to your Prisma config file |
+
+## Examples
+
+### Mark as Applied (Baselining)
+
+If you have existing tables and want to initialize migrations without running the SQL:
+
+```bash
+prisma migrate resolve --applied 20240101000000_initial_migration
+```
+
+This tells Prisma "Assume this migration has already run".
+
+### Mark as Rolled Back (Fixing Failures)
+
+If a migration failed (e.g., syntax error) and you fixed the SQL or want to retry:
+
+```bash
+prisma migrate resolve --rolled-back 20240115120000_failed_migration
+```
+
+This tells Prisma "Forget this migration run, let me try applying it again".
+
+## Use Cases
+
+1. **Baselining**: Adopting Prisma Migrate on an existing production database.
+2. **Failed Migrations**: Recovering from a failed `migrate deploy` in production.
+3. **Hotfixes**: reconciling manual database changes (rare).
+
+## References
+
+- [Baselining](https://www.prisma.io/docs/guides/database/developing-with-prisma-migrate/baselining)
+- [Troubleshooting](https://www.prisma.io/docs/guides/database/production-troubleshooting)
diff --git a/apps/backend/.agents/skills/prisma-cli/references/migrate-status.md b/apps/backend/.agents/skills/prisma-cli/references/migrate-status.md
new file mode 100644
index 0000000..80a7ffa
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/migrate-status.md
@@ -0,0 +1,65 @@
+# prisma migrate status
+
+Checks the status of your database migrations.
+
+## Command
+
+```bash
+prisma migrate status [options]
+```
+
+## What It Does
+
+- Connects to the database
+- Checks the `_prisma_migrations` table
+- Compares applied migrations with local migration files
+- Reports:
+ - **Status**: Database is up-to-date or behind
+ - **Unapplied migrations**: Count of pending migrations
+ - **Missing migrations**: Migrations present in DB but missing locally
+ - **Failed migrations**: Any migrations that failed to apply
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--schema` | Path to schema file |
+| `--config` | Custom path to your Prisma config file |
+
+## Examples
+
+### Check status
+
+```bash
+prisma migrate status
+```
+
+Output example (Up to date):
+```
+Database schema is up to date!
+```
+
+Output example (Pending):
+```
+Following migration have not yet been applied:
+ 20240115120000_add_user
+
+To apply migrations in development, run:
+ prisma migrate dev
+
+To apply migrations in production, run:
+ prisma migrate deploy
+```
+
+## When to Use
+
+- **Debugging**: Why is `migrate dev` complaining about drift?
+- **CI/CD**: Verify database state before deploying
+- **Production**: Check if migrations are needed (`migrate deploy`) or if a deployment failed
+
+## Exit Codes
+
+- `0`: Success (may have pending migrations, but command ran successfully)
+- `1`: Error
+
+To check for pending migrations programmatically, you might need to parse the output or use `migrate diff` with exit code flags.
diff --git a/apps/backend/.agents/skills/prisma-cli/references/studio.md b/apps/backend/.agents/skills/prisma-cli/references/studio.md
new file mode 100644
index 0000000..ba71c9d
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/studio.md
@@ -0,0 +1,137 @@
+# prisma studio
+
+Opens a visual database browser for viewing and editing data.
+
+## Command
+
+```bash
+prisma studio [options]
+```
+
+## What It Does
+
+- Starts a web-based database GUI
+- View all your models and records
+- Create, update, and delete records
+- Filter and sort data
+- Navigate relations
+
+## Options
+
+| Option | Description | Default |
+|--------|-------------|---------|
+| `--port` / `-p` | Port to start Studio on | `5555` |
+| `--browser` / `-b` | Browser to open Studio in | System default |
+| `--config` | Custom path to your Prisma config file | - |
+| `--url` | Database connection string (overrides the one in your Prisma config) | - |
+
+## Examples
+
+### Open Studio
+
+```bash
+prisma studio
+```
+
+Opens at http://localhost:5555
+
+### Custom port
+
+```bash
+prisma studio --port 3000
+```
+
+### Specific browser
+
+```bash
+prisma studio --browser firefox
+```
+
+### Don't open browser
+
+```bash
+BROWSER=none prisma studio
+```
+
+Useful for remote servers.
+
+## Features
+
+### View Records
+
+- See all records in table format
+- Pagination for large datasets
+- Column sorting
+
+### Filter Data
+
+- Filter by any field
+- Multiple conditions
+- Relation filtering
+
+### Edit Records
+
+- Click to edit inline
+- Add new records
+- Delete records (with confirmation)
+
+### Navigate Relations
+
+- Click relations to view related records
+- See counts of related items
+- Follow relation links
+
+## Recent Studio Capabilities
+
+Recent Prisma Studio releases added richer editor workflows:
+
+- multi-cell selection and editing
+- full-table search and more intuitive filtering
+- command palette shortcuts
+- dark mode
+- copy selections as Markdown
+- back-relation navigation
+- SQL workflows including raw SQL queries
+
+Some recent builds also expose AI-assisted SQL authoring. Treat these as interactive Studio features rather than a replacement for checked-in migrations or application queries.
+
+## Use Cases
+
+- **Development**: Quick data inspection
+- **Debugging**: Check data state
+- **Testing**: Verify seed data
+- **Demo**: Show data to stakeholders
+
+## Limitations
+
+- Development tool only
+- Not for production use
+- Limited to configured database
+- Prisma Studio in Prisma 7 currently targets PostgreSQL, MySQL, and SQLite first
+- For reproducible application logic, prefer Prisma Client and checked-in SQL scripts
+
+## Common Workflow
+
+1. Run migrations:
+ ```bash
+ prisma migrate dev
+ ```
+
+2. Seed data:
+ ```bash
+ prisma db seed
+ ```
+
+3. Open Studio to verify:
+ ```bash
+ prisma studio
+ ```
+
+4. Make manual edits if needed
+
+## Security Note
+
+Studio provides direct database access. Only run on:
+- Local development machines
+- Secure internal networks
+- Never expose publicly
diff --git a/apps/backend/.agents/skills/prisma-cli/references/validate.md b/apps/backend/.agents/skills/prisma-cli/references/validate.md
new file mode 100644
index 0000000..61156c6
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-cli/references/validate.md
@@ -0,0 +1,53 @@
+# prisma validate
+
+Validates your Prisma schema file.
+
+## Command
+
+```bash
+prisma validate [options]
+```
+
+## What It Does
+
+- Parses the `schema.prisma` file
+- Checks for syntax errors
+- Validates model definitions, relations, and types
+- Reports any errors or warnings without generating code
+
+## Options
+
+| Option | Description |
+|--------|-------------|
+| `--schema` | Path to schema file |
+| `--config` | Custom path to your Prisma config file |
+
+## Examples
+
+### Validate default schema
+
+```bash
+prisma validate
+```
+
+### Validate specific schema
+
+```bash
+prisma validate --schema=./custom/schema.prisma
+```
+
+### Use in CI
+
+Run `validate` in your CI pipeline to catch schema errors early:
+
+```yaml
+- name: Validate Schema
+ run: npx prisma validate
+```
+
+## Common Errors
+
+- Missing `@relation` fields
+- Invalid types
+- Duplicate model names
+- Syntax errors (missing braces, etc.)
diff --git a/apps/backend/.agents/skills/prisma-client-api/SKILL.md b/apps/backend/.agents/skills/prisma-client-api/SKILL.md
new file mode 100644
index 0000000..57aa8a5
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/SKILL.md
@@ -0,0 +1,216 @@
+---
+name: prisma-client-api
+description: Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
+license: MIT
+metadata:
+ author: prisma
+ version: "7.9.1"
+---
+
+# Prisma Client API Reference
+
+Complete API reference for Prisma Client. This skill provides guidance on model queries, filtering, relations, and client methods for current Prisma projects.
+
+## When to Apply
+
+Reference this skill when:
+- Writing database queries with Prisma Client
+- Performing CRUD operations (create, read, update, delete)
+- Filtering and sorting data
+- Working with relations
+- Using transactions
+- Configuring client options
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Client Construction | HIGH | `constructor` |
+| 2 | Model Queries | CRITICAL | `model-queries` |
+| 3 | Query Shape | HIGH | `query-options` |
+| 4 | Filtering | HIGH | `filters` |
+| 5 | Relations | HIGH | `relations` |
+| 6 | Transactions | CRITICAL | `transactions` |
+| 7 | Raw SQL | CRITICAL | `raw-queries` |
+| 8 | Client Methods | MEDIUM | `client-methods` |
+
+## Quick Reference
+
+- `constructor` - `PrismaClient` setup, adapter wiring, logging, and SQL commenter plugins
+- `model-queries` - CRUD operations and bulk operations
+- `query-options` - `select`, `include`, `omit`, sort, pagination
+- `filters` - scalar and logical filter operators
+- `relations` - relation reads and nested writes
+- `transactions` - array and interactive transaction patterns
+- `raw-queries` - `$queryRaw` and `$executeRaw` safety
+- `client-methods` - lifecycle methods, extensions, and `satisfies` patterns for `prisma-client`
+
+## Client Instantiation
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+## Model Query Methods
+
+| Method | Description |
+|--------|-------------|
+| `findUnique()` | Find one record by unique field |
+| `findUniqueOrThrow()` | Find one or throw error |
+| `findFirst()` | Find first matching record |
+| `findFirstOrThrow()` | Find first or throw error |
+| `findMany()` | Find multiple records |
+| `create()` | Create a new record |
+| `createMany()` | Create multiple records |
+| `createManyAndReturn()` | Create multiple and return them |
+| `update()` | Update one record |
+| `updateMany()` | Update multiple records |
+| `updateManyAndReturn()` | Update multiple and return them |
+| `upsert()` | Update or create record |
+| `delete()` | Delete one record |
+| `deleteMany()` | Delete multiple records |
+| `count()` | Count matching records |
+| `aggregate()` | Aggregate values (sum, avg, etc.) |
+| `groupBy()` | Group and aggregate |
+
+## Query Options
+
+| Option | Description |
+|--------|-------------|
+| `where` | Filter conditions |
+| `select` | Fields to include |
+| `include` | Relations to load |
+| `omit` | Fields to exclude |
+| `orderBy` | Sort order |
+| `take` | Limit results |
+| `skip` | Skip results (pagination) |
+| `cursor` | Cursor-based pagination |
+| `distinct` | Unique values only |
+
+## Client Methods
+
+| Method | Description |
+|--------|-------------|
+| `$connect()` | Explicitly connect to database |
+| `$disconnect()` | Disconnect from database |
+| `$transaction()` | Execute transaction |
+| `$queryRaw()` | Execute raw SQL query |
+| `$executeRaw()` | Execute raw SQL command |
+| `$on()` | Subscribe to events |
+| `$extends()` | Add extensions |
+
+## Quick Examples
+
+### Find records
+
+```typescript
+// Find by unique field
+const user = await prisma.user.findUnique({
+ where: { email: 'alice@prisma.io' }
+})
+
+// Find with filter
+const users = await prisma.user.findMany({
+ where: { role: 'ADMIN' },
+ orderBy: { createdAt: 'desc' },
+ take: 10
+})
+```
+
+### Create records
+
+```typescript
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ name: 'Alice',
+ posts: {
+ create: { title: 'Hello World' }
+ }
+ },
+ include: { posts: true }
+})
+```
+
+### Update records
+
+```typescript
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: { name: 'Alice Smith' }
+})
+```
+
+### Delete records
+
+```typescript
+await prisma.user.delete({
+ where: { id: 1 }
+})
+```
+
+### Transactions
+
+```typescript
+const [user, post] = await prisma.$transaction([
+ prisma.user.create({ data: { email: 'alice@prisma.io' } }),
+ prisma.post.create({ data: { title: 'Hello', authorId: 1 } })
+])
+```
+
+## Rule Files
+
+Detailed API documentation:
+
+```
+references/constructor.md - PrismaClient constructor options
+references/model-queries.md - CRUD operations
+references/query-options.md - select, include, omit, where, orderBy
+references/filters.md - Filter conditions and operators
+references/relations.md - Relation queries and nested operations
+references/transactions.md - Transaction API
+references/raw-queries.md - $queryRaw, $executeRaw
+references/client-methods.md - $connect, $disconnect, $on, $extends
+```
+
+## Filter Operators
+
+| Operator | Description |
+|----------|-------------|
+| `equals` | Exact match |
+| `not` | Not equal |
+| `in` | In array |
+| `notIn` | Not in array |
+| `lt`, `lte` | Less than |
+| `gt`, `gte` | Greater than |
+| `contains` | String contains |
+| `startsWith` | String starts with |
+| `endsWith` | String ends with |
+| `mode` | Case sensitivity |
+
+## Relation Filters
+
+| Operator | Description |
+|----------|-------------|
+| `some` | At least one related record matches |
+| `every` | All related records match |
+| `none` | No related records match |
+| `is` | Related record matches (1-to-1) |
+| `isNot` | Related record doesn't match |
+
+## Resources
+
+- [Prisma Client API Reference](https://www.prisma.io/docs/orm/reference/prisma-client-reference)
+- [CRUD Operations](https://www.prisma.io/docs/orm/prisma-client/queries/crud)
+- [Filtering and Sorting](https://www.prisma.io/docs/orm/prisma-client/queries/filtering-and-sorting)
+
+## How to Use
+
+Pick the category from the table above, then open the matching reference file for implementation details and examples.
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/client-methods.md b/apps/backend/.agents/skills/prisma-client-api/references/client-methods.md
new file mode 100644
index 0000000..17beb1f
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/client-methods.md
@@ -0,0 +1,223 @@
+# Client Methods
+
+Prisma Client instance methods.
+
+## $connect()
+
+Explicitly connect to the database:
+
+```typescript
+const prisma = new PrismaClient({ adapter })
+
+// Explicit connection
+await prisma.$connect()
+```
+
+### When to use
+
+Usually not needed - Prisma connects automatically on first query. Use for:
+- Fail fast on startup
+- Health checks
+- Pre-warming connections
+
+```typescript
+async function main() {
+ try {
+ await prisma.$connect()
+ console.log('Database connected')
+ } catch (e) {
+ console.error('Failed to connect:', e)
+ process.exit(1)
+ }
+}
+```
+
+## $disconnect()
+
+Close database connection:
+
+```typescript
+await prisma.$disconnect()
+```
+
+### Graceful shutdown
+
+```typescript
+process.on('beforeExit', async () => {
+ await prisma.$disconnect()
+})
+
+// Or with SIGTERM
+process.on('SIGTERM', async () => {
+ await prisma.$disconnect()
+ process.exit(0)
+})
+```
+
+### In tests
+
+```typescript
+afterAll(async () => {
+ await prisma.$disconnect()
+})
+```
+
+## $on()
+
+Subscribe to events:
+
+### Query events
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ log: [{ level: 'query', emit: 'event' }]
+})
+
+prisma.$on('query', (e) => {
+ console.log('Query:', e.query)
+ console.log('Params:', e.params)
+ console.log('Duration:', e.duration, 'ms')
+})
+```
+
+### Log events
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ log: [
+ { level: 'info', emit: 'event' },
+ { level: 'warn', emit: 'event' },
+ { level: 'error', emit: 'event' }
+ ]
+})
+
+prisma.$on('info', (e) => console.log(e.message))
+prisma.$on('warn', (e) => console.warn(e.message))
+prisma.$on('error', (e) => console.error(e.message))
+```
+
+## $extends()
+
+Add extensions for custom behavior:
+
+### Add custom methods
+
+```typescript
+const prisma = new PrismaClient({ adapter }).$extends({
+ client: {
+ $log: (message: string) => console.log(message)
+ }
+})
+
+prisma.$log('Hello!')
+```
+
+### Add model methods
+
+```typescript
+const prisma = new PrismaClient({ adapter }).$extends({
+ model: {
+ user: {
+ async findByEmail(email: string) {
+ return prisma.user.findUnique({ where: { email } })
+ }
+ }
+ }
+})
+
+const user = await prisma.user.findByEmail('alice@prisma.io')
+```
+
+### Query extensions
+
+```typescript
+const prisma = new PrismaClient({ adapter }).$extends({
+ query: {
+ user: {
+ async findMany({ args, query }) {
+ // Add default filter
+ args.where = { ...args.where, deletedAt: null }
+ return query(args)
+ }
+ }
+ }
+})
+```
+
+### Result extensions
+
+```typescript
+const prisma = new PrismaClient({ adapter }).$extends({
+ result: {
+ user: {
+ fullName: {
+ needs: { firstName: true, lastName: true },
+ compute(user) {
+ return `${user.firstName} ${user.lastName}`
+ }
+ }
+ }
+ }
+})
+
+const user = await prisma.user.findFirst()
+console.log(user.fullName) // Computed field
+```
+
+### Chain extensions
+
+```typescript
+const prisma = new PrismaClient({ adapter })
+ .$extends(loggingExtension)
+ .$extends(softDeleteExtension)
+ .$extends(computedFieldsExtension)
+```
+
+## $transaction()
+
+See `transactions.md` for details.
+
+## $queryRaw() / $executeRaw()
+
+See `raw-queries.md` for details.
+
+## Type utilities
+
+### Prisma namespace
+
+```typescript
+import { Prisma } from '../generated/client'
+
+// Input types
+type UserCreateInput = Prisma.UserCreateInput
+type UserWhereInput = Prisma.UserWhereInput
+
+// Output types
+type User = Prisma.UserGetPayload<{}>
+type UserWithPosts = Prisma.UserGetPayload<{
+ include: { posts: true }
+}>
+```
+
+### Type-safe query fragments with satisfies
+
+Type-safe query fragments:
+
+```typescript
+import { Prisma } from '../generated/client'
+
+const userSelect = {
+ id: true,
+ email: true,
+ name: true
+} satisfies Prisma.UserSelect
+
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ select: userSelect
+})
+```
+
+With the `prisma-client` generator, use TypeScript `satisfies` for typed query fragments. You may still see older examples that use `Prisma.validator()` with `prisma-client-js`.
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/constructor.md b/apps/backend/.agents/skills/prisma-client-api/references/constructor.md
new file mode 100644
index 0000000..a9fb5e8
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/constructor.md
@@ -0,0 +1,221 @@
+# PrismaClient Constructor
+
+Configure Prisma Client when instantiating.
+
+## Basic Instantiation
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+## Constructor Options
+
+### adapter (Required for the SQL provider workflow)
+
+Driver adapter instance:
+
+```typescript
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### accelerateUrl (For Accelerate users)
+
+```typescript
+import { withAccelerate } from '@prisma/extension-accelerate'
+
+const prisma = new PrismaClient({
+ accelerateUrl: process.env.DATABASE_URL, // prisma:// URL
+}).$extends(withAccelerate())
+```
+
+### log
+
+Configure logging:
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ log: ['query', 'info', 'warn', 'error'],
+})
+```
+
+#### Log levels
+
+| Level | Description |
+|-------|-------------|
+| `query` | All SQL queries |
+| `info` | Informational messages |
+| `warn` | Warnings |
+| `error` | Errors |
+
+#### Log to events
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ log: [
+ { level: 'query', emit: 'event' },
+ { level: 'error', emit: 'stdout' },
+ ],
+})
+
+prisma.$on('query', (e) => {
+ console.log('Query:', e.query)
+ console.log('Duration:', e.duration, 'ms')
+})
+```
+
+### errorFormat
+
+Control error formatting:
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ errorFormat: 'pretty', // 'pretty' | 'colorless' | 'minimal'
+})
+```
+
+### comments
+
+Attach SQL commenter plugins for observability, tracing, or query insights:
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+import { prismaQueryInsights } from '@prisma/sqlcommenter-query-insights'
+import { queryTags, withQueryTags } from '@prisma/sqlcommenter-query-tags'
+import { traceContext } from '@prisma/sqlcommenter-trace-context'
+
+const prisma = new PrismaClient({
+ adapter: new PrismaPg(process.env.DATABASE_URL!),
+ comments: [prismaQueryInsights(), traceContext(), queryTags()],
+})
+
+await withQueryTags({ route: '/api/users', requestId: 'req-123' }, () =>
+ prisma.user.findMany(),
+)
+```
+
+Use `comments` only for SQL providers. This is the clean way to add trace or query-shape metadata without changing your query calls.
+
+### transactionOptions
+
+Default transaction settings:
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ transactionOptions: {
+ maxWait: 5000, // Max wait to acquire transaction (ms)
+ timeout: 10000, // Max transaction duration (ms)
+ isolationLevel: 'Serializable',
+ },
+})
+```
+
+### queryPlanCacheMaxSize
+
+Use `queryPlanCacheMaxSize` to limit the in-memory query-plan cache:
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ queryPlanCacheMaxSize: 2_000,
+})
+```
+
+The value must be a non-negative integer. Set it to `0` to disable query-plan caching; omit it to use Prisma's default. Treat this as a process-local memory/performance control, not a database prepared-statement setting.
+
+## Singleton Pattern
+
+Prevent multiple client instances in development:
+
+```typescript
+// lib/prisma.ts
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const globalForPrisma = globalThis as unknown as {
+ prisma: PrismaClient | undefined
+}
+
+function createPrismaClient() {
+ const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL!
+ })
+ return new PrismaClient({ adapter })
+}
+
+export const prisma = globalForPrisma.prisma ?? createPrismaClient()
+
+if (process.env.NODE_ENV !== 'production') {
+ globalForPrisma.prisma = prisma
+}
+```
+
+## Next.js Pattern
+
+```typescript
+// lib/prisma.ts
+import { PrismaClient } from '@/generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const createAdapter = () => new PrismaPg({
+ connectionString: process.env.DATABASE_URL!
+})
+
+const prismaClientSingleton = () => {
+ return new PrismaClient({ adapter: createAdapter() })
+}
+
+declare const globalThis: {
+ prismaGlobal: ReturnType
+} & typeof global
+
+const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
+
+export default prisma
+
+if (process.env.NODE_ENV !== 'production') {
+ globalThis.prismaGlobal = prisma
+}
+```
+
+## Query Events
+
+Listen to query events:
+
+```typescript
+const prisma = new PrismaClient({
+ adapter,
+ log: [{ level: 'query', emit: 'event' }],
+})
+
+prisma.$on('query', (e) => {
+ console.log('Query:', e.query)
+ console.log('Params:', e.params)
+ console.log('Duration:', e.duration)
+})
+```
+
+## Log Events
+
+```typescript
+prisma.$on('info', (e) => console.log(e.message))
+prisma.$on('warn', (e) => console.warn(e.message))
+prisma.$on('error', (e) => console.error(e.message))
+```
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/filters.md b/apps/backend/.agents/skills/prisma-client-api/references/filters.md
new file mode 100644
index 0000000..a9b7eea
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/filters.md
@@ -0,0 +1,256 @@
+# Filter Conditions and Operators
+
+Filter operators for the `where` clause.
+
+## Equality
+
+```typescript
+// Exact match (implicit)
+where: { email: 'alice@prisma.io' }
+
+// Explicit equals
+where: { email: { equals: 'alice@prisma.io' } }
+
+// Not equal
+where: { email: { not: 'alice@prisma.io' } }
+```
+
+## Comparison
+
+```typescript
+// Greater than
+where: { age: { gt: 18 } }
+
+// Greater than or equal
+where: { age: { gte: 18 } }
+
+// Less than
+where: { age: { lt: 65 } }
+
+// Less than or equal
+where: { age: { lte: 65 } }
+
+// Combined
+where: { age: { gte: 18, lte: 65 } }
+```
+
+## Lists
+
+```typescript
+// In array
+where: { role: { in: ['ADMIN', 'MODERATOR'] } }
+
+// Not in array
+where: { role: { notIn: ['GUEST', 'BANNED'] } }
+```
+
+## String Filters
+
+```typescript
+// Contains
+where: { email: { contains: 'prisma' } }
+
+// Starts with
+where: { email: { startsWith: 'alice' } }
+
+// Ends with
+where: { email: { endsWith: '@prisma.io' } }
+
+// Case-insensitive (default for some databases)
+where: {
+ email: {
+ contains: 'PRISMA',
+ mode: 'insensitive'
+ }
+}
+```
+
+## Null Checks
+
+```typescript
+// Is null
+where: { deletedAt: null }
+
+// Is not null
+where: { deletedAt: { not: null } }
+
+// Using isSet (for optional fields)
+where: { middleName: { isSet: true } }
+```
+
+## Logical Operators
+
+### AND (implicit)
+
+```typescript
+// Multiple conditions = AND
+where: {
+ email: { contains: '@prisma.io' },
+ role: 'ADMIN'
+}
+```
+
+### AND (explicit)
+
+```typescript
+where: {
+ AND: [
+ { email: { contains: '@prisma.io' } },
+ { role: 'ADMIN' }
+ ]
+}
+```
+
+### OR
+
+```typescript
+where: {
+ OR: [
+ { email: { contains: '@gmail.com' } },
+ { email: { contains: '@prisma.io' } }
+ ]
+}
+```
+
+### NOT
+
+```typescript
+where: {
+ NOT: {
+ role: 'GUEST'
+ }
+}
+
+// Multiple NOT conditions
+where: {
+ NOT: [
+ { role: 'GUEST' },
+ { verified: false }
+ ]
+}
+```
+
+### Combined
+
+```typescript
+where: {
+ AND: [
+ { verified: true },
+ {
+ OR: [
+ { role: 'ADMIN' },
+ { role: 'MODERATOR' }
+ ]
+ }
+ ],
+ NOT: { deletedAt: { not: null } }
+}
+```
+
+## Relation Filters
+
+### some
+
+At least one related record matches:
+
+```typescript
+// Users with at least one published post
+where: {
+ posts: {
+ some: { published: true }
+ }
+}
+```
+
+### every
+
+All related records match:
+
+```typescript
+// Users where all posts are published
+where: {
+ posts: {
+ every: { published: true }
+ }
+}
+```
+
+### none
+
+No related records match:
+
+```typescript
+// Users with no published posts
+where: {
+ posts: {
+ none: { published: true }
+ }
+}
+```
+
+### is / isNot (1-to-1)
+
+```typescript
+// Users with profile in specific country
+where: {
+ profile: {
+ is: { country: 'USA' }
+ }
+}
+
+// Users without profile
+where: {
+ profile: {
+ isNot: null
+ }
+}
+```
+
+## Array Field Filters
+
+For fields like `String[]`:
+
+```typescript
+// Has element
+where: { tags: { has: 'typescript' } }
+
+// Has some elements
+where: { tags: { hasSome: ['typescript', 'javascript'] } }
+
+// Has every element
+where: { tags: { hasEvery: ['typescript', 'prisma'] } }
+
+// Is empty
+where: { tags: { isEmpty: true } }
+```
+
+## JSON Filters
+
+```typescript
+// Path-based filter
+where: {
+ metadata: {
+ path: ['settings', 'theme'],
+ equals: 'dark'
+ }
+}
+
+// String contains in JSON
+where: {
+ metadata: {
+ path: ['bio'],
+ string_contains: 'developer'
+ }
+}
+```
+
+## Full-Text Search
+
+```typescript
+// Requires @@fulltext index
+where: {
+ content: {
+ search: 'prisma database'
+ }
+}
+```
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/model-queries.md b/apps/backend/.agents/skills/prisma-client-api/references/model-queries.md
new file mode 100644
index 0000000..0687ef5
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/model-queries.md
@@ -0,0 +1,281 @@
+# Model Queries
+
+CRUD operations for your Prisma models.
+
+## Read Operations
+
+### findUnique
+
+Find a single record by unique field:
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 }
+})
+
+const user = await prisma.user.findUnique({
+ where: { email: 'alice@prisma.io' }
+})
+```
+
+#### With composite unique key
+
+```typescript
+// Model with @@unique([firstName, lastName])
+const user = await prisma.user.findUnique({
+ where: {
+ firstName_lastName: {
+ firstName: 'Alice',
+ lastName: 'Smith'
+ }
+ }
+})
+```
+
+### findUniqueOrThrow
+
+Same as findUnique but throws if not found:
+
+```typescript
+const user = await prisma.user.findUniqueOrThrow({
+ where: { id: 1 }
+})
+// Throws PrismaClientKnownRequestError if not found
+```
+
+### findFirst
+
+Find first matching record:
+
+```typescript
+const user = await prisma.user.findFirst({
+ where: { role: 'ADMIN' },
+ orderBy: { createdAt: 'desc' }
+})
+```
+
+### findFirstOrThrow
+
+```typescript
+const user = await prisma.user.findFirstOrThrow({
+ where: { role: 'ADMIN' }
+})
+```
+
+### findMany
+
+Find multiple records:
+
+```typescript
+const users = await prisma.user.findMany({
+ where: { role: 'USER' },
+ orderBy: { name: 'asc' },
+ take: 10,
+ skip: 0
+})
+```
+
+## Create Operations
+
+### create
+
+Create a single record:
+
+```typescript
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ name: 'Alice'
+ }
+})
+```
+
+#### With relations
+
+```typescript
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ posts: {
+ create: [
+ { title: 'First Post' },
+ { title: 'Second Post' }
+ ]
+ }
+ },
+ include: { posts: true }
+})
+```
+
+### createMany
+
+Create multiple records:
+
+```typescript
+const result = await prisma.user.createMany({
+ data: [
+ { email: 'alice@prisma.io', name: 'Alice' },
+ { email: 'bob@prisma.io', name: 'Bob' }
+ ],
+ skipDuplicates: true // Skip records with duplicate unique fields
+})
+// Returns { count: 2 }
+```
+
+### createManyAndReturn
+
+Create multiple and return them:
+
+```typescript
+const users = await prisma.user.createManyAndReturn({
+ data: [
+ { email: 'alice@prisma.io', name: 'Alice' },
+ { email: 'bob@prisma.io', name: 'Bob' }
+ ]
+})
+// Returns array of created users
+```
+
+## Update Operations
+
+### update
+
+Update a single record:
+
+```typescript
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: { name: 'Alice Smith' }
+})
+```
+
+#### Atomic operations
+
+```typescript
+const post = await prisma.post.update({
+ where: { id: 1 },
+ data: {
+ views: { increment: 1 },
+ likes: { decrement: 1 },
+ score: { multiply: 2 },
+ rating: { divide: 2 },
+ version: { set: 5 }
+ }
+})
+```
+
+### updateMany
+
+Update multiple records:
+
+```typescript
+const result = await prisma.user.updateMany({
+ where: { role: 'USER' },
+ data: { verified: true }
+})
+// Returns { count: 42 }
+```
+
+### updateManyAndReturn
+
+```typescript
+const users = await prisma.user.updateManyAndReturn({
+ where: { role: 'USER' },
+ data: { verified: true }
+})
+// Returns array of updated users
+```
+
+### upsert
+
+Update or create:
+
+```typescript
+const user = await prisma.user.upsert({
+ where: { email: 'alice@prisma.io' },
+ update: { name: 'Alice Smith' },
+ create: { email: 'alice@prisma.io', name: 'Alice' }
+})
+```
+
+## Delete Operations
+
+### delete
+
+Delete a single record:
+
+```typescript
+const user = await prisma.user.delete({
+ where: { id: 1 }
+})
+// Returns deleted record
+```
+
+### deleteMany
+
+Delete multiple records:
+
+```typescript
+const result = await prisma.user.deleteMany({
+ where: { role: 'GUEST' }
+})
+// Returns { count: 5 }
+
+// Delete all
+const result = await prisma.user.deleteMany({})
+```
+
+## Aggregation Operations
+
+### count
+
+```typescript
+const count = await prisma.user.count({
+ where: { role: 'ADMIN' }
+})
+```
+
+### aggregate
+
+```typescript
+const result = await prisma.post.aggregate({
+ _avg: { views: true },
+ _sum: { views: true },
+ _min: { views: true },
+ _max: { views: true },
+ _count: { _all: true }
+})
+```
+
+### groupBy
+
+```typescript
+const groups = await prisma.user.groupBy({
+ by: ['country'],
+ _count: { _all: true },
+ _avg: { age: true },
+ having: {
+ age: { _avg: { gt: 30 } }
+ }
+})
+```
+
+## Return Types
+
+| Method | Returns |
+|--------|---------|
+| `findUnique` | Record \| null |
+| `findUniqueOrThrow` | Record (throws if not found) |
+| `findFirst` | Record \| null |
+| `findFirstOrThrow` | Record (throws if not found) |
+| `findMany` | Record[] |
+| `create` | Record |
+| `createMany` | { count: number } |
+| `createManyAndReturn` | Record[] |
+| `update` | Record |
+| `updateMany` | { count: number } |
+| `delete` | Record |
+| `deleteMany` | { count: number } |
+| `count` | number |
+| `aggregate` | Aggregate result |
+| `groupBy` | Group result[] |
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/query-options.md b/apps/backend/.agents/skills/prisma-client-api/references/query-options.md
new file mode 100644
index 0000000..25864a4
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/query-options.md
@@ -0,0 +1,276 @@
+# Query Options
+
+Options for controlling query behavior.
+
+## select
+
+Choose specific fields to return:
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ // password: false (excluded by not including)
+ }
+})
+// Returns: { id: 1, name: 'Alice', email: 'alice@prisma.io' }
+```
+
+### Select relations
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ select: {
+ name: true,
+ posts: {
+ select: {
+ title: true,
+ published: true
+ }
+ }
+ }
+})
+```
+
+### Select with include inside
+
+```typescript
+const user = await prisma.user.findMany({
+ select: {
+ name: true,
+ posts: {
+ include: {
+ comments: true
+ }
+ }
+ }
+})
+```
+
+### Select relation count
+
+```typescript
+const users = await prisma.user.findMany({
+ select: {
+ name: true,
+ _count: {
+ select: { posts: true }
+ }
+ }
+})
+// Returns: { name: 'Alice', _count: { posts: 5 } }
+```
+
+## include
+
+Include related records:
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ include: {
+ posts: true,
+ profile: true
+ }
+})
+```
+
+### Filtered include
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ include: {
+ posts: {
+ where: { published: true },
+ orderBy: { createdAt: 'desc' },
+ take: 5
+ }
+ }
+})
+```
+
+### Nested include
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ include: {
+ posts: {
+ include: {
+ comments: {
+ include: {
+ author: true
+ }
+ }
+ }
+ }
+ }
+})
+```
+
+### Include relation count
+
+```typescript
+const users = await prisma.user.findMany({
+ include: {
+ _count: {
+ select: { posts: true, followers: true }
+ }
+ }
+})
+```
+
+## omit
+
+Exclude specific fields:
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ omit: {
+ password: true
+ }
+})
+// Returns all fields except password
+```
+
+### Omit in relations
+
+```typescript
+const users = await prisma.user.findMany({
+ omit: { password: true },
+ include: {
+ posts: {
+ omit: { content: true }
+ }
+ }
+})
+```
+
+**Note:** Cannot use `select` and `omit` together.
+
+## where
+
+Filter records:
+
+```typescript
+const users = await prisma.user.findMany({
+ where: {
+ email: { contains: '@prisma.io' },
+ role: 'ADMIN'
+ }
+})
+```
+
+See `filters.md` for detailed filter operators.
+
+## orderBy
+
+Sort results:
+
+```typescript
+// Single field
+const users = await prisma.user.findMany({
+ orderBy: { name: 'asc' }
+})
+
+// Multiple fields
+const users = await prisma.user.findMany({
+ orderBy: [
+ { role: 'desc' },
+ { name: 'asc' }
+ ]
+})
+```
+
+### Order by relation
+
+```typescript
+const users = await prisma.user.findMany({
+ orderBy: {
+ posts: { _count: 'desc' }
+ }
+})
+```
+
+### Null handling
+
+```typescript
+const users = await prisma.user.findMany({
+ orderBy: {
+ name: { sort: 'asc', nulls: 'last' }
+ }
+})
+```
+
+## take & skip
+
+Pagination:
+
+```typescript
+// First page
+const users = await prisma.user.findMany({
+ take: 10,
+ skip: 0
+})
+
+// Second page
+const users = await prisma.user.findMany({
+ take: 10,
+ skip: 10
+})
+```
+
+### Negative take (reverse)
+
+```typescript
+const lastUsers = await prisma.user.findMany({
+ take: -10,
+ orderBy: { id: 'asc' }
+})
+// Returns last 10 users
+```
+
+## cursor
+
+Cursor-based pagination:
+
+```typescript
+// First page
+const firstPage = await prisma.user.findMany({
+ take: 10,
+ orderBy: { id: 'asc' }
+})
+
+// Next page using cursor
+const nextPage = await prisma.user.findMany({
+ take: 10,
+ skip: 1, // Skip the cursor record
+ cursor: { id: firstPage[firstPage.length - 1].id },
+ orderBy: { id: 'asc' }
+})
+```
+
+## distinct
+
+Return unique values:
+
+```typescript
+const cities = await prisma.user.findMany({
+ distinct: ['city'],
+ select: { city: true }
+})
+```
+
+### Multiple distinct fields
+
+```typescript
+const locations = await prisma.user.findMany({
+ distinct: ['city', 'country']
+})
+```
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/raw-queries.md b/apps/backend/.agents/skills/prisma-client-api/references/raw-queries.md
new file mode 100644
index 0000000..e444ce2
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/raw-queries.md
@@ -0,0 +1,198 @@
+# Raw Queries
+
+Execute raw SQL when Prisma's query API isn't sufficient.
+
+## $queryRaw
+
+Execute SELECT queries and get typed results:
+
+```typescript
+const users = await prisma.$queryRaw`
+ SELECT * FROM "User" WHERE email LIKE ${'%@prisma.io'}
+`
+```
+
+### With type
+
+```typescript
+type User = { id: number; email: string; name: string | null }
+
+const users = await prisma.$queryRaw`
+ SELECT id, email, name FROM "User" WHERE role = ${'ADMIN'}
+`
+```
+
+### Dynamic table/column names
+
+Use `Prisma.raw()` for identifiers (not safe for user input):
+
+```typescript
+import { Prisma } from '../generated/client'
+
+const column = 'email'
+const users = await prisma.$queryRaw`
+ SELECT ${Prisma.raw(column)} FROM "User"
+`
+```
+
+### With Prisma.sql
+
+Build queries dynamically:
+
+```typescript
+import { Prisma } from '../generated/client'
+
+const email = 'alice@prisma.io'
+const query = Prisma.sql`SELECT * FROM "User" WHERE email = ${email}`
+const users = await prisma.$queryRaw(query)
+```
+
+### Join multiple SQL fragments
+
+```typescript
+import { Prisma } from '../generated/client'
+
+const conditions = [
+ Prisma.sql`role = ${'ADMIN'}`,
+ Prisma.sql`verified = ${true}`
+]
+
+const users = await prisma.$queryRaw`
+ SELECT * FROM "User"
+ WHERE ${Prisma.join(conditions, ' AND ')}
+`
+```
+
+## $executeRaw
+
+Execute INSERT, UPDATE, DELETE (returns affected count):
+
+```typescript
+const count = await prisma.$executeRaw`
+ UPDATE "User" SET verified = true WHERE email LIKE ${'%@prisma.io'}
+`
+console.log(`Updated ${count} users`)
+```
+
+### Delete example
+
+```typescript
+const deleted = await prisma.$executeRaw`
+ DELETE FROM "User" WHERE "deletedAt" < ${thirtyDaysAgo}
+`
+```
+
+### Insert example
+
+```typescript
+const inserted = await prisma.$executeRaw`
+ INSERT INTO "Log" (message, level, timestamp)
+ VALUES (${message}, ${level}, ${new Date()})
+`
+```
+
+## $queryRawUnsafe / $executeRawUnsafe
+
+For fully dynamic queries (use with caution!):
+
+```typescript
+// ⚠️ SQL injection risk - only use with trusted input
+const table = 'User'
+const users = await prisma.$queryRawUnsafe(
+ `SELECT * FROM "${table}" WHERE id = $1`,
+ userId
+)
+```
+
+### Parameterized unsafe query
+
+```typescript
+const result = await prisma.$executeRawUnsafe(
+ 'UPDATE "User" SET name = $1 WHERE id = $2',
+ 'Alice',
+ 1
+)
+```
+
+## SQL Injection Prevention
+
+### Safe (parameterized)
+
+```typescript
+// ✅ User input is parameterized
+const email = userInput
+const users = await prisma.$queryRaw`
+ SELECT * FROM "User" WHERE email = ${email}
+`
+```
+
+### Unsafe (concatenation)
+
+```typescript
+// ❌ SQL injection vulnerability!
+const email = userInput
+const users = await prisma.$queryRawUnsafe(
+ `SELECT * FROM "User" WHERE email = '${email}'`
+)
+```
+
+## Database-Specific Features
+
+### PostgreSQL
+
+```typescript
+// Array operations
+const users = await prisma.$queryRaw`
+ SELECT * FROM "User" WHERE 'admin' = ANY(roles)
+`
+
+// JSON operations
+const users = await prisma.$queryRaw`
+ SELECT * FROM "User" WHERE metadata->>'theme' = 'dark'
+`
+```
+
+### MySQL
+
+```typescript
+// Full-text search
+const posts = await prisma.$queryRaw`
+ SELECT * FROM Post WHERE MATCH(title, content) AGAINST(${searchTerm})
+`
+```
+
+## Transactions with Raw Queries
+
+```typescript
+await prisma.$transaction(async (tx) => {
+ await tx.$executeRaw`UPDATE "Account" SET balance = balance - ${amount} WHERE id = ${senderId}`
+ await tx.$executeRaw`UPDATE "Account" SET balance = balance + ${amount} WHERE id = ${recipientId}`
+})
+```
+
+## Handling Results
+
+### BigInt handling
+
+PostgreSQL returns BigInt for COUNT:
+
+```typescript
+const result = await prisma.$queryRaw<[{ count: bigint }]>`
+ SELECT COUNT(*) as count FROM "User"
+`
+const count = Number(result[0].count)
+```
+
+### Date handling
+
+```typescript
+type Result = { createdAt: Date }
+const users = await prisma.$queryRaw`
+ SELECT "createdAt" FROM "User"
+`
+// createdAt is already a Date object
+```
+
+Invalid JavaScript `Date` values passed to raw queries fail validation instead of being silently serialized as `null`. Validate date input at the application boundary; do not rely on `new Date(badValue)` reaching the database.
+
+When a driver adapter returns an unmapped database-specific error, Prisma surfaces `P2039` with the adapter's preserved original code/message. If those details are missing, fix the adapter mapping rather than parsing rendered error text.
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/relations.md b/apps/backend/.agents/skills/prisma-client-api/references/relations.md
new file mode 100644
index 0000000..001c448
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/relations.md
@@ -0,0 +1,308 @@
+# Relation Queries
+
+Query and modify related records.
+
+## Include Relations
+
+Load related records:
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ include: {
+ posts: true,
+ profile: true
+ }
+})
+```
+
+### Filtered include
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ include: {
+ posts: {
+ where: { published: true },
+ orderBy: { createdAt: 'desc' },
+ take: 5,
+ select: { id: true, title: true }
+ }
+ }
+})
+```
+
+### Nested include
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ include: {
+ posts: {
+ include: {
+ comments: {
+ include: { author: true }
+ }
+ }
+ }
+ }
+})
+```
+
+## Select Relations
+
+```typescript
+const user = await prisma.user.findUnique({
+ where: { id: 1 },
+ select: {
+ name: true,
+ posts: {
+ select: { title: true }
+ }
+ }
+})
+```
+
+## Nested Writes
+
+### Create with relations
+
+```typescript
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ posts: {
+ create: [
+ { title: 'Post 1' },
+ { title: 'Post 2' }
+ ]
+ },
+ profile: {
+ create: { bio: 'Hello!' }
+ }
+ }
+})
+```
+
+### Create or connect
+
+```typescript
+const post = await prisma.post.create({
+ data: {
+ title: 'New Post',
+ author: {
+ connectOrCreate: {
+ where: { email: 'alice@prisma.io' },
+ create: { email: 'alice@prisma.io', name: 'Alice' }
+ }
+ }
+ }
+})
+```
+
+### Connect existing
+
+```typescript
+const post = await prisma.post.create({
+ data: {
+ title: 'New Post',
+ author: {
+ connect: { id: 1 }
+ }
+ }
+})
+
+// Shorthand for foreign key
+const post = await prisma.post.create({
+ data: {
+ title: 'New Post',
+ authorId: 1
+ }
+})
+```
+
+## Update Relations
+
+### Update related records
+
+```typescript
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: {
+ posts: {
+ update: {
+ where: { id: 1 },
+ data: { title: 'Updated Title' }
+ }
+ }
+ }
+})
+```
+
+### Update many related
+
+```typescript
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: {
+ posts: {
+ updateMany: {
+ where: { published: false },
+ data: { published: true }
+ }
+ }
+ }
+})
+```
+
+### Upsert related
+
+```typescript
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: {
+ profile: {
+ upsert: {
+ create: { bio: 'New bio' },
+ update: { bio: 'Updated bio' }
+ }
+ }
+ }
+})
+```
+
+### Disconnect
+
+```typescript
+// 1-to-1 optional
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: {
+ profile: { disconnect: true }
+ }
+})
+
+// Many-to-many
+const post = await prisma.post.update({
+ where: { id: 1 },
+ data: {
+ tags: {
+ disconnect: [{ id: 1 }, { id: 2 }]
+ }
+ }
+})
+```
+
+### Delete related
+
+```typescript
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: {
+ posts: {
+ delete: { id: 1 }
+ }
+ }
+})
+
+// Delete many
+const user = await prisma.user.update({
+ where: { id: 1 },
+ data: {
+ posts: {
+ deleteMany: { published: false }
+ }
+ }
+})
+```
+
+### Set (replace all)
+
+```typescript
+// Replace all related records
+const post = await prisma.post.update({
+ where: { id: 1 },
+ data: {
+ tags: {
+ set: [{ id: 1 }, { id: 2 }]
+ }
+ }
+})
+```
+
+## Relation Filters
+
+### some
+
+At least one matches:
+
+```typescript
+const users = await prisma.user.findMany({
+ where: {
+ posts: { some: { published: true } }
+ }
+})
+```
+
+### every
+
+All match:
+
+```typescript
+const users = await prisma.user.findMany({
+ where: {
+ posts: { every: { published: true } }
+ }
+})
+```
+
+### none
+
+None match:
+
+```typescript
+const users = await prisma.user.findMany({
+ where: {
+ posts: { none: { published: true } }
+ }
+})
+```
+
+### is / isNot (1-to-1)
+
+```typescript
+const users = await prisma.user.findMany({
+ where: {
+ profile: { is: { country: 'USA' } }
+ }
+})
+```
+
+## Count Relations
+
+```typescript
+const users = await prisma.user.findMany({
+ select: {
+ name: true,
+ _count: {
+ select: { posts: true, followers: true }
+ }
+ }
+})
+// { name: 'Alice', _count: { posts: 5, followers: 100 } }
+```
+
+### Filter counted relations
+
+```typescript
+const users = await prisma.user.findMany({
+ select: {
+ name: true,
+ _count: {
+ select: {
+ posts: { where: { published: true } }
+ }
+ }
+ }
+})
+```
diff --git a/apps/backend/.agents/skills/prisma-client-api/references/transactions.md b/apps/backend/.agents/skills/prisma-client-api/references/transactions.md
new file mode 100644
index 0000000..c2a981a
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-client-api/references/transactions.md
@@ -0,0 +1,184 @@
+# Transactions
+
+Execute multiple operations atomically.
+
+## Sequential Transactions
+
+Array of operations executed in order:
+
+```typescript
+const [user, post] = await prisma.$transaction([
+ prisma.user.create({ data: { email: 'alice@prisma.io' } }),
+ prisma.post.create({ data: { title: 'Hello', authorId: 1 } })
+])
+```
+
+### All or nothing
+
+If any operation fails, all are rolled back:
+
+```typescript
+try {
+ await prisma.$transaction([
+ prisma.user.create({ data: { email: 'alice@prisma.io' } }),
+ prisma.user.create({ data: { email: 'alice@prisma.io' } }) // Duplicate!
+ ])
+} catch (e) {
+ // Both operations rolled back
+}
+```
+
+## Interactive Transactions
+
+For complex logic and dependent operations:
+
+```typescript
+await prisma.$transaction(async (tx) => {
+ // Decrement sender balance
+ const sender = await tx.account.update({
+ where: { id: senderId },
+ data: { balance: { decrement: amount } }
+ })
+
+ // Check balance
+ if (sender.balance < 0) {
+ throw new Error('Insufficient funds')
+ }
+
+ // Increment recipient balance
+ await tx.account.update({
+ where: { id: recipientId },
+ data: { balance: { increment: amount } }
+ })
+})
+```
+
+### Transaction options
+
+```typescript
+await prisma.$transaction(
+ async (tx) => {
+ // operations
+ },
+ {
+ maxWait: 5000, // Max wait to acquire lock (ms)
+ timeout: 10000, // Max transaction duration (ms)
+ isolationLevel: 'Serializable' // Isolation level
+ }
+)
+```
+
+### Isolation levels
+
+| Level | Description |
+|-------|-------------|
+| `ReadUncommitted` | Lowest isolation, can read uncommitted changes |
+| `ReadCommitted` | Only read committed changes |
+| `RepeatableRead` | Consistent reads within transaction |
+| `Serializable` | Highest isolation, serialized execution |
+
+## Nested Writes
+
+Automatic transactions for nested operations:
+
+```typescript
+// This is automatically a transaction
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ posts: {
+ create: [
+ { title: 'Post 1' },
+ { title: 'Post 2' }
+ ]
+ },
+ profile: {
+ create: { bio: 'Hello!' }
+ }
+ }
+})
+```
+
+## Transaction Client
+
+The `tx` parameter is a Prisma Client scoped to the transaction:
+
+```typescript
+await prisma.$transaction(async (tx) => {
+ // Use tx instead of prisma
+ await tx.user.create({ ... })
+ await tx.post.create({ ... })
+
+ // Can call methods
+ const count = await tx.user.count()
+})
+```
+
+## OrThrow in Transactions
+
+Use with interactive transactions:
+
+```typescript
+await prisma.$transaction(async (tx) => {
+ // If not found, throws and rolls back entire transaction
+ const user = await tx.user.findUniqueOrThrow({
+ where: { id: 1 }
+ })
+
+ await tx.post.create({
+ data: { title: 'New Post', authorId: user.id }
+ })
+})
+```
+
+## Best Practices
+
+### Keep transactions short
+
+```typescript
+// Good - only DB operations in transaction
+const data = prepareData() // Outside transaction
+await prisma.$transaction(async (tx) => {
+ await tx.user.create({ data })
+})
+```
+
+### Handle errors
+
+```typescript
+try {
+ await prisma.$transaction(async (tx) => {
+ // operations
+ })
+} catch (e) {
+ if (e.code === 'P2002') {
+ // Handle unique constraint violation
+ }
+ throw e
+}
+```
+
+### Use appropriate isolation
+
+```typescript
+// Default is fine for most cases
+await prisma.$transaction(async (tx) => {
+ // operations
+})
+
+// Use Serializable for strict consistency
+await prisma.$transaction(
+ async (tx) => { /* operations */ },
+ { isolationLevel: 'Serializable' }
+)
+```
+
+## Sequential vs Interactive
+
+| Feature | Sequential | Interactive |
+|---------|------------|-------------|
+| Syntax | Array | Async function |
+| Dependent ops | No | Yes |
+| Conditional logic | No | Yes |
+| Performance | Better | More flexible |
+| Use case | Simple batch | Complex logic |
diff --git a/apps/backend/.agents/skills/prisma-compute/SKILL.md b/apps/backend/.agents/skills/prisma-compute/SKILL.md
new file mode 100644
index 0000000..f1105f9
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-compute/SKILL.md
@@ -0,0 +1,193 @@
+---
+name: prisma-compute
+description: Prisma Compute deployment and hosting guide. Use whenever the user mentions Prisma Compute, `prisma.compute.ts`, `defineComputeConfig`, deploying or hosting a Prisma app, `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, `PRISMA_SERVICE_TOKEN`, Compute auth/workspaces, apps/deployments/build logs/domains, localhost vs `0.0.0.0`, deploy port binding, or framework deploy readiness for Hono, Elysia, Next.js, TanStack Start, Astro, Nuxt, Svelte, Nest, Turborepo, or custom/prebuilt artifacts.
+license: MIT
+metadata:
+ author: prisma
+ version: "1.5.1"
+---
+
+# Prisma Compute
+
+Guide agents through Prisma Compute app creation, deployment, operations, and framework-specific deploy readiness.
+
+## Prisma Compute CLI Surface
+
+Use the Prisma Platform CLI for Compute app workflows:
+
+```bash
+bunx @prisma/cli@latest app deploy --help
+bunx @prisma/cli@latest app --help
+bunx @prisma/cli@latest build logs --help
+bunx create-prisma@latest --help
+```
+
+Use `@prisma/cli@latest` for Compute app deployment. Use `create-prisma@latest` for new-project scaffolding.
+
+## Send Feedback and Report CLI Issues
+
+The CLI has a built-in feedback channel. Use it whenever a command crashes (`UNEXPECTED_ERROR`), a failure survives troubleshooting, or the user asks to send feedback to the Prisma team:
+
+```bash
+bunx @prisma/cli@latest feedback "app deploy crashed: "
+bunx @prisma/cli@latest feedback "love the deploy flow" --email you@example.com
+```
+
+Crash output points here on its own: `--json` crash envelopes carry the exact pre-filled command as a `recover` entry in `nextActions` (run it verbatim), and human crash output ends with a `Tell us what happened:` hint. Feedback is anonymous unless `--email` is passed and attaches only the CLI version, node version, and OS platform/arch. Never include secrets, connection URLs, or user data in the message.
+
+## Source-of-Truth Order
+
+Use evidence in this order when deciding what to edit or run:
+
+1. The project's generated scripts and config, especially `prisma.compute.ts`, `compute:deploy`, framework config, and `package.json`.
+2. CLI help output from `create-prisma` and `@prisma/cli`.
+3. Local installed package code, generated artifacts, and type definitions.
+4. Official docs.
+
+## When to Apply
+
+Use this skill for:
+
+- Creating a new app that can deploy to Prisma Compute
+- Deploying an existing TypeScript app to Prisma Compute
+- Creating or updating a typed `prisma.compute.ts` deploy config
+- Deciding whether a framework is Compute-ready
+- Debugging `create-prisma --deploy`, `compute:deploy`, or `app deploy`
+- Managing Compute app logs, deployments, environment variables, and domains, and listing platform branches (`branch list`; there are no branch create/remove commands)
+- Inspecting GitHub/Console build logs and GitHub push-to-deploy status
+- Running non-interactive deploys with browser auth, multiple stored workspaces, or Prisma service tokens
+- Switching, selecting, listing, or logging out local Prisma Platform workspaces for `@prisma/cli`
+- Sending feedback about an unresolvable Compute CLI failure with `@prisma/cli feedback`
+- Programmatic deployments with `@prisma/compute-sdk` or Management API integrations
+
+## Decision Tree
+
+1. Existing project deployment or redeploy:
+ Read [`references/app-deploy-cli.md`](references/app-deploy-cli.md).
+
+2. Typed Compute config, monorepos, deploy targets, app roots, or build/env defaults:
+ Read [`references/compute-config.md`](references/compute-config.md).
+
+3. Framework-specific build/runtime work:
+ Read [`references/frameworks.md`](references/frameworks.md).
+
+4. New project from a scaffold:
+ Read [`references/create-prisma.md`](references/create-prisma.md).
+
+5. Programmatic deployment, SDKs, APIs, or low-level App/Deployment concepts:
+ Read [`references/sdk-api.md`](references/sdk-api.md).
+
+6. Build, auth, env, deploy, or runtime failures:
+ Read [`references/troubleshooting.md`](references/troubleshooting.md).
+
+## Rules by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Command verification | CRITICAL | `verify-` |
+| 2 | Auth and workspace selection | CRITICAL | `auth-` |
+| 3 | Framework readiness | CRITICAL | `framework-` |
+| 4 | Runtime host and port binding | CRITICAL | `runtime-` |
+| 5 | Typed Compute config | HIGH | `config-` |
+| 6 | Branch, environment, and database wiring | HIGH | `env-` |
+| 7 | Deploy operations | HIGH | `deploy-` |
+| 8 | SDK and API automation | MEDIUM | `sdk-` |
+
+## Quick Rules
+
+### 1. Command Verification
+
+- `verify-help-first` - Use CLI help output to confirm command syntax while working.
+- `verify-prisma-vs-platform-cli` - Do not assume `prisma app deploy` exists in the ORM CLI; check whether the task should use `@prisma/cli`.
+- `verify-generated-scripts` - Prefer the generated `compute:deploy` script when a project already has one.
+- `verify-public-url` - After a real deploy, request the public deployment URL instead of trusting local or readiness-only checks.
+- `verify-config-support` - Treat `prisma.compute.ts` as the typed Compute config; inspect the project's config and generated scripts before editing or deploying.
+- `verify-auth-workspace-support` - Use `@prisma/cli auth workspace` commands for local workspace list/use/logout flows.
+
+### 2. Auth and Workspace Selection
+
+- `auth-source-precedence` - A non-empty `PRISMA_SERVICE_TOKEN` is the active auth source for commands and local OAuth workspaces are ignored for execution. If it is set but empty, the CLI should fail instead of falling back to stored OAuth.
+- `auth-multi-workspace` - `auth login` can store OAuth sessions for multiple workspaces on the same machine. The active workspace pointer selects which stored OAuth grant normal commands use.
+- `auth-list-before-switch` - Use `auth workspace list --json` to inspect local sessions. Agents should prefer workspace ids from JSON over names because names can be ambiguous.
+- `auth-switch-explicitly` - Use `auth workspace use ` for non-interactive switching. Use `auth workspace use` with no argument only for an interactive picker or when exactly one local OAuth workspace exists.
+- `auth-no-fallthrough` - If the active OAuth workspace is logged out or fails refresh, the CLI should not silently fall through to another cached workspace. Run `auth workspace use ` to choose the next workspace.
+- `auth-single-workspace-logout` - Use `auth workspace logout ` or `auth logout --workspace ` to remove one local OAuth workspace session. Plain `auth logout` clears all local OAuth workspace sessions.
+- `auth-service-token-switching` - While `PRISMA_SERVICE_TOKEN` is set, `auth workspace use` is unavailable because the service token is the active auth source; unset the env var to switch local OAuth workspaces. Workspace logout still only cleans local OAuth state.
+- `auth-storage-awareness` - Local OAuth credentials live in the platform auth file, with workspace metadata in a sidecar context file. Project pins live in `.prisma/local.json`, and CLI app/project state lives in `.prisma/cli/state.json` near `prisma.compute.ts` when present.
+
+### 3. Framework Readiness
+
+- `framework-cli-first` - Evaluate deploy readiness against `@prisma/cli app deploy`, not against what `create-prisma` can scaffold.
+- `framework-supported-cli-deploy` - Compute deploy supports `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, and `bun`.
+- `framework-create-prisma-defaults-only` - `create-prisma` can provide generated defaults and `compute:deploy`, but it is not the general deploy surface for existing apps.
+- `framework-build-output` - Compute needs a server entrypoint or framework artifact, not only static output.
+
+### 4. Runtime Host and Port Binding
+
+- `runtime-bind-all-interfaces` - Deployed servers must bind on all interfaces (`0.0.0.0` or the framework equivalent), not hard-coded `localhost` or `127.0.0.1`.
+- `runtime-match-http-port` - The app must listen on the deployed HTTP port: read `process.env.PORT` when possible, or pass the matching `--http-port`.
+- `runtime-readiness-port-only` - Compute readiness watches listening ports; a loopback-only listener can look ready while public ingress cannot reach it.
+- `runtime-respond-within-60s` - The ingress gives an app 60 seconds to start responding, then returns `504 Gateway Time-out` and cancels the request. Design handlers to answer first and run longer work under `waitUntil` or from a queue, never inside the request.
+
+### 5. Typed Compute Config
+
+- `config-optional-simple-app` - `prisma.compute.ts` is not required to deploy a normal single app; use flags when there is no durable config.
+- `config-init-formalizer` - Generate a fresh config with `bunx @prisma/cli@latest init`: it detects the framework, pins name/framework/httpPort (plus entry for Bun/Hono), and offers the Project link. `--format json` writes a dependency-free `prisma.compute.json` instead. `init` refuses when any config already exists, never scaffolds code, and never deploys.
+- `config-use-prisma-compute-ts` - Put reusable deploy defaults in `prisma.compute.ts` with `defineComputeConfig`, not in `prisma.config.ts`.
+- `config-app-vs-apps` - Use `app` for a single deploy target and `apps` for monorepos or multi-app repos; define exactly one.
+- `config-monorepo-roots` - For monorepos, use `prisma.compute.ts` to declare app targets, roots, framework defaults, entrypoints, ports, and env inputs.
+- `config-targets` - In multi-app configs, `@prisma/cli app deploy web` selects the `apps.web` target. Without `[app]`, commands can infer the target from the current directory; otherwise deploy can run all targets while build/run require one.
+- `config-region-new-app-only` - A config `region` is only a default for newly created apps; deploys to existing apps keep the app's current region.
+- `config-custom-artifact` - Use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint` for prebuilt or custom-built artifacts.
+- `config-no-project-branch-secrets` - Do not commit Workspace, Project, Branch, production intent, service tokens, or secret values in `prisma.compute.ts`; keep those in flags, `.prisma/local.json`, env storage, or CI secrets. App-level defaults such as `region`, `root`, `framework`, `entry`, `httpPort`, and non-secret env file paths belong in config.
+- `config-flags-win` - Explicit deploy flags such as `--framework`, `--entry`, `--http-port`, `--region`, and `--env` override matching config values.
+
+### 6. Branch, Environment, and Database
+
+- `env-do-not-leak-secrets` - Never print full `DATABASE_URL`, service tokens, or secret values.
+- `env-deploy-loads-dotenv` - Generated deploy scripts may load env via `prisma.compute.ts` or `--env .env`; inspect the actual script/config before redeploy.
+- `env-migrations-separate` - Redeploy scripts do not run migrations or seed data. Run the appropriate Prisma database scripts separately.
+- `env-cli-token-name` - `@prisma/cli` uses `PRISMA_SERVICE_TOKEN` for service-token auth.
+- `env-branch-scope` - Branch deploys, branch env vars, and branch databases must use the same branch name; pass `--branch ` explicitly when targeting a preview branch.
+- `env-production-vs-preview` - Use `--role production` for production env, `--role preview` for preview template env, and `--branch ` for branch-specific overrides.
+- `env-db-explicit` - Keep database and env wiring explicit through database and project env commands; deploy examples should not add database setup, and deploys do not run migrations, seed data, or create one database per app automatically.
+
+### 7. Deploy Operations
+
+- `deploy-prod-intent` - Use `--prod --yes` only when the user intends a production deploy. The first production deploy of an App auto-promotes without `--prod`; the flag gates subsequent production-branch deploys.
+- `deploy-no-promote` - Use `app deploy --no-promote` for build-then-verify: it builds a candidate reachable at its own URL without touching the live deployment, promoted later with `app promote `.
+- `deploy-github-default-branch` - When a Compute app is connected to GitHub push-to-deploy, a merge to the default branch is the production deploy path; check deployment records or GitHub check runs instead of telling users to redeploy the merged PR branch or run a default-branch preview deploy.
+- `deploy-build-logs` - Use `@prisma/cli build logs ` for GitHub/Console build output. Use `app logs` for runtime deployment logs; the two ids are different.
+- `deploy-noninteractive-auth` - Non-interactive deploys need either the correct active stored OAuth workspace or a supported service token env var; never print the token.
+- `deploy-json-for-agents` - Use `--json --no-interactive` for scripts and agent-readable output.
+- `deploy-create-project` - Use `--create-project ` only when the user wants deploy to create and link a new project; it conflicts with `--project` and `PRISMA_PROJECT_ID`.
+- `deploy-ops-targets` - App show/open/logs/list-deploys/promote/rollback/remove and domain commands can also accept `[app]` targets from `prisma.compute.ts`.
+- `deploy-report-cli-bugs` - On `UNEXPECTED_ERROR` or an unresolvable failure, report it with the feedback command; see "Send Feedback and Report CLI Issues" above.
+
+### 8. SDK and API
+
+- `sdk-use-cli-first` - Prefer `@prisma/cli app deploy` for app workflows; use `create-prisma` only to scaffold a new app unless the user is building lower-level automation.
+- `sdk-result-handling` - `@prisma/compute-sdk` returns `Result` values; check `isOk()`/`isErr()` instead of relying on exceptions.
+- `sdk-snapshot-detection` - Use `detectComputeApp` for repository snapshots that are not checked out to disk; enumerate workspaces yourself and call it once per candidate app root.
+
+## Preferred Workflow
+
+1. Inspect the project: package manager, template/framework, `package.json` scripts, Prisma version, Prisma client location, `prisma.compute.ts`, and existing `compute:deploy`.
+2. Verify CLI help output for the package actually being used.
+3. Verify auth context before project/app mutations: `auth whoami --json`, and when multiple local sessions may exist, `auth workspace list --json`.
+4. Choose the path:
+ - existing app deploy: config-backed target when present, generated `compute:deploy`, or `@prisma/cli app build/run/deploy` flags
+ - new app scaffold: `create-prisma`, then generated `compute:deploy` or `@prisma/cli app deploy`
+ - low-level automation: `@prisma/compute-sdk` or Management API
+5. Check framework readiness plus host/port/env/runtime requirements, including project and branch scope.
+6. Run a local build or `app build` before deploying when feasible.
+7. Deploy with JSON output when automating, then request the public URL and summarize app URL, app id, deployment id, project id, workspace id, and follow-up steps.
+8. For GitHub/Console builds, inspect the `Prisma Compute Deploy` check run or `build logs ` before guessing why a build failed.
+
+## Avoid
+
+- Do not bury Compute deployment guidance in the generic `prisma-cli` skill.
+- Do not run `create-prisma` inside an existing app just to deploy it; use the generated `compute:deploy` script or `@prisma/cli app deploy`.
+- Do not tell users that every `create-prisma` template can auto-deploy.
+- Do not deploy with placeholder `DATABASE_URL` values.
+- Do not assume `next start` is the Compute runtime path; Next.js deploys need standalone output.
diff --git a/apps/backend/.agents/skills/prisma-compute/references/app-deploy-cli.md b/apps/backend/.agents/skills/prisma-compute/references/app-deploy-cli.md
new file mode 100644
index 0000000..0c472e0
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-compute/references/app-deploy-cli.md
@@ -0,0 +1,403 @@
+# Prisma Platform CLI App Deploy
+
+Use this reference for existing projects and for generated `compute:deploy` scripts.
+
+## Package and Command
+
+Compute app workflows are exposed through the Prisma Platform CLI package:
+
+```bash
+bunx @prisma/cli@latest --help
+bunx @prisma/cli@latest app --help
+bunx @prisma/cli@latest app deploy --help
+bunx @prisma/cli@latest build logs --help
+```
+
+The examples in help output may call the binary `prisma-cli`. When using package runners, prefer:
+
+```bash
+bunx @prisma/cli@latest app deploy
+npx @prisma/cli@latest app deploy
+pnpm dlx @prisma/cli@latest app deploy
+```
+
+## Agent Skill Installation
+
+`@prisma/cli` can install and refresh Prisma skills for local AI coding agents:
+
+```bash
+bunx @prisma/cli@latest agent install
+bunx @prisma/cli@latest agent install --skill prisma-compute
+bunx @prisma/cli@latest agent update
+bunx @prisma/cli@latest agent status --json
+```
+
+`agent install` and `agent update` shell out to `skills@latest add prisma/skills` through the detected package runner. Use them when the user wants Prisma's agent context installed or refreshed; they are not a deployment command.
+
+## Typed Compute Config
+
+`prisma.compute.ts` is optional for normal single-app deploys and useful for reusable defaults or multi-app targets. Read [`compute-config.md`](compute-config.md) for config shapes, target selection, precedence, and monorepo rules. This reference only shows how deploy commands consume those settings.
+
+## Auth and Project Binding
+
+Useful commands:
+
+```bash
+bunx @prisma/cli@latest auth login
+bunx @prisma/cli@latest auth whoami
+bunx @prisma/cli@latest project list --json
+bunx @prisma/cli@latest project show
+bunx @prisma/cli@latest project link
+```
+
+`@prisma/cli` can keep multiple local browser-login workspace sessions. Running `auth login` again for a different workspace should add/update that workspace session and make it active; it should not delete the existing workspace session. The active workspace pointer decides which stored OAuth workspace normal commands use.
+
+For agents, prefer this flow before project/app mutations:
+
+```bash
+bunx @prisma/cli@latest auth whoami --json
+bunx @prisma/cli@latest auth workspace list --json
+bunx @prisma/cli@latest auth workspace use
+```
+
+Use workspace ids from `auth workspace list --json` when possible. Names are friendlier for humans but can be ambiguous. Use `auth workspace use` with no argument for a human interactive picker; headless scripts should pass an id because no-argument `use` fails non-interactively when multiple local OAuth workspaces exist.
+
+If the active workspace is logged out or its refresh fails, the CLI intentionally does not auto-select another cached workspace. Choose the next workspace explicitly:
+
+Use `auth workspace list --json`, then `auth workspace use `.
+
+To clean up one local OAuth workspace without clearing every stored workspace session:
+
+```bash
+bunx @prisma/cli@latest auth workspace logout
+# equivalent:
+bunx @prisma/cli@latest auth logout --workspace
+```
+
+Plain `auth logout` clears all local OAuth workspace sessions. It does not unset `PRISMA_SERVICE_TOKEN`.
+
+For a new linked project:
+
+```bash
+bunx @prisma/cli@latest project create my-app --json
+```
+
+For non-interactive or CI work, `@prisma/cli` accepts a workspace service token through `PRISMA_SERVICE_TOKEN`. A non-empty service token takes precedence over stored browser-login credentials, so local OAuth workspace switching does not affect command execution while the env var is set. `auth workspace list --json` may still show local OAuth sessions, but they are not switchable until the service-token env var is unset. Verify auth with `auth whoami` and never print the token value.
+
+If `PRISMA_SERVICE_TOKEN` is set but empty, unset it or provide a real token. The CLI should fail instead of silently falling back to local OAuth credentials.
+
+Local auth storage is useful for debugging but should not be printed verbatim:
+
+- `PRISMA_COMPUTE_AUTH_FILE` can override the auth file path.
+- On macOS, the default OAuth credentials file is `~/Library/Application Support/prisma/auth.json`.
+- Workspace metadata and the active workspace pointer live beside it as `auth.context.json`.
+- Project pins live in `.prisma/local.json`.
+- Local CLI state such as selected app and known live deployment lives in `.prisma/cli/state.json`, rooted near `prisma.compute.ts` when a config is discovered.
+
+## Project, Branch, Database, and Env Scope
+
+Compute deploys resolve a target project, app, and branch. Be explicit when the user's intent is not the already linked default project/app:
+
+```bash
+bunx @prisma/cli@latest project show --json
+bunx @prisma/cli@latest app deploy --project proj_123 --app my-api --branch feature/login --json
+```
+
+If `prisma.compute.ts` defines a `name` or an `apps` key, that config can provide the app name. `--app` and `PRISMA_APP_ID` rank above the config value. `[app]` selects a target from `apps`:
+
+```bash
+bunx @prisma/cli@latest app deploy api --project proj_123 --branch feature/login --json
+```
+
+See [`compute-config.md`](compute-config.md) for no-argument target inference, deploy-all, and build/run target rules.
+
+Branch scope must line up across deploys, databases, and env vars:
+
+- `app deploy --branch ` creates a deployment for that branch.
+- `database create --branch ` creates a Prisma Postgres database for that branch scope.
+- `project env add/update/list/remove --branch ` manages branch-specific env overrides.
+- `project env add/update/list/remove --role production` manages production env.
+- `project env add/update/list/remove --role preview` manages preview-template env.
+
+Do not assume a local Git branch was used by the CLI unless the generated script or command output says so. If a user asks for `feature/login`, pass `--branch feature/login` consistently to app, database, and env commands.
+
+Promotion is a separate production action: `app promote ` rebuilds a deployment with production env vars. Do not treat a preview branch deploy as production promotion.
+
+## Deployment Story: GitHub vs CLI
+
+When a Compute app is connected to GitHub push-to-deploy, the default branch is the production deploy path. If a PR has been merged into `main` or another configured default branch, the natural answer is that the changes should appear in production after the production deployment completes; use CLI deploys for explicit manual deploys, local-source deploys, or repositories that are not using GitHub push-to-deploy.
+
+`app show`, `app list-deploys`, and `app logs` expose `--app`, `--project`, and for logs `--deployment`, not `--branch`. For branch debugging, capture the deployment id from deploy JSON and inspect that deployment or its logs.
+
+`app deploy --create-project ` creates and links a new Project before deploying. Use it only when the user wants a new Project. It conflicts with `--project` and `PRISMA_PROJECT_ID`, and `--yes` alone does not choose Project scope.
+
+`app deploy --region ` only applies when deploy creates a new app. Existing apps keep their current region. Use `prisma.compute.ts` `region` for a durable default, and use the flag only for one-off new-app placement.
+
+## Database and Env
+
+Create a Prisma Postgres database for the linked project:
+
+```bash
+bunx @prisma/cli@latest database create main --branch main --json
+```
+
+Manage project env vars:
+
+```bash
+bunx @prisma/cli@latest project env list
+bunx @prisma/cli@latest project env add --file .env --role production
+bunx @prisma/cli@latest project env add --file .env.preview --role preview
+bunx @prisma/cli@latest project env add DATABASE_URL=postgresql://... --branch feature/foo
+bunx @prisma/cli@latest project env update --file .env --role production
+bunx @prisma/cli@latest project env update DATABASE_URL=postgresql://... --branch feature/foo
+bunx @prisma/cli@latest project env list --branch feature/foo
+bunx @prisma/cli@latest project env remove STRIPE_KEY --role preview
+```
+
+`app deploy --env .env` loads environment variables from a file for the deployment. A config-backed deploy can instead load env through `prisma.compute.ts` `env`. Neither path is a migration command or seed command.
+
+Database setup is not part of `prisma.compute.ts`. Keep database intent explicit with `database create` and project env commands. Do not add database setup to deploy examples. Treat any generated connection URL as a one-time secret.
+
+Database and env guardrails:
+
+- Deploys do not run migrations, seed data, or schema push. Run the app's own Prisma database command after deploy setup when needed.
+- In deploy-all, every target on the same branch shares branch-scoped project env unless you assign app-specific env values yourself.
+- Existing database env values supplied through `--env DATABASE_URL=...`, `--env DIRECT_URL=...`, an env file, or project env should be treated as the source of truth.
+- Known non-PostgreSQL Prisma schema sources should not be wired to Prisma Postgres automatically.
+
+## Project Git, Branch, and Database Operations
+
+These commands are part of the same Platform CLI surface and often matter while preparing Compute deploys:
+
+```bash
+bunx @prisma/cli@latest branch list --json
+bunx @prisma/cli@latest git connect git@github.com:org/repo.git --project proj_123
+bunx @prisma/cli@latest git disconnect --project proj_123
+bunx @prisma/cli@latest database list --branch feature/foo --json
+bunx @prisma/cli@latest database show db_123 --json
+bunx @prisma/cli@latest database remove db_123 --confirm db_123
+bunx @prisma/cli@latest database connection list db_123 --json
+bunx @prisma/cli@latest database connection create db_123 --name readonly
+bunx @prisma/cli@latest database connection remove conn_123 --confirm conn_123
+bunx @prisma/cli@latest database connection rotate conn_123 --confirm conn_123
+bunx @prisma/cli@latest database usage db_123 --json
+bunx @prisma/cli@latest database backup list db_123 --json
+bunx @prisma/cli@latest database restore db_123 --backup bkp_123 --confirm db_123
+bunx @prisma/cli@latest project rename new-name --project proj_123
+bunx @prisma/cli@latest project transfer proj_123 --to-workspace wksp_456 --confirm proj_123
+bunx @prisma/cli@latest project remove proj_123 --confirm proj_123
+```
+
+Destructive and ownership-changing commands (`remove`, `restore`, `transfer`, `connection rotate`) require exact `--confirm `; `--yes` is not enough.
+
+Git integration connects a Project to a GitHub repository. Console-side GitHub import can create a Compute app and trigger push-to-deploy for the connected repository, including default-branch production deploys. The CLI `git connect` command is setup, not a local deploy command; use `app deploy` for explicit CLI deploys.
+
+For GitHub-driven deploys, inspect the Console/build-runner state, deployment records, build logs, or the `Prisma Compute Deploy` GitHub check run instead of assuming local CLI output exists. The build runner can perform branch-aware database/env wiring: a preview branch with a Prisma schema and no `DATABASE_URL` can get a branch-scoped preview database, while production can wire a missing `DATABASE_URL` template from an existing ready database. GitHub check runs are the guided feedback path; do not promise Vercel-style PR comments.
+
+Database and database-connection commands never print stored secret values in list/show output. `database create` and `database connection create` return a one-time connection URL; treat it as a secret, store it immediately in env if needed, and do not echo it back in summaries. Removal requires exact `--confirm `; `--yes` is not enough.
+
+## Build and Run Locally
+
+Before deploy, verify that the app can produce a Compute artifact:
+
+```bash
+bunx @prisma/cli@latest app build --build-type auto
+bunx @prisma/cli@latest app run --build-type auto --port 3000
+```
+
+For Bun/server entrypoints:
+
+```bash
+bunx @prisma/cli@latest app build --build-type bun --entry src/index.ts
+bunx @prisma/cli@latest app run --build-type bun --entry src/index.ts --port 8080
+```
+
+For NestJS, use `app build` to validate the Compute artifact and run the framework's own dev command locally:
+
+```bash
+bunx @prisma/cli@latest app build --build-type nestjs
+bun run dev
+```
+
+With a compute config, pass the target name instead of repeating framework/entry/port flags:
+
+```bash
+bunx @prisma/cli@latest app build api
+bunx @prisma/cli@latest app run api --port 8080
+```
+
+`app run --port` sets `PORT` for local development. It does not rewrite an app's explicit host binding, so a local run is not enough to prove the deployed server is reachable from ingress.
+
+`app run --build-type nestjs` is not supported. If a config-backed NestJS target is selected, run the Nest dev server directly instead.
+
+## Deploy
+
+Deploy with prompts:
+
+```bash
+bunx @prisma/cli@latest app deploy
+```
+
+Agent/script-friendly deploy (do not assume production; add `--prod --yes` only when the user intends a production deploy, and note the first production deploy of an App auto-promotes without `--prod`):
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --json \
+ --no-interactive \
+ --env .env
+```
+
+Build-then-verify path for CI: `--no-promote` builds a candidate deployment without changing the live one; it is reachable at its own candidate URL and promoted later with `app promote `:
+
+```bash
+bunx @prisma/cli@latest app deploy --no-promote --json --no-interactive
+```
+
+For preview branches, omit `--prod` unless the user explicitly intends a production deploy:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --branch feature/foo \
+ --json \
+ --no-interactive \
+ --env .env.preview
+```
+
+After a real deploy, verify the public deployment URL. Do not stop at "deploy succeeded" or a local `app run` check:
+
+```bash
+curl -i https://
+```
+
+If the deploy command returns JSON, parse the URL from the result and request that exact public URL. Do not accidentally test `localhost` or `127.0.0.1` instead of public ingress.
+
+Create/link a project during deploy:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --create-project my-app \
+ --prod \
+ --yes \
+ --env .env
+```
+
+Deploy with framework and port:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --framework hono \
+ --http-port 8080 \
+ --prod \
+ --yes \
+ --env .env
+```
+
+Deploy a newly created app in a specific region:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --app my-api \
+ --region us-west-1 \
+ --prod \
+ --yes \
+ --env .env
+```
+
+`--region` is a new-app placement hint. It does not move an existing app.
+
+Deploy a preview branch with framework and port:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --framework hono \
+ --branch feature/foo \
+ --http-port 8080 \
+ --json \
+ --no-interactive \
+ --env .env.preview
+```
+
+Bun-style app with explicit entrypoint:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --framework bun \
+ --entry src/index.ts \
+ --http-port 8080 \
+ --prod \
+ --yes \
+ --env .env
+```
+
+`--entry ` without `--framework` is treated as a Bun app deploy.
+
+Config-backed Bun-style app:
+
+```bash
+bunx @prisma/cli@latest app deploy api --prod --yes --env .env
+```
+
+Use config for stable app defaults, and flags for one-off project, branch, region, env, and production choices. Keep database setup in explicit database and project-env commands.
+
+## Operations
+
+Inspect and open:
+
+```bash
+bunx @prisma/cli@latest app show --json
+bunx @prisma/cli@latest app open
+```
+
+Deployments:
+
+```bash
+bunx @prisma/cli@latest app list-deploys --json
+bunx @prisma/cli@latest app show-deploy --json
+bunx @prisma/cli@latest app promote --yes
+bunx @prisma/cli@latest app rollback --to --yes
+bunx @prisma/cli@latest app remove --app my-api --yes
+```
+
+Logs:
+
+```bash
+bunx @prisma/cli@latest app logs
+bunx @prisma/cli@latest app logs --deployment
+bunx @prisma/cli@latest app logs --json
+```
+
+Build logs for GitHub/Console builds:
+
+```bash
+bunx @prisma/cli@latest build logs
+bunx @prisma/cli@latest build logs --follow
+bunx @prisma/cli@latest build logs --json
+```
+
+`build logs` streams build output keyed by a Build id from a GitHub/Console build or check run. It is separate from runtime `app logs`, which are keyed by the current app deployment or a deployment id.
+
+Domains:
+
+```bash
+bunx @prisma/cli@latest app domain add shop.example.com
+bunx @prisma/cli@latest app domain show shop.example.com
+bunx @prisma/cli@latest app domain wait shop.example.com --timeout 15m
+bunx @prisma/cli@latest app domain retry shop.example.com
+bunx @prisma/cli@latest app domain remove shop.example.com
+```
+
+Custom domain commands target production branch runtime. Do not use a preview branch for production domain setup.
+
+## Output Handling
+
+When `--json` is available, parse the JSON and summarize:
+
+- project id/name
+- branch name
+- app id/name
+- deployment id/status
+- build id when present
+- deployment URL
+- database id/name if one was created
+
+Do not print secret env var values.
diff --git a/apps/backend/.agents/skills/prisma-compute/references/compute-config.md b/apps/backend/.agents/skills/prisma-compute/references/compute-config.md
new file mode 100644
index 0000000..633a603
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-compute/references/compute-config.md
@@ -0,0 +1,222 @@
+# Prisma Compute Config
+
+Use this reference when creating or updating `prisma.compute.ts`, especially for monorepos, multi-app deploys, reusable framework defaults, env inputs, ports, entrypoints, or build settings.
+
+`prisma.compute.ts` is not required for every deploy. A simple app can deploy with `@prisma/cli app deploy --framework ... --entry ... --http-port ... --env ...`. The config file exists to make those app-level defaults typed and repeatable.
+
+For monorepos or multi-app repositories, use `prisma.compute.ts`: it is the practical way to tell Compute which app target lives at which `root` and which framework/entry/env defaults belong to each target.
+
+## Generating a Config with `init`
+
+Prefer `bunx @prisma/cli@latest init` over hand-writing a fresh single-app config. It detects the framework from the same registry deploy uses, pins `name`, `framework`, and `httpPort` (plus `entry` for Bun and Hono), previews every value with its source, offers the `@prisma/compute-sdk` devDependency for editor types, and offers the Project link. Useful flags: `--framework`, `--entry`, `--http-port`, `--name`, `--no-link`, `--json`.
+
+`--format json` writes a dependency-free static `prisma.compute.json` instead of the TypeScript config; a later explicit `init --format ts` converts it in place when the config needs to become programmatic. `init` fails with `INIT_CONFIG_EXISTS` when any compute config already exists, never scaffolds application code, and never deploys. Multi-app monorepo configs are still written by hand.
+
+## File Names and Discovery
+
+The canonical file is `prisma.compute.ts`. The loader also accepts:
+
+```text
+prisma.compute.mts
+prisma.compute.js
+prisma.compute.mjs
+prisma.compute.cjs
+prisma.compute.json
+```
+
+`prisma.compute.json` is the static, dependency-free variant of the same config; it is discovered and loaded like the others.
+
+Keep exactly one compute config file in a directory. If multiple names exist together, the CLI reports `COMPUTE_CONFIG_INVALID`.
+
+The CLI searches from the invocation directory up to the repository or workspace boundary. Boundaries include `.git`, `pnpm-workspace.yaml`, `bun.lock`, `bun.lockb`, or `package.json#workspaces`. Config-relative paths such as `root` and `env.file` resolve from the config file directory. `--env` flag paths still resolve from the invocation directory.
+
+When a config is discovered, its directory becomes the Compute project directory for local state: `.prisma/local.json` and `.prisma/cli/state.json` live beside that config, not necessarily inside the app root.
+
+## Basic Shape
+
+Import `defineComputeConfig` from `@prisma/compute-sdk/config`. The CLI aliases this helper when loading the config, so the command can evaluate the config without a local SDK install solely for runtime loading.
+
+```typescript
+import { defineComputeConfig } from "@prisma/compute-sdk/config";
+
+export default defineComputeConfig({
+ app: {
+ name: "api",
+ framework: "hono",
+ httpPort: 8080,
+ env: ".env",
+ },
+});
+```
+
+JavaScript configs can default-export a plain object, but prefer `prisma.compute.ts` for type checking.
+
+Define exactly one of:
+
+- `app` for a single deploy target
+- `apps` for a monorepo or multi-app repository
+
+Do not define both. Besides `app`/`apps`, the only other allowed top-level key is `region`: a project-level default region applied when deploy creates new apps, overridable per app and by `--region`.
+
+## App Fields
+
+Each app target accepts:
+
+| Field | Meaning |
+|-------|---------|
+| `name` | Deployed app name. Defaults to the `apps` key, then CLI inference. |
+| `region` | Compute region id used only when deploy creates a new app. Existing apps keep their current region. |
+| `root` | App directory relative to the config file. Defaults to the config directory. |
+| `framework` | Deploy framework: `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, or `bun`. |
+| `entry` | Entrypoint path for Bun/Hono-style deploys, relative to the app root. |
+| `httpPort` | Deployed HTTP port. Use this for fixed-port apps. |
+| `env` | Dotenv file path string, or `{ file, vars }`. Paths resolve from the config directory. |
+| `build` | `{ command, outputDirectory, entrypoint }`. Present means the config owns build settings for that target. |
+
+`env` examples:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "nextjs",
+ env: {
+ file: [".env", ".env.production"],
+ vars: {
+ NODE_ENV: "production",
+ },
+ },
+ },
+});
+```
+
+Do not put secrets directly in committed `vars`. Keep secret values in platform env, CI secrets, or dotenv files that are intentionally managed outside version control.
+
+`build` examples:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "nextjs",
+ build: {
+ command: "pnpm build",
+ outputDirectory: ".next/standalone",
+ },
+ },
+});
+```
+
+Use `command: null` to skip the build step only when the app root already contains the deployable artifact.
+
+For a custom or prebuilt artifact, make the deploy target explicit:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "custom",
+ build: {
+ command: "npm run build",
+ outputDirectory: "build",
+ entrypoint: "handler.js",
+ },
+ },
+});
+```
+
+`build.entrypoint` is relative to `build.outputDirectory` when an output directory is set. For Bun/Hono configs without an output directory, an entrypoint-backed build can supply the source entrypoint. Do not set both `entry` and `build.entrypoint` unless they describe the same file.
+
+A config `build` block is accepted for every supported framework: the config-backed build types are `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun` (`hono` builds through the `bun` strategy). Only `custom` requires one (`build.outputDirectory` and `build.entrypoint`); for the others it overrides inferred build settings.
+
+## Monorepos and Multi-App Repos
+
+For monorepos, put `prisma.compute.ts` at the repo or workspace root and use `apps`. This keeps project binding and local `.prisma/` state at the repo root while each app builds from its own `root`.
+
+```typescript
+import { defineComputeConfig } from "@prisma/compute-sdk/config";
+
+export default defineComputeConfig({
+ apps: {
+ web: {
+ root: "apps/web",
+ framework: "nextjs",
+ env: "apps/web/.env",
+ },
+ api: {
+ root: "apps/api",
+ framework: "hono",
+ entry: "src/index.ts",
+ httpPort: 8080,
+ env: {
+ file: "apps/api/.env",
+ vars: {
+ LOG_LEVEL: "info",
+ },
+ },
+ },
+ frontend: {
+ root: "apps/frontend",
+ framework: "custom",
+ build: {
+ command: "pnpm --filter frontend build",
+ outputDirectory: "dist/server",
+ entrypoint: "index.mjs",
+ },
+ },
+ },
+});
+```
+
+Target selection:
+
+```bash
+bunx @prisma/cli@latest app deploy web
+bunx @prisma/cli@latest app deploy api
+bunx @prisma/cli@latest app build api
+bunx @prisma/cli@latest app run api --port 8080
+```
+
+If no `[app]` argument is passed, commands can infer the target from the invocation directory when it is inside a configured `root`. The deepest matching root wins. If no target is inferred from a multi-app config, a bare deploy can deploy all targets in declaration order:
+
+```bash
+bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive
+```
+
+Deploy-all rejects per-app overrides such as `--app`, `--framework`, `--entry`, `--http-port`, `--region`, `--env`, and `PRISMA_APP_ID`. Project, branch, production, and confirmation flags still apply to the whole run. Keep database setup in explicit database and project-env commands.
+
+`app build` and `app run` still need one target in multi-app configs because a local build/run command cannot operate N apps at once.
+
+Additional target rules:
+
+- A single-entry `apps` map can deploy its only target without an argument.
+- With a single `app` config, `[app]` is accepted only when it equals the configured `name`.
+- `[app]` without any compute config file is a usage error.
+
+## Precedence
+
+Explicit flags win over config values:
+
+- `--framework` overrides `framework`
+- `--entry` overrides `entry`
+- `--http-port` overrides `httpPort`
+- `--region` overrides `region`
+- any `--env` flag replaces all config env inputs
+- `--app` and `PRISMA_APP_ID` rank above config app names
+
+`region` is not an app selector. Config `region` and `--region` are only used when deploy creates a new app. If the selected app already exists, deploy keeps that app's existing region.
+
+`prisma.compute.ts` never selects Workspace, Project, Branch, or production intent. Keep those in CLI flags, environment variables, `.prisma/local.json`, or CI configuration:
+
+```bash
+bunx @prisma/cli@latest app deploy api \
+ --project proj_123 \
+ --branch feature/foo \
+ --prod \
+ --yes
+```
+
+## Database Scope
+
+The config does not declare databases. Keep database intent in `database create`, project env commands, or external automation. Read [`app-deploy-cli.md`](app-deploy-cli.md) for deploy-all, migration, and env-var guardrails.
+
+## Relationship to `prisma.config.ts`
+
+Do not put Compute deploy defaults in `prisma.config.ts`. Prisma ORM uses `prisma.config.ts`, while Compute uses `prisma.compute.ts`.
diff --git a/apps/backend/.agents/skills/prisma-compute/references/create-prisma.md b/apps/backend/.agents/skills/prisma-compute/references/create-prisma.md
new file mode 100644
index 0000000..ae09f92
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-compute/references/create-prisma.md
@@ -0,0 +1,117 @@
+# create-prisma Compute Flow
+
+Use this reference when creating a new app with Prisma and optionally deploying it to Prisma Compute.
+
+Do not use `create-prisma` as the deploy path for an existing app. For existing projects, use the generated `compute:deploy` script when present, or call `bunx @prisma/cli@latest app deploy` directly.
+
+## Reference
+
+Useful scaffold checks:
+
+```bash
+bunx create-prisma@latest --help
+bunx create-prisma@latest --version
+```
+
+Use `create-prisma@latest` for new-project scaffolding.
+
+## Supported Templates
+
+`create-prisma@latest` scaffolds `hono`, `elysia`, `nest`, `next`, `svelte`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`.
+
+Integrated `--deploy` support applies to `hono`, `elysia`, `nest`, `next`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`. For `turborepo`, the generated config target is usually `api`.
+
+The scaffold template name is `nest`, but the Compute deploy framework/config key is `nestjs`.
+
+`svelte` is scaffold-only for Compute because `@prisma/cli app deploy --framework` has no `svelte` key.
+
+## Basic Commands
+
+Interactive creation:
+
+```bash
+bunx create-prisma@latest
+```
+
+Non-interactive scaffold only:
+
+```bash
+bunx create-prisma@latest \
+ --name my-api \
+ --template hono \
+ --provider postgresql \
+ --no-install \
+ --no-generate \
+ --no-migrate-and-seed \
+ --no-deploy
+```
+
+Create and deploy a supported template:
+
+```bash
+bunx create-prisma@latest \
+ --name my-api \
+ --template hono \
+ --provider postgresql \
+ --deploy
+```
+
+## PostgreSQL and Database Behavior
+
+With PostgreSQL, no explicit `--database-url`, and no `--no-prisma-postgres`, the Compute flow can create:
+
+- a Prisma Compute project
+- a `main` Prisma Postgres database on the `main` branch
+- a `.env` file containing `DATABASE_URL`
+- an initial Compute deployment with env vars loaded from `.env`
+
+`create-prisma` is the new-project path. If the user needs a later preview branch deploy, use the generated `compute:deploy` script or `@prisma/cli app deploy --branch ` after the app exists. Keep branch names aligned across `app deploy --branch`, `database create --branch`, and `project env ... --branch`.
+
+For unattended local tests, pass `--no-prisma-postgres` unless you intentionally want provisioning:
+
+```bash
+bunx create-prisma@latest \
+ --name smoke-app \
+ --template hono \
+ --provider postgresql \
+ --no-prisma-postgres \
+ --database-url "postgresql://USER:PASSWORD@HOST:PORT/DB" \
+ --no-deploy
+```
+
+Do not deploy placeholder database URLs. If `DATABASE_URL` came from a placeholder default, omit it from deploy env and ask the user for a real production database.
+
+## Generated Deploy Script
+
+When the deploy flow is selected, `create-prisma` can add:
+
+```json
+{
+ "scripts": {
+ "compute:deploy": "bunx @prisma/cli@latest app deploy --prod --yes ..."
+ }
+}
+```
+
+Use the actual generated script from `package.json`; do not reconstruct it from memory. The script redeploys app code using generated flags and/or `prisma.compute.ts`. It does not create a new project, create a new database, run migrations, or seed data. If a scaffolded project does not have `compute:deploy`, use `@prisma/cli app deploy` directly.
+
+Inspect the generated `package.json`, `prisma.compute.ts`, and README before editing deploy behavior.
+
+## Generated Files to Preserve
+
+Preserve generated framework runtime files and `prisma.compute.ts` unless you are intentionally changing the deploy target. For framework-specific deploy/runtime details, read [`frameworks.md`](frameworks.md).
+
+All Prisma 7 scaffolds:
+
+- use `prisma.config.ts`
+- load `dotenv/config` where the runtime supports it
+- generate Prisma Client into a template-local path such as `src/generated/prisma`
+- use `@prisma/adapter-pg` with a `DATABASE_URL` connection string for PostgreSQL
+
+## Addon Notes
+
+`create-prisma` supports `--skills`, `--mcp`, and `--extension`. Those are separate from Compute deployment. Do not imply that enabling skills or MCP deploys the app.
+
+## Failure Handling
+
+If `--deploy` is explicit and setup cannot authenticate, cannot run the Platform CLI, or cannot complete the integrated deploy, report that deploy failed and keep the scaffolded project. Do not delete the user's files.
diff --git a/apps/backend/.agents/skills/prisma-compute/references/frameworks.md b/apps/backend/.agents/skills/prisma-compute/references/frameworks.md
new file mode 100644
index 0000000..915cf17
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-compute/references/frameworks.md
@@ -0,0 +1,382 @@
+# Prisma Compute Framework Readiness
+
+Use this reference when deciding whether and how an app can deploy to Prisma Compute.
+
+## CLI-First Model
+
+Treat `@prisma/cli app deploy` as the deployment surface. Treat `create-prisma` as a new-project scaffold that can generate useful defaults and, for some templates, a `compute:deploy` script.
+
+Compute deploy supports these framework keys:
+
+```text
+nextjs
+nuxt
+astro
+hono
+nestjs
+tanstack-start
+custom
+bun
+```
+
+Auto-detection:
+
+- Next.js: `next.config.*` or `next` dependency
+- Nuxt: `nuxt.config.*` or `nuxt` dependency
+- Astro: `astro.config.*` or `astro` dependency
+- Hono: `hono` dependency
+- NestJS: `nest-cli.json` or `@nestjs/core` dependency
+- TanStack Start: `@tanstack/react-start` or `@tanstack/solid-start`
+- Custom artifact: explicit `framework: "custom"` plus `build.outputDirectory` and `build.entrypoint` in `prisma.compute.ts`
+- Bun: explicit `--entry ` or `--framework bun`
+
+If detection is ambiguous, set `framework` in `prisma.compute.ts` or pass a supported `--framework` value. If the app is a source-level plain server, use `framework: "bun"` plus `entry`, or pass `--framework bun --entry `, after verifying the server entrypoint. If the app already produces a runnable Node artifact, use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint`.
+
+## CLI Matrix
+
+| App shape | Deploy command shape | Auto-detected | Required output/entry | Notes |
+|-----------|----------------------|---------------|-----------------------|-------|
+| Next.js | `--framework nextjs` | Yes | standalone `server.js` output | Requires `output: "standalone"` |
+| Nuxt | `--framework nuxt` | Yes | `.output/server/index.mjs` | Framework strategy supplies build defaults; a config `build` block is optional |
+| Astro | `--framework astro` | Yes | standalone Node server artifact | Framework strategy supplies build defaults; a config `build` block is optional |
+| Hono | `--framework hono` | Yes | Bun entry from `main`, `module`, `--entry`, or `src/index.ts` | Usually fixed port `8080` in generated config/scripts |
+| NestJS | `--framework nestjs` | Yes | NestJS server artifact | Omit host or bind to `0.0.0.0`; a config `build` block is optional |
+| TanStack Start | `--framework tanstack-start` | Yes | `.output/server/index.mjs` | Requires Nitro node output |
+| Custom artifact | config-backed `framework: "custom"` | No | configured `build.outputDirectory` and `build.entrypoint` | Use for prebuilt/custom-built Node artifacts |
+| Bun / plain server | `--framework bun --entry ` | With explicit entry | server entrypoint | Use for Elysia and custom HTTP servers |
+| Elysia | `--framework bun --entry src/index.ts` | No dedicated deploy key | Bun entrypoint | Preserve port/host handling |
+| SvelteKit | No deploy framework key | No | Node adapter/prebuilt artifact | Do not deploy `vite preview` |
+| Turborepo | Deploy concrete app targets | No | app-specific entry/output | Prefer `prisma.compute.ts` with `apps` |
+
+`app build --build-type` uses the framework build type. Build types include `auto`, `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun`.
+
+`app run --build-type` is local-dev oriented and supports `auto`, `bun`, and `nextjs`. It streams the local dev server and is not proof that the deployed app is reachable through public ingress.
+
+`prisma.compute.ts` can set framework, entrypoint, HTTP port, env inputs, app root, region, and build settings. A config `build` block is accepted for every supported framework; all build types are config-backed (`nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, `bun`; `hono` builds through the `bun` strategy). For Nuxt, Astro, and NestJS the framework strategy supplies the default build command and output, so a `build` block is optional and normally unnecessary, but it overrides those defaults when present. Only `custom` requires one.
+
+Config snippets below assume:
+
+```typescript
+import { defineComputeConfig } from "@prisma/compute-sdk/config";
+```
+
+## Universal Runtime Requirements
+
+Compute needs a server process:
+
+- It must listen on the deployed HTTP port. `@prisma/cli app deploy` defaults to the framework's default HTTP port (3000 for most frameworks, 4321 for Astro) unless `--http-port` is passed.
+- It must bind on all interfaces. Do not hard-code `localhost` or `127.0.0.1` for a deployed server; use `0.0.0.0`, `server.host: true`, or the framework equivalent.
+- It must have a deployable entrypoint or recognized framework output.
+- It must not rely on a preview-only command such as `vite preview`.
+- It must receive env vars through `--env`, project env, branch env, or external automation.
+
+Check host and port together. A listener on the right port but bound to loopback can appear ready while public ingress cannot reach it.
+
+## Next.js
+
+Deploy shape:
+
+```bash
+bunx @prisma/cli@latest app deploy --framework nextjs --env .env
+```
+
+`next.config.ts` must include standalone output:
+
+```typescript
+import type { NextConfig } from "next"
+
+const nextConfig: NextConfig = {
+ output: "standalone",
+}
+
+export default nextConfig
+```
+
+Do not pass `--entry` with `nextjs`; the CLI derives the runtime entrypoint from framework build output.
+
+Do not set `HOSTNAME=localhost` or `HOSTNAME=127.0.0.1` in deploy env. If the standalone server host is overridden, use `0.0.0.0`.
+
+## Hono
+
+Deploy shape:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --framework hono \
+ --http-port 8080 \
+ --env .env
+```
+
+Config shape:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "hono",
+ entry: "src/index.ts",
+ httpPort: 8080,
+ env: ".env",
+ },
+});
+```
+
+Project expectations:
+
+- `package.json` has `main` or `module` pointing at the entrypoint, or deploy passes `--entry src/index.ts`
+- server uses `@hono/node-server`
+- code reads `process.env.PORT` and defaults to the same port used by `--http-port`
+- code does not set `hostname` to `localhost` or `127.0.0.1`; if hostname is set explicitly, use `0.0.0.0`
+
+Example runtime shape:
+
+```typescript
+const rawPort = (process.env.PORT ?? "").trim()
+const parsedPort = rawPort.length > 0 ? Number(rawPort) : Number.NaN
+const port = Number.isInteger(parsedPort) ? parsedPort : 8080
+serve({ fetch: app.fetch, port })
+```
+
+## NestJS
+
+Deploy shape:
+
+```bash
+bunx @prisma/cli@latest app deploy --framework nestjs --env .env
+```
+
+Config shape:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "nestjs",
+ env: ".env",
+ },
+});
+```
+
+Project expectations:
+
+- detection uses `nest-cli.json` or the `@nestjs/core` dependency; pass `--framework nestjs` when neither signal is present
+- `src/main.ts` or the compiled runtime must start an HTTP server
+- read `process.env.PORT` and default to the same port used by `--http-port`
+- omit the host argument in `app.listen(port)` or pass `"0.0.0.0"`; do not pass `"localhost"` or `"127.0.0.1"`
+- use `app build --build-type nestjs` for a Compute artifact check; `app run --build-type nestjs` is not supported, so use the Nest dev server locally
+
+Example runtime shape:
+
+```typescript
+const port = Number(process.env.PORT ?? "3000")
+await app.listen(port)
+```
+
+## TanStack Start
+
+Deploy shape:
+
+```bash
+bunx @prisma/cli@latest app deploy --framework tanstack-start --env .env
+```
+
+Expected `vite.config.ts` shape:
+
+```typescript
+import { defineConfig } from "vite"
+import viteReact from "@vitejs/plugin-react"
+import { tanstackStart } from "@tanstack/react-start/plugin/vite"
+import { nitro } from "nitro/vite"
+
+export default defineConfig({
+ plugins: [tanstackStart(), nitro(), viteReact()],
+})
+```
+
+Preserve these details:
+
+- keep `nitro` in `dependencies`
+- keep `import { nitro } from "nitro/vite"`
+- keep `nitro()` in the Vite plugin list
+- keep the React Vite plugin after `tanstackStart()`
+- keep Nitro on its default node server preset; do not switch to edge, static, Cloudflare, or another non-Node preset for Compute
+
+The build command is `vite build`. The build must produce `.output/server/index.mjs`, and the production start shape is:
+
+```json
+{
+ "scripts": {
+ "build": "vite build",
+ "start": "node .output/server/index.mjs"
+ }
+}
+```
+
+Do not deploy TanStack Start as a Bun entrypoint such as `src/router.tsx`. If `.output/server/index.mjs` is missing, fix the TanStack/Nitro build path.
+
+Make sure Nitro does not bind only to localhost in deployment. If host env/config is customized, use the framework's all-interface host setting rather than `localhost`.
+
+## Nuxt
+
+Deploy shape:
+
+```bash
+bunx @prisma/cli@latest app deploy --framework nuxt --env .env
+```
+
+Config shape:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "nuxt",
+ env: ".env",
+ },
+});
+```
+
+Nuxt uses Nitro output at `.output/server/index.mjs`. Keep the Nitro preset compatible with a Node server runtime.
+
+## Astro
+
+Deploy shape:
+
+```bash
+bunx @prisma/cli@latest app deploy --framework astro --env .env
+```
+
+Config shape:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "astro",
+ httpPort: 4321,
+ env: ".env",
+ },
+});
+```
+
+Astro Compute-style server output usually needs:
+
+```javascript
+import { defineConfig } from "astro/config"
+import node from "@astrojs/node"
+
+export default defineConfig({
+ output: "server",
+ adapter: node({ mode: "standalone" }),
+ server: { host: true },
+})
+```
+
+## Bun, Elysia, and Plain Source Servers
+
+Use the Bun deploy key for app shapes without a dedicated `--framework` value:
+
+```bash
+bunx @prisma/cli@latest app deploy \
+ --framework bun \
+ --entry src/index.ts \
+ --http-port 8080 \
+ --env .env
+```
+
+`app deploy` also treats `--entry ` without `--framework` as a Bun app deploy.
+
+Requirements:
+
+- pass `--entry` unless `package.json` `main` or `module` points at the runtime entrypoint
+- ensure the entrypoint starts an HTTP server, not only exports handlers
+- read `process.env.PORT` or align `--http-port` with the fixed listener port
+- bind on all interfaces
+
+Elysia example:
+
+```typescript
+const port = Number(process.env.PORT ?? "8080")
+app.listen({ port, hostname: "0.0.0.0" })
+```
+
+## Custom Build Artifacts
+
+Use `framework: "custom"` when the app is already built, or when a custom command produces a runnable Node artifact that Compute should stage as-is:
+
+```typescript
+export default defineComputeConfig({
+ app: {
+ framework: "custom",
+ build: {
+ command: "npm run build",
+ outputDirectory: "build",
+ entrypoint: "handler.js",
+ },
+ httpPort: 3000,
+ env: ".env",
+ },
+});
+```
+
+Requirements:
+
+- set both `build.outputDirectory` and `build.entrypoint`
+- make `build.entrypoint` relative to `build.outputDirectory`
+- ensure the artifact starts an HTTP server and binds on all interfaces
+- use `command: null` only when the output directory already contains the deployable artifact
+
+## SvelteKit and Other Frameworks
+
+`@prisma/cli app deploy --framework` has no `svelte` framework key. Do not claim SvelteKit is directly deployable with that name.
+
+For frameworks without a dedicated deploy key, use one of these paths:
+
+- produce a Node server artifact and deploy with config-backed `framework: "custom"`, or through a supported prebuilt/SDK flow
+- if the app has a plain Node/Bun server entrypoint, deploy that entrypoint through `--framework bun --entry `
+
+SvelteKit should use a Node adapter or another production server artifact. Do not use `vite preview` as the deployed runtime.
+
+## Turborepo
+
+Deploy concrete app packages, not the monorepo root by default. Prefer `prisma.compute.ts` at the repo root with one `apps` entry per deploy target.
+
+Checklist:
+
+- choose the app directory, such as `apps/api`
+- run the workspace build from the correct root/package
+- pass the app package's runtime entrypoint or framework
+- pass the correct env file, which may live outside the app package
+- keep branch env/database scope aligned with the deployed app
+
+Example config:
+
+```typescript
+export default defineComputeConfig({
+ apps: {
+ web: { root: "apps/web", framework: "nextjs" },
+ api: {
+ root: "apps/api",
+ framework: "bun",
+ entry: "src/index.ts",
+ httpPort: 3000,
+ env: "packages/db/.env",
+ },
+ },
+});
+```
+
+Deploy one target:
+
+```bash
+bunx @prisma/cli@latest app deploy api --branch feature/foo --json
+```
+
+Flag-only shape after confirming output paths:
+
+```bash
+bun run build
+bunx @prisma/cli@latest app deploy \
+ --framework bun \
+ --entry apps/api/dist/src/index.js \
+ --http-port 3000 \
+ --env packages/db/.env
+```
+
+Verify the actual output path before using this command.
diff --git a/apps/backend/.agents/skills/prisma-compute/references/sdk-api.md b/apps/backend/.agents/skills/prisma-compute/references/sdk-api.md
new file mode 100644
index 0000000..290f743
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-compute/references/sdk-api.md
@@ -0,0 +1,167 @@
+# SDK and API Automation
+
+Use this reference when building automation rather than using `create-prisma` or `@prisma/cli app deploy`.
+
+## Prefer the CLI for App Workflows
+
+For normal app deployment:
+
+1. Use generated `compute:deploy` when present.
+2. Otherwise use `@prisma/cli app build/run/deploy`.
+3. Use SDK/API only for custom automation, platform integrations, or tool builders.
+
+## Compute SDK
+
+Install:
+
+```bash
+npm install @prisma/compute-sdk @prisma/management-api-sdk
+```
+
+Config helper:
+
+```typescript
+import { defineComputeConfig } from "@prisma/compute-sdk/config";
+```
+
+Use this import in `prisma.compute.ts` for type checking. The helper is an identity function; the CLI loader aliases the import when it evaluates config files, so a user project does not need the SDK solely to load a Compute config.
+
+Create an authenticated Management API client:
+
+```typescript
+import { createManagementApiClient } from "@prisma/management-api-sdk"
+
+const apiClient = createManagementApiClient({
+ token: process.env.PRISMA_API_TOKEN,
+})
+```
+
+Token naming differs by surface. `@prisma/cli app ...` uses `PRISMA_SERVICE_TOKEN` for non-interactive service-token auth. The SDK examples here use `PRISMA_API_TOKEN` as an application convention for passing a token into `createManagementApiClient`; the SDK itself only receives the `token` string.
+
+Deploy a prebuilt artifact:
+
+```typescript
+import { ComputeClient, PreBuilt } from "@prisma/compute-sdk"
+
+const compute = new ComputeClient(apiClient)
+const databaseUrl = process.env.DATABASE_URL
+if (!databaseUrl) throw new Error("DATABASE_URL is required")
+
+const result = await compute.deploy({
+ strategy: new PreBuilt({
+ appPath: "./dist",
+ entrypoint: "index.js",
+ }),
+ projectId: "proj_abc",
+ appName: "my-app",
+ // region: "us-east-1", // optional: explicit placement for a new app
+ envVars: { DATABASE_URL: databaseUrl },
+ portMapping: { http: 3000 },
+})
+
+if (result.isOk()) {
+ console.log(result.value.deploymentEndpointDomain)
+} else {
+ console.error(result.error.message)
+}
+```
+
+SDK methods return `Result`. Check `isOk()` or `isErr()` instead of assuming errors throw. Deploy results expose app/deployment vocabulary including `appId`, `appName`, `projectId`, `region`, `deploymentId`, `deploymentEndpointDomain`, `appEndpointDomain`, `promoted`, `previousDeploymentId`, `previousDeploymentAction`, and `resolvedConfig`.
+
+## SDK Build Strategies
+
+Project Compute SDK strategies:
+
+- `AutoBuild`: tries supported framework strategies such as Next.js, Nuxt, Astro, NestJS, TanStack Start, then Bun
+- `NextjsBuild`: requires standalone output and returns `server.js`
+- `NuxtBuild`: expects `.output/server/index.mjs`
+- `AstroBuild`: expects `dist/server/entry.mjs`
+- `NestjsBuild`: builds a NestJS HTTP server artifact
+- `TanstackStartBuild`: runs `vite build` and expects a Nitro node server at `.output/server/index.mjs`; keep `tanstackStart()` and `nitro()` in Vite config
+- `CustomBuild`: runs optional configured build settings and stages a configured artifact entrypoint
+- `BunBuild`: runs `bun build` and needs an explicit entrypoint or `package.json` `main`
+- `PreBuilt`: uses an existing artifact directory and relative entrypoint
+
+## Regions
+
+Known SDK region ids:
+
+```text
+us-east-1
+us-west-1
+eu-west-3
+eu-central-1
+ap-northeast-1
+ap-southeast-1
+```
+
+Use `--region` in `@prisma/cli app deploy` or `region` in SDK deploy input only when creating a new Compute app. Existing apps keep their current region.
+
+`region` is optional on `deploy` and `createApp`. Omit it to use the Project/platform default when creating an app; do not hard-code a region unless placement is an application requirement.
+
+## Repository-snapshot detection
+
+Tooling that already has an in-memory repository tree can detect a deployable app without checking files out:
+
+```typescript
+import { detectComputeApp } from '@prisma/compute-sdk/config'
+
+const detected = detectComputeApp({
+ root: 'apps/api',
+ manifest: {
+ main: 'src/index.ts',
+ scripts: { start: 'bun src/index.ts' },
+ dependencies: { hono: '^4' },
+ },
+ filePaths: ['apps/api/package.json', 'apps/api/src/index.ts'],
+})
+```
+
+The result contains `framework`, `frameworkName`, `buildType`, `httpPort`, `entrypoint`, and detection `evidence`, or `null` when nothing is deployable. Paths are repository-relative and unsafe absolute/parent-traversal entrypoints are rejected.
+
+The helper detects one app root. A monorepo consumer must enumerate workspaces and call it once per candidate. Detection reads `dependencies` and `devDependencies` (not peer dependencies), recognizes config files and framework packages, and can infer Bun-backed servers from valid `start`/`serve` script entrypoints.
+
+## Management API Concepts
+
+Compute resources map roughly to:
+
+- Project: parent container
+- Branch: production or preview scope for env resolution and database/env attachment
+- App: stable app endpoint and branch attachment
+- Deployment: build artifact plus runtime status and preview URL
+
+Low-level public routes use App/Deployment names:
+
+- list/create apps under a project with `/v1/apps`
+- get/update/delete an app
+- create/list deployments for an app
+- get/start/stop/delete deployments with `/v1/deployments/:deploymentId`
+- promote or roll back an app using `deploymentId`
+- stream logs with `/v1/deployments/:deploymentId/logs`
+- manage custom domains
+
+Internal compatibility aliases may still appear in code. Prefer App/Deployment names in new docs, skills, and automation.
+
+Environment variables are not embedded directly in the low-level deployment create payload. The attached branch's role selects their scope: a preview branch resolves branch-scoped vars, while a production branch (or no branch) resolves project-scoped production vars. Use project/environment-variable APIs or CLI env commands to write env vars first, and keep the branch name consistent across app creation, database creation, and env writes.
+
+When using the CLI alongside SDK automation:
+
+```bash
+bunx @prisma/cli@latest project env add --file .env.preview --branch feature/foo
+bunx @prisma/cli@latest database create preview-db --branch feature/foo --json
+bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive
+```
+
+Production promotion is not just "the same branch with another label"; `app promote ` rebuilds with production env vars.
+
+## Secrets and Redaction
+
+Management API deployment inspection exposes env var names with redacted values. Treat any value like `[redacted]` as a marker, not as the deployed value.
+
+Do not log:
+
+- service tokens
+- OAuth tokens
+- full database URLs
+- env var values
+- pre-signed upload URLs
diff --git a/apps/backend/.agents/skills/prisma-compute/references/troubleshooting.md b/apps/backend/.agents/skills/prisma-compute/references/troubleshooting.md
new file mode 100644
index 0000000..0489989
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-compute/references/troubleshooting.md
@@ -0,0 +1,477 @@
+# Troubleshooting Prisma Compute
+
+Use this reference when setup, build, deploy, env, or runtime behavior fails.
+
+## First Checks
+
+Run:
+
+```bash
+bunx @prisma/cli@latest --help
+bunx @prisma/cli@latest app deploy --help
+bunx @prisma/cli@latest auth whoami
+bunx @prisma/cli@latest auth workspace list --json
+```
+
+Then inspect:
+
+```bash
+pwd
+cat package.json
+find .. -maxdepth 3 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print
+test -f .env && sed -n 's/=.*/=/p' .env
+```
+
+Do not print unredacted secrets.
+
+## `prisma.compute.ts` Not Picked Up
+
+This only matters when the project is supposed to use a config-backed deploy. A simple app without `prisma.compute.ts` can still deploy with explicit `app deploy` flags.
+
+Symptoms:
+
+- deploy ignores the expected framework, entrypoint, port, env file, or app root
+- a monorepo target such as `api` is not recognized
+- local state appears in the wrong `.prisma/` directory
+
+Check:
+
+```bash
+pwd
+find .. -maxdepth 4 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print
+bunx @prisma/cli@latest app deploy --help
+```
+
+Fix:
+
+- keep exactly one compute config file in the directory where it lives
+- put repo-wide or monorepo config at the repository/workspace root
+- run commands from inside the repo or workspace boundary so discovery can walk up to the config
+- use `[app]` targets from the `apps` keys, such as `bunx @prisma/cli@latest app deploy api`
+- remember that config-relative paths such as `root` and `env.file` resolve from the config file directory
+
+## Compute Config Invalid
+
+Symptoms:
+
+- `COMPUTE_CONFIG_INVALID`
+- `COMPUTE_CONFIG_TARGET_REQUIRED`
+- `COMPUTE_CONFIG_TARGET_UNKNOWN`
+- "Multiple compute config files found"
+
+Fix:
+
+- export `defineComputeConfig({ app: ... })` or `defineComputeConfig({ apps: ... })`
+- define exactly one of `app` or `apps`
+- remove unknown top-level keys
+- pass a target for multi-app build/run commands, such as `app build web`
+- pass an existing `apps` key for multi-app deploys, such as `app deploy api`
+- for `nuxt`, `astro`, and `nestjs`, prefer strategy defaults unless a custom `build` override is intentional; current configs allow the override
+- for `framework: "custom"`, set both `build.outputDirectory` and `build.entrypoint`
+- when `build.outputDirectory` is set for a configurable framework, also set `build.entrypoint` if the framework needs a configured runtime entrypoint
+
+Minimal recovery config:
+
+```typescript
+import { defineComputeConfig } from "@prisma/compute-sdk/config";
+
+export default defineComputeConfig({
+ app: {
+ framework: "hono",
+ entry: "src/index.ts",
+ httpPort: 8080,
+ },
+});
+```
+
+## `create-prisma --yes` Did Not Deploy
+
+`--yes` skips prompts and does not opt into deploy. Pass `--deploy` explicitly:
+
+```bash
+bunx create-prisma@latest --name my-api --template hono --provider postgresql --deploy
+```
+
+If the integrated deploy cannot complete, scaffold succeeds but deploy should be reported as failed.
+
+## Accidental Prisma Postgres Provisioning
+
+With PostgreSQL, no `--database-url`, and no `--no-prisma-postgres`, setup can provision Prisma Postgres. For local smoke tests, pass:
+
+```bash
+--no-prisma-postgres --database-url "postgresql://USER:PASSWORD@HOST:PORT/DB"
+```
+
+Use a disposable real database URL if Prisma commands need to run.
+
+## Auth Fails
+
+Symptoms:
+
+- `project list` fails
+- `auth whoami` fails
+- browser login was not completed
+- commands use the wrong workspace after a second login
+- another workspace is stored locally but commands behave signed out
+- `PRISMA_SERVICE_TOKEN` is missing, empty, expired, or lacks workspace/project permissions
+
+Fix:
+
+```bash
+bunx @prisma/cli@latest auth login
+bunx @prisma/cli@latest auth whoami
+bunx @prisma/cli@latest auth workspace list --json
+```
+
+If multiple local OAuth workspaces exist, switch explicitly. Prefer ids from JSON:
+
+```bash
+bunx @prisma/cli@latest auth workspace use
+bunx @prisma/cli@latest auth whoami --json
+bunx @prisma/cli@latest project list --json
+```
+
+For a human terminal, `auth workspace use` with no argument opens an interactive picker or selects the only local OAuth workspace without prompting. In non-interactive or `--json` mode, use `auth workspace use ` instead.
+
+If the active workspace was logged out or its token refresh failed, the CLI intentionally stays signed out for OAuth commands rather than falling through to another cached workspace. Recover by running `auth workspace list --json` and then `auth workspace use `.
+
+To remove only one local OAuth workspace session:
+
+```bash
+bunx @prisma/cli@latest auth workspace logout
+# or:
+bunx @prisma/cli@latest auth logout --workspace
+```
+
+Use plain `auth logout` only when you want to clear all local OAuth workspace sessions.
+
+For CI, `@prisma/cli` can authenticate with `PRISMA_SERVICE_TOKEN`:
+
+```bash
+test -n "${PRISMA_SERVICE_TOKEN:-}" && echo "PRISMA_SERVICE_TOKEN is set"
+bunx @prisma/cli@latest auth whoami
+bunx @prisma/cli@latest app deploy --json --no-interactive --prod --yes --env .env
+```
+
+If `PRISMA_SERVICE_TOKEN` is set and non-empty, it is the active auth source and local OAuth workspace switching is unavailable for command execution. Unset `PRISMA_SERVICE_TOKEN` before using `auth workspace use` to change local OAuth workspace context.
+
+If `PRISMA_SERVICE_TOKEN` is set but empty, the CLI errors before trying browser-login credentials. Unset it or provide a valid workspace service token. Never echo, log, or paste the token value; only check whether it is present.
+
+Local storage hints for debugging:
+
+- Override auth storage with `PRISMA_COMPUTE_AUTH_FILE` when isolating tests.
+- Default macOS OAuth credential file: `~/Library/Application Support/prisma/auth.json`.
+- Active workspace metadata sidecar: `~/Library/Application Support/prisma/auth.context.json`.
+- Project binding: `.prisma/local.json`.
+- Local app/project state: `.prisma/cli/state.json`, usually next to the discovered `prisma.compute.ts`.
+
+Do not print credential files or token values into logs.
+
+## Project Setup Fails
+
+Symptoms:
+
+- `PROJECT_SETUP_REQUIRED`
+- non-interactive deploy cannot choose a Project
+- deploy was expected to create a Project but did not
+
+Fix:
+
+```bash
+bunx @prisma/cli@latest app deploy --project --json --no-interactive
+bunx @prisma/cli@latest app deploy --create-project --yes
+```
+
+Do not rely on `--yes` alone to choose Project scope. `--project`, `--create-project`, and `PRISMA_PROJECT_ID` are mutually exclusive.
+
+## Missing or Placeholder `DATABASE_URL`
+
+Symptoms:
+
+- Prisma Client throws `DATABASE_URL is required`
+- migration scripts fail immediately
+- deploy runs but app fails on database access
+
+Fix:
+
+1. Put a real production-ready `DATABASE_URL` in `.env` or project env.
+2. Run `prisma generate`.
+3. Run migrations with the project's `db:migrate` or production migration command.
+4. Redeploy with `--env .env` or project env configured.
+
+If Prisma Client generation or runtime env loading is the concrete failure, then inspect Prisma-specific config:
+
+```bash
+test -f prisma.config.ts && sed -n '1,160p' prisma.config.ts
+test -f prisma/schema.prisma && sed -n '1,220p' prisma/schema.prisma
+```
+
+Never deploy `postgresql://USER:PASSWORD@HOST:PORT/DATABASE` placeholder values.
+
+## Wrong Branch, Env, or Database
+
+Symptoms:
+
+- preview deploy reads production env
+- branch deploy cannot find `DATABASE_URL`
+- app is deployed to the expected branch but points at the wrong database
+- logs are inspected for the current app while the failing URL belongs to a different deployment id
+
+Check:
+
+```bash
+bunx @prisma/cli@latest project show --json
+bunx @prisma/cli@latest project env list --role production --json
+bunx @prisma/cli@latest project env list --role preview --json
+bunx @prisma/cli@latest project env list --branch feature/foo --json
+bunx @prisma/cli@latest app list-deploys --json
+bunx @prisma/cli@latest app logs --deployment --json
+```
+
+Fix:
+
+- pass the same `--branch ` to `app deploy`, `database create`, and branch-specific `project env` commands
+- use `--role production` for production env and `--role preview` for preview-template env
+- capture the deployment id and URL from deploy JSON, then inspect logs with `app logs --deployment `
+- `app show`, `app list-deploys`, and `app logs` do not filter by branch; capture and use the deployment id
+- treat `app promote ` as a production action because it rebuilds with production env vars
+- do not expect `prisma.compute.ts` to select Project, Branch, production, or database scope; it only supplies app deploy defaults
+
+## Database Wiring or Schema Did Not Apply
+
+Symptoms:
+
+- deploy runs but the app cannot find `DATABASE_URL`
+- database env vars exist but the database is empty
+- a deploy-all run points multiple apps at the same branch database
+
+Fix:
+
+- read [`app-deploy-cli.md`](app-deploy-cli.md) `Database and Env` for the database/env guardrails
+- create and assign database env vars explicitly for the intended branch/app scope
+- run migrations, seed, or schema push yourself after database setup; Compute never applies schema changes for you
+- for multi-app deploy-all with app-specific database isolation, create and assign those database env vars explicitly before deploy
+
+## Workspace plan limit reached
+
+When the installed CLI returns `PLAN_LIMIT_REACHED`, treat it as a workspace plan restriction rather than a Compute or database outage.
+
+For agent/CI handling, run the relevant database command with `--json` and branch on `error.code === "PLAN_LIMIT_REACHED"`. Read `error.meta.upgradeUrl`, `planName`, `workspaceId`, and `usageBlocked`; optional values may be `null`. This is a workspace plan restriction rather than a Compute/database outage. Use the canonical upgrade URL when returned or direct the user to Prisma Console. Do not retry as an outage or infer a plan limit from status codes or message text.
+
+## Next.js Standalone Missing
+
+Error shape:
+
+```text
+Next.js build did not produce standalone output
+```
+
+Fix `next.config.ts`:
+
+```typescript
+const nextConfig = {
+ output: "standalone",
+}
+
+export default nextConfig
+```
+
+Then reinstall/build if needed and deploy again.
+
+## Next.js dependency missing after a successful build
+
+Symptoms in pnpm/Bun isolated workspaces can include a deployment that builds successfully but exits before useful runtime logs, often with `Cannot find module` for `styled-jsx` or another traced dependency.
+
+The current Compute SDK preserves in-artifact package-store symlinks and materializes only safe out-of-tree targets when staging Next standalone output. Do not manually flatten or rewrite `.next/standalone/node_modules` symlinks; that can break the isolated-store layout.
+
+Fix:
+
+1. Upgrade `@prisma/compute-sdk` and `@prisma/cli` to current versions.
+2. Remove only the generated build artifact/cache appropriate to the project, then rebuild.
+3. Confirm `output: "standalone"`, redeploy, and inspect the new deployment logs.
+4. If it persists, report the package manager, workspace layout, first missing module, and SDK/CLI versions through `@prisma/cli feedback` without secrets.
+
+## Nitro Entry Missing
+
+Nuxt or TanStack Start error shape:
+
+```text
+.output/server/index.mjs
+```
+
+General fix:
+
+- ensure the correct framework plugins are installed
+- run the framework build locally
+- avoid custom Nitro presets that produce a non-Node target
+- use the default Nitro node server preset
+
+For TanStack Start specifically:
+
+- keep `nitro` in `dependencies`
+- keep `import { nitro } from "nitro/vite"` in `vite.config.ts`
+- keep `plugins: [tanstackStart(), nitro(), viteReact()]` or the framework-equivalent plugin order
+- run `bun run build` and verify `.output/server/index.mjs` exists
+- do not replace the production server with `vite preview`
+
+Compute detection selects TanStack Start when it sees `@tanstack/react-start` or `@tanstack/solid-start`. If the Nitro entrypoint is missing after that, fix the TanStack/Nitro build output; do not assume Compute will silently use a Bun deployment.
+
+## Bun Entrypoint Missing
+
+Error shape:
+
+```text
+Entrypoint is required
+Entrypoint file does not exist
+```
+
+Fix either:
+
+```json
+{
+ "main": "src/index.ts"
+}
+```
+
+or deploy with:
+
+```bash
+bunx @prisma/cli@latest app deploy --framework bun --entry src/index.ts
+```
+
+## Port Mismatch
+
+Symptoms:
+
+- deploy succeeds but the app is unreachable
+- health checks fail
+- logs show the server listening on a different port
+
+Fix:
+
+- read `process.env.PORT`
+- pass `--http-port ` when the app has a fixed port
+- use the generated `compute:deploy` script when it exists
+- remember the `@prisma/cli app deploy` default is HTTP `3000`; generated Hono/Elysia projects usually configure `8080` through `prisma.compute.ts` or flag-backed `--http-port 8080` scripts
+- use the template defaults: Hono/Elysia `8080`, Next/TanStack/Nuxt `3000`, Astro `4321`
+
+## Public URL Smoke Test Fails
+
+Symptoms:
+
+- deploy command completed
+- `app show` or deploy output has a URL
+- the public URL times out, returns 5xx, or returns an unexpected page
+
+Check:
+
+```bash
+curl -i https://
+curl -i https:///health
+bunx @prisma/cli@latest app logs --json
+```
+
+Fix by following the first concrete failure:
+
+- connection timeout or 5xx: check logs, host binding, and port mapping
+- `504 Gateway Time-out` with an `openresty` body about 60s in: the ingress request timeout, not the app; see Request Timeout below
+- unexpected status or body: verify the route path and app framework output
+- local URL tested by mistake: rerun against the public deployment URL, not `localhost` or `127.0.0.1`
+
+## Localhost Binding
+
+Symptoms:
+
+- deploy says the app started or the port was observed, but the public URL is unreachable
+- logs show a server listening on `localhost` or `127.0.0.1`
+- `app run` works locally, but the deployed app cannot receive external traffic
+
+Why this happens:
+
+Compute's boot watcher polls `/proc/net/tcp` and `/proc/net/tcp6` for configured ports entering `LISTEN`. That readiness signal tracks the port, not whether the app bound `127.0.0.1` or all interfaces. A loopback-only listener can therefore look ready while public ingress still cannot reach it.
+
+Fix:
+
+- remove hard-coded `localhost` or `127.0.0.1` server host settings
+- bind on `0.0.0.0` or the framework equivalent, such as Astro `server.host: true`
+- for Next.js standalone, do not deploy with `HOSTNAME=localhost`; use `HOSTNAME=0.0.0.0` if the host is overridden
+- keep port and host fixes together: `0.0.0.0:`
+
+## Request Timeout
+
+Symptoms:
+
+- the public URL returns `504 Gateway Time-out` with a short `openresty` body, about 60 seconds after the request was sent
+- the app's own logs show the handler running, with no timeout error
+- the same route works whenever it starts responding in under 60 seconds
+- application timeouts set above 60 seconds never produce a response the caller sees
+
+Why this happens:
+
+Compute's ingress gives an app 60 seconds to start responding, then answers the client itself and cancels the request. The deadline covers the wait for the first bytes, not how long the response takes to finish, so a response that has already started streaming is not cut off. The app is not told directly; the cancellation surfaces as the request's abort signal. Once the request is cancelled, Compute stops counting it as in flight, so the instance can scale to zero while the handler is still working.
+
+Fix:
+
+- respond within 60 seconds; for webhooks, return `200` or `202` before doing the work
+- continue the work after the response with `waitUntil` or `KeepAwakeGuard` from `@prisma/compute`, which hold the instance awake on a best-effort basis
+- for work that must not be lost, persist a job and process it from a separate trigger in steps that each fit inside one request
+- keep in-request timeouts (`AbortSignal.timeout`, fetch timeouts) under 60 seconds so the app's own error handling runs first
+- check `req.signal` when a handler should stop work it no longer needs to finish
+- docs: https://www.prisma.io/docs/compute/request-timeout
+
+## Env Changes Did Not Apply
+
+Generated `compute:deploy` scripts redeploy using the generated flags and/or `prisma.compute.ts`; they do not run migrations or seed data.
+
+After env changes:
+
+```bash
+bunx @prisma/cli@latest project env list
+bunx @prisma/cli@latest project env list --branch feature/foo
+bunx @prisma/cli@latest app deploy --prod --yes --env .env
+bunx @prisma/cli@latest app deploy --branch feature/foo --env .env.preview
+```
+
+If using branch-specific env, confirm the branch name and role.
+
+## Need Logs
+
+Runtime logs for the current app:
+
+```bash
+bunx @prisma/cli@latest app logs
+```
+
+Specific deployment:
+
+```bash
+bunx @prisma/cli@latest app logs --deployment
+```
+
+Machine-readable:
+
+```bash
+bunx @prisma/cli@latest app logs --json
+```
+
+Build logs for GitHub/Console builds:
+
+```bash
+bunx @prisma/cli@latest build logs
+bunx @prisma/cli@latest build logs --follow
+bunx @prisma/cli@latest build logs --json
+```
+
+Use `build logs` for build output keyed by a Build id from a GitHub check run, Console build page, or Management API build record. Use `app logs` for runtime logs keyed by the current app deployment or a deployment id.
+
+Summarize relevant errors. Do not paste secrets.
+
+## Report Unresolved CLI Issues
+
+When a CLI failure survives the checks above, or a command crashes with `UNEXPECTED_ERROR`, report it to the Prisma team:
+
+```bash
+bunx @prisma/cli@latest feedback "app deploy crashed: "
+```
+
+Prefer the pre-filled command from a `--json` crash envelope's `nextActions` verbatim. Anonymous; never put secrets, connection URLs, or tokens in the message.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/SKILL.md b/apps/backend/.agents/skills/prisma-database-setup/SKILL.md
new file mode 100644
index 0000000..51643e7
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/SKILL.md
@@ -0,0 +1,192 @@
+---
+name: prisma-database-setup
+description: Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup".
+license: MIT
+metadata:
+ author: prisma
+ version: "7.6.0"
+---
+
+# Prisma Database Setup
+
+Comprehensive guides for configuring Prisma ORM with various database providers.
+
+## When to Apply
+
+Reference this skill when:
+- Initializing a new Prisma project
+- Switching database providers
+- Configuring connection strings and environment variables
+- Troubleshooting database connection issues
+- Setting up database-specific features
+- Generating and instantiating Prisma Client
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Provider Guides | CRITICAL | provider names |
+| 2 | Prisma Postgres | HIGH | `prisma-postgres` |
+| 3 | Client Setup | CRITICAL | `prisma-client-setup` |
+
+## System Prerequisites
+
+- **Node.js 20.19.0+**
+- **TypeScript 5.4.0+**
+
+## Bun Runtime
+
+If you're using Bun, run Prisma CLI commands with `bunx --bun prisma ...` so Prisma uses the Bun runtime instead of falling back to Node.js.
+
+## Supported Databases
+
+| Database | Provider String | Notes |
+|----------|-----------------|-------|
+| PostgreSQL | `postgresql` | Default, full feature support |
+| MySQL | `mysql` | Widespread support, some JSON diffs |
+| SQLite | `sqlite` | Local file-based, no enum/scalar lists |
+| MongoDB | `mongodb` | Mongo-specific workflow; do not apply SQL driver-adapter guidance |
+| SQL Server | `sqlserver` | Microsoft ecosystem |
+| CockroachDB | `cockroachdb` | Distributed SQL, Postgres-compatible |
+| Prisma Postgres | `postgresql` | Managed serverless database |
+
+## Configuration Files
+
+Your configuration shape depends on the provider and Prisma major version:
+
+1. **All providers** use **`prisma/schema.prisma`**.
+2. **Prisma 7 SQL setups** typically use **`prisma.config.ts`** for datasource URLs.
+3. **MongoDB projects should stay on Prisma 6.x**, keep `url = env("DATABASE_URL")` in the schema, and continue using the classic MongoDB setup.
+
+## Driver Adapters
+
+The standard SQL workflow uses a driver adapter. Choose the adapter and driver for your database and pass the adapter to `PrismaClient`.
+
+| Database | Adapter | JS Driver |
+|----------|---------|-----------|
+| PostgreSQL | `@prisma/adapter-pg` | `pg` |
+| CockroachDB | `@prisma/adapter-pg` | `pg` |
+| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
+| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
+| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
+| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
+| SQLite (Turso/LibSQL) | `@prisma/adapter-libsql` | `@libsql/client` |
+| SQL Server | `@prisma/adapter-mssql` | `node-mssql` |
+
+MongoDB should not follow the Prisma 7 SQL adapter workflow. Use the latest Prisma 6.x release for MongoDB projects and do not install a SQL `@prisma/adapter-*` package for it.
+
+Example (PostgreSQL):
+
+```ts
+import 'dotenv/config'
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+const prisma = new PrismaClient({ adapter })
+```
+
+## Prisma Client Setup (Required)
+
+Prisma Client must be installed and generated for any database.
+
+1. Install Prisma CLI and Prisma Client:
+ ```bash
+ npm install prisma --save-dev
+ npm install @prisma/client
+ ```
+
+1. Add a generator block (`prisma-client` requires an explicit output path):
+ ```prisma
+ generator client {
+ provider = "prisma-client"
+ output = "../generated"
+ }
+ ```
+
+1. Generate Prisma Client:
+ ```bash
+ npx prisma generate
+ ```
+
+1. For SQL providers, instantiate Prisma Client with the database-specific driver adapter:
+ ```typescript
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+1. Re-run `prisma generate` after every schema change.
+
+## Quick Reference
+
+### PostgreSQL
+```prisma
+datasource db {
+ provider = "postgresql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+### MySQL
+```prisma
+datasource db {
+ provider = "mysql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+### SQLite
+```prisma
+datasource db {
+ provider = "sqlite"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+### MongoDB
+```prisma
+datasource db {
+ provider = "mongodb"
+ url = env("DATABASE_URL")
+}
+
+generator client {
+ provider = "prisma-client-js"
+}
+```
+
+For MongoDB, stay on the latest Prisma 6.x line and keep the connection URL in `schema.prisma`. Do not move a MongoDB project to the Prisma 7 SQL adapter setup. If a MongoDB project asks about upgrading Prisma versions, route to the `prisma-mongodb-upgrade` skill (stay-on-v6 vs Prisma Next is the real decision; Prisma 7 is not an option).
+
+## Rule Files
+
+See individual rule files for detailed setup instructions:
+
+```
+references/postgresql.md
+references/mysql.md
+references/sqlite.md
+references/mongodb.md
+references/sqlserver.md
+references/cockroachdb.md
+references/prisma-postgres.md
+references/prisma-client-setup.md
+```
+
+## How to Use
+
+Choose the provider reference file for your database, then apply `references/prisma-client-setup.md` to complete client generation and adapter setup. For MongoDB, use `references/mongodb.md` instead of copying the SQL adapter examples or Prisma 7 config pattern.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/cockroachdb.md b/apps/backend/.agents/skills/prisma-database-setup/references/cockroachdb.md
new file mode 100644
index 0000000..38d3859
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/cockroachdb.md
@@ -0,0 +1,89 @@
+# CockroachDB Setup
+
+Configure Prisma with CockroachDB.
+
+## Prerequisites
+
+- CockroachDB cluster
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "cockroachdb"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="postgresql://user:password@host:26257/db?sslmode=verify-full"
+```
+
+Note: CockroachDB uses the PostgreSQL wire protocol, so the URL often looks like postgresql, but the provider **MUST** be `cockroachdb` in the schema to handle specific CRDB features correctly.
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow. CockroachDB is PostgreSQL-compatible, so use the PostgreSQL adapter.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-pg pg
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## ID Generation
+
+CockroachDB uses `BigInt` or `UUID` for IDs efficiently.
+
+```prisma
+model User {
+ id BigInt @id @default(autoincrement()) // Uses unique_rowid()
+}
+```
+
+Or using string UUIDs:
+
+```prisma
+model User {
+ id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
+}
+```
+
+## Common Issues
+
+### Schema Introspection
+Always use `provider = "cockroachdb"` to ensure correct type mapping during `db pull`.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/mongodb.md b/apps/backend/.agents/skills/prisma-database-setup/references/mongodb.md
new file mode 100644
index 0000000..29dc2a0
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/mongodb.md
@@ -0,0 +1,90 @@
+# MongoDB Setup
+
+MongoDB projects should stay on the latest Prisma 6.x release. Do not upgrade a MongoDB app to Prisma 7's SQL client path.
+
+## Prerequisites
+
+- MongoDB 4.2+
+- Replica Set configured (required for transactions)
+- Latest Prisma 6.x release, or your team's pinned Prisma 6 version
+- Node.js 20.19.0+
+- TypeScript 5.4.0+
+
+## 1. Schema Configuration
+
+Use the standard Prisma 6 MongoDB setup with `prisma-client-js`.
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "mongodb"
+ url = env("DATABASE_URL")
+}
+
+generator client {
+ provider = "prisma-client-js"
+}
+```
+
+### Driver Adapters
+
+Do **not** apply the Prisma 7 SQL adapter setup here. MongoDB does not use a SQL `@prisma/adapter-*` package.
+
+### ID Field Requirement
+
+MongoDB models **must** have a mapped `_id` field using `@id` and `@map("_id")`, usually of type `String` with `auto()` and `db.ObjectId`.
+
+```prisma
+model User {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ email String @unique
+ name String?
+}
+```
+
+### Relations
+
+Relations in MongoDB expect IDs to be `db.ObjectId` type.
+
+```prisma
+model Post {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ author User @relation(fields: [authorId], references: [id])
+ authorId String @db.ObjectId
+}
+```
+
+## 2. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="mongodb+srv://user:password@cluster.mongodb.net/mydb?retryWrites=true&w=majority"
+```
+
+## Migrations vs Introspection
+
+- **No Migrations**: MongoDB is schema-less. `prisma migrate` commands **do not work**.
+- **db push**: Use `prisma db push` to sync indexes and constraints.
+- **db pull**: Use `prisma db pull` to generate schema from existing data (sampling).
+
+## Current Verification Notes
+
+- `prisma init --datasource-provider mongodb` is still implemented in Prisma's CLI source.
+- Prisma's upstream repo still contains MongoDB fixtures and tests.
+- Local verification shows Prisma 7 can still recognize MongoDB inputs, but the generated client path does not provide a supported MongoDB upgrade path.
+- Local verification shows Prisma 6.x works end to end with `prisma-client-js`, `prisma db push`, and `new PrismaClient()` against a MongoDB replica set.
+
+## Version Guidance
+
+- For MongoDB, stay on the latest available Prisma 6.x release.
+- Treat Prisma 7 MongoDB migration attempts as unsupported until Prisma ships a real MongoDB upgrade path.
+
+## Common Issues
+
+### "Transactions not supported"
+Ensure your MongoDB instance is a **Replica Set**. Standalone instances do not support transactions. Atlas clusters are replica sets by default.
+
+### "Invalid ObjectID"
+Ensure fields referencing IDs are decorated with `@db.ObjectId` if the target is an ObjectID.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/mysql.md b/apps/backend/.agents/skills/prisma-database-setup/references/mysql.md
new file mode 100644
index 0000000..eb67b18
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/mysql.md
@@ -0,0 +1,126 @@
+# MySQL Setup
+
+Configure Prisma with MySQL (or MariaDB).
+
+## Prerequisites
+
+- MySQL or MariaDB database
+- Connection string
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "mysql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="mysql://user:password@localhost:3306/mydb"
+```
+
+### Connection String Format
+
+```
+mysql://USER:PASSWORD@HOST:PORT/DATABASE
+```
+
+- **USER**: Database user
+- **PASSWORD**: Password
+- **HOST**: Hostname
+- **PORT**: Port (default 3306)
+- **DATABASE**: Database name
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-mariadb mariadb
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaMariaDb } from '@prisma/adapter-mariadb'
+
+ const adapter = new PrismaMariaDb({
+ host: 'localhost',
+ port: 3306,
+ connectionLimit: 5,
+ user: process.env.MYSQL_USER,
+ password: process.env.MYSQL_PASSWORD,
+ database: process.env.MYSQL_DATABASE,
+ })
+
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+### Text protocol option
+
+If you need the MariaDB driver's text protocol instead of the default binary `execute()` path, enable `useTextProtocol` explicitly:
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaMariaDb } from '@prisma/adapter-mariadb'
+
+const adapter = new PrismaMariaDb(process.env.DATABASE_URL!, {
+ useTextProtocol: true,
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+Use this only when you specifically need text-protocol compatibility for your MariaDB setup.
+
+## PlanetScale Setup
+
+PlanetScale uses MySQL but requires specific settings because it doesn't support foreign key constraints.
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "mysql"
+ relationMode = "prisma" // Emulate foreign keys in Prisma
+}
+```
+
+## Common Issues
+
+### "Too many connections"
+MySQL has a connection limit. Adjust connection pool size in URL:
+```env
+DATABASE_URL="mysql://...?connection_limit=5"
+```
+
+### JSON Support
+MySQL 5.7+ supports JSON. MariaDB 10.2+ supports JSON (as an alias for LONGTEXT with check constraints). Prisma handles this, but verify your version.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/postgresql.md b/apps/backend/.agents/skills/prisma-database-setup/references/postgresql.md
new file mode 100644
index 0000000..ea575f6
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/postgresql.md
@@ -0,0 +1,92 @@
+# PostgreSQL Setup
+
+Configure Prisma with PostgreSQL.
+
+## Prerequisites
+
+- PostgreSQL database (local or cloud)
+- Connection string
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "postgresql"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
+```
+
+### Connection String Format
+
+```
+postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA
+```
+
+- **USER**: Database user
+- **PASSWORD**: Password (URL encoded if special chars)
+- **HOST**: Hostname (localhost, IP, or domain)
+- **PORT**: Port (default 5432)
+- **DATABASE**: Database name
+- **SCHEMA**: Schema name (default `public`)
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-pg pg
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Common Issues
+
+### "Can't reach database server"
+- Check host and port
+- Check firewall settings
+- Ensure database is running
+
+### "Authentication failed"
+- Check user/password
+- Special characters in password must be URL-encoded
+
+### "Schema does not exist"
+- Ensure `?schema=public` (or your schema) is in the URL
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/prisma-client-setup.md b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-client-setup.md
new file mode 100644
index 0000000..bb36932
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-client-setup.md
@@ -0,0 +1,47 @@
+# Prisma Client Setup
+
+Generate and instantiate Prisma Client for Prisma's standard SQL provider workflow. For MongoDB, follow the provider-specific notes in `references/mongodb.md` instead of copying the SQL adapter example below.
+
+## 1. Install dependencies
+
+```bash
+npm install prisma --save-dev
+npm install @prisma/client
+```
+
+## 2. Add generator block
+
+In `prisma/schema.prisma`:
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+`prisma-client` requires an explicit `output` path and does not generate into `node_modules` by default.
+
+## 3. Generate Prisma Client
+
+```bash
+npx prisma generate
+```
+
+Re-run `prisma generate` after every schema change to keep the client in sync.
+
+## 4. Instantiate Prisma Client
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+const prisma = new PrismaClient({ adapter })
+```
+
+If you change the generator `output`, update the import path to match. For the SQL provider workflow, replace `PrismaPg` with the adapter for your database.
+
+## 5. Use a single instance
+
+Each `PrismaClient` instance creates a connection pool. Reuse a single instance per app process to avoid exhausting database connections.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/prisma-postgres.md b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-postgres.md
new file mode 100644
index 0000000..dc939e5
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/prisma-postgres.md
@@ -0,0 +1,130 @@
+# Prisma Postgres Setup
+
+Configure Prisma with Prisma Postgres (Managed).
+
+## Overview
+
+Prisma Postgres is a serverless, managed PostgreSQL database optimized for Prisma.
+
+## Setup via CLI
+
+You can provision a Prisma Postgres instance directly via the CLI:
+
+```bash
+prisma init --db
+```
+
+This will:
+1. Log you into Prisma Data Platform.
+2. Create a new project and database instance.
+3. Update your `.env` with the connection string.
+
+## Connection String
+
+For Prisma CLI flows and Accelerate-style usage, you may see a `prisma+postgres://` URL.
+
+For Prisma Client with a driver adapter in Node.js, prefer the direct TCP connection string from the Prisma Postgres dashboard:
+
+```env
+DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require"
+```
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "postgresql" // Use postgresql provider
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Driver Adapter
+
+Use a driver adapter for Prisma Postgres in the standard SQL workflow.
+
+### Recommended for standard Node.js apps
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-pg pg
+ ```
+
+2. Use the direct TCP connection string from Prisma Console:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaPg } from '@prisma/adapter-pg'
+
+ const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+`PrismaPg` also accepts the connection string directly:
+
+```typescript
+const adapter = new PrismaPg(process.env.DATABASE_URL!)
+const prisma = new PrismaClient({ adapter })
+```
+
+For PostgreSQL prepared statement naming, pass adapter options as the second argument:
+
+```typescript
+import { createHash } from 'node:crypto'
+
+const adapter = new PrismaPg(process.env.DATABASE_URL!, {
+ statementNameGenerator: ({ sql }) =>
+ `prisma_${createHash('sha1').update(sql).digest('hex').slice(0, 16)}`,
+})
+```
+
+### Edge/serverless option
+
+Use the Prisma Postgres serverless driver only when you need HTTP/WebSocket transport in environments like Workers or Edge Functions:
+
+```bash
+npm install @prisma/adapter-ppg @prisma/ppg
+```
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
+
+const prisma = new PrismaClient({
+ adapter: new PrismaPostgresAdapter({
+ connectionString: process.env.PRISMA_DIRECT_TCP_URL,
+ }),
+})
+```
+
+This serverless driver is the specialized path for HTTP/WebSocket-based edge and serverless runtimes, not the default recommendation for standard Node.js apps.
+
+## Features
+
+- **Serverless**: Scales to zero.
+- **Caching**: Integrated query caching (Accelerate).
+- **Real-time**: Database events (Pulse).
+
+## Using with Prisma Client
+
+Use the Prisma Postgres adapter shown above when instantiating Prisma Client.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/sqlite.md b/apps/backend/.agents/skills/prisma-database-setup/references/sqlite.md
new file mode 100644
index 0000000..30e3e00
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/sqlite.md
@@ -0,0 +1,106 @@
+# SQLite Setup
+
+Configure Prisma with SQLite.
+
+## Prerequisites
+
+- None (file-based)
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "sqlite"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="file:./dev.db"
+```
+
+### Connection String Format
+
+```
+file:PATH
+```
+
+- **PATH**: Relative path to the database file. Check `prisma.config.ts` if you need to confirm how your app resolves it.
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-better-sqlite3 better-sqlite3
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import { PrismaClient } from '../generated/client'
+ import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
+
+ const adapter = new PrismaBetterSqlite3({
+ url: process.env.DATABASE_URL ?? 'file:./dev.db',
+ })
+
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Using Driver Adapter (LibSQL / Turso)
+
+For edge compatibility or Turso:
+
+1. Install:
+ ```bash
+ npm install @prisma/adapter-libsql @libsql/client
+ ```
+
+2. Instantiate:
+ ```typescript
+ import { PrismaClient } from '../generated/client'
+ import { PrismaLibSql } from '@prisma/adapter-libsql'
+
+ const adapter = new PrismaLibSql({
+ url: process.env.TURSO_DATABASE_URL,
+ authToken: process.env.TURSO_AUTH_TOKEN,
+ })
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Limitations
+
+- **No Enums**: SQLite doesn't support enums (Prisma polyfills them or treats as String).
+- **No Scalar Lists**: `String[]` is not supported directly.
+- **Concurrency**: Write operations lock the file.
+
+## Common Issues
+
+### "Database file not found"
+Ensure the path in `DATABASE_URL` is correct relative to where Prisma is running or the schema file. `file:./dev.db` creates it next to schema.
diff --git a/apps/backend/.agents/skills/prisma-database-setup/references/sqlserver.md b/apps/backend/.agents/skills/prisma-database-setup/references/sqlserver.md
new file mode 100644
index 0000000..b519d95
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-database-setup/references/sqlserver.md
@@ -0,0 +1,94 @@
+# SQL Server Setup
+
+Configure Prisma with Microsoft SQL Server.
+
+## Prerequisites
+
+- SQL Server 2017, 2019, 2022, or Azure SQL
+- TCP/IP enabled
+
+## 1. Schema Configuration
+
+In `prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "sqlserver"
+}
+
+generator client {
+ provider = "prisma-client"
+ output = "../generated"
+}
+```
+
+## 2. Config Configuration
+
+In `prisma.config.ts`:
+
+```typescript
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## 3. Environment Variable
+
+In `.env`:
+
+```env
+DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=Password123;encrypt=true;trustServerCertificate=true"
+```
+
+### Connection String Format
+
+```
+sqlserver://HOST:PORT;database=DB;user=USER;password=PASS;encrypt=true;trustServerCertificate=true
+```
+
+- **encrypt**: Required for Azure (true).
+- **trustServerCertificate**: True for self-signed certs (local dev).
+
+## Driver Adapter
+
+Use a driver adapter for the standard SQL workflow.
+
+1. Install adapter and driver:
+ ```bash
+ npm install @prisma/adapter-mssql mssql
+ ```
+
+2. Instantiate Prisma Client with the adapter:
+ ```typescript
+ import 'dotenv/config'
+ import { PrismaClient } from '../generated/client'
+ import { PrismaMssql } from '@prisma/adapter-mssql'
+
+ const adapter = new PrismaMssql({
+ server: 'localhost',
+ port: 1433,
+ database: 'mydb',
+ user: process.env.SQLSERVER_USER,
+ password: process.env.SQLSERVER_PASSWORD,
+ options: {
+ encrypt: true,
+ trustServerCertificate: true,
+ },
+ })
+
+ const prisma = new PrismaClient({ adapter })
+ ```
+
+## Common Issues
+
+### "Login failed for user"
+- SQL Server auth vs Windows auth. Prisma typically uses SQL Server authentication (username/password).
+- Ensure TCP/IP is enabled in SQL Server Configuration Manager.
+
+### "Table not found" (dbo schema)
+Prisma assumes `dbo` schema by default. If using another schema, update the model or connection string? SQL Server provider mostly sticks to default schema.
diff --git a/apps/backend/.agents/skills/prisma-driver-adapter-implementation/SKILL.md b/apps/backend/.agents/skills/prisma-driver-adapter-implementation/SKILL.md
new file mode 100644
index 0000000..4bf3479
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-driver-adapter-implementation/SKILL.md
@@ -0,0 +1,270 @@
+---
+name: prisma-driver-adapter-implementation
+description: Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.
+license: MIT
+metadata:
+ author: prisma
+ version: "7.9.1"
+---
+
+# Prisma SQL Driver Adapter Implementation
+
+Use this guide with the exact `@prisma/driver-adapter-utils` version installed by the target Prisma release. Driver adapters are a protocol boundary: type-compatible code can still corrupt values, leak connections, or break transactions.
+
+## When to Apply
+
+- Implementing `SqlDriverAdapterFactory`, `SqlMigrationAwareDriverAdapterFactory`, `SqlDriverAdapter`, or `Transaction`
+- Adding nested-transaction/savepoint support
+- Mapping driver values, column metadata, bind arguments, or database errors
+- Debugging `P2039`, transaction leaks, shadow-database failures, or adapter-specific query behavior
+
+## Contract snapshot
+
+```typescript
+interface SqlDriverAdapterFactory extends AdapterInfo {
+ connect(): Promise
+}
+
+interface SqlMigrationAwareDriverAdapterFactory extends SqlDriverAdapterFactory {
+ connectToShadowDb(): Promise
+}
+
+interface SqlDriverAdapter extends AdapterInfo {
+ queryRaw(query: SqlQuery): Promise
+ executeRaw(query: SqlQuery): Promise
+ executeScript(script: string): Promise
+ startTransaction(isolationLevel?: IsolationLevel): Promise
+ getConnectionInfo?(): ConnectionInfo
+ dispose(): Promise
+}
+
+interface Transaction extends AdapterInfo {
+ readonly options: { usePhantomQuery: boolean }
+ queryRaw(query: SqlQuery): Promise
+ executeRaw(query: SqlQuery): Promise
+ commit(): Promise
+ rollback(): Promise
+ createSavepoint?(name: string): Promise
+ rollbackToSavepoint?(name: string): Promise
+ releaseSavepoint?(name: string): Promise
+}
+```
+
+`IsolationLevel` currently includes `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, `SNAPSHOT`, and `SERIALIZABLE`; validate what the concrete database supports.
+
+## Priority rules
+
+| Priority | Rule | Impact |
+|----------|------|--------|
+| CRITICAL | One dedicated connection per transaction | Prevents interleaving and leaks |
+| CRITICAL | `commit`/`rollback` are lifecycle cleanup hooks | Prevents duplicate COMMIT/ROLLBACK |
+| CRITICAL | Savepoints live on `Transaction`, not adapter-global depth | Makes nested scopes connection-local |
+| CRITICAL | Preserve original database error code/message | Enables useful `P2039` fallback |
+| HIGH | Map arguments and result metadata exactly | Prevents silent value corruption |
+| HIGH | Shadow databases are isolated and always cleaned up | Makes Migrate safe |
+| HIGH | Dispose only resources the adapter owns | Prevents shutting down caller-owned pools |
+
+## Query implementation
+
+`SqlQuery` contains `sql`, `args`, and parallel `argTypes`. Map each argument using both value and `ArgType`; do not discard type/arity information. Execute in the driver's array/tuple row mode so column order is stable.
+
+```typescript
+class ExampleQueryable {
+ readonly provider = 'postgres' as const
+ readonly adapterName = '@acme/adapter-example'
+
+ constructor(protected readonly connection: DriverConnection) {}
+
+ async queryRaw(query: SqlQuery): Promise {
+ try {
+ const result = await this.connection.query({
+ text: query.sql,
+ values: query.args.map((value, index) =>
+ mapArg(value, query.argTypes[index]),
+ ),
+ rowMode: 'array',
+ })
+
+ return {
+ columnNames: result.fields.map((field) => field.name),
+ columnTypes: result.fields.map(mapColumnType),
+ rows: result.rows,
+ }
+ } catch (error) {
+ throwAdapterError(error)
+ }
+ }
+
+ async executeRaw(query: SqlQuery): Promise {
+ try {
+ const result = await this.connection.execute(
+ query.sql,
+ query.args.map((value, index) => mapArg(value, query.argTypes[index])),
+ )
+ return result.rowsAffected ?? 0
+ } catch (error) {
+ throwAdapterError(error)
+ }
+ }
+}
+```
+
+### Result mapping
+
+Return `columnNames`, `columnTypes`, and `rows` with identical lengths/order. Map driver metadata to `ColumnTypeEnum` deliberately:
+
+- signed integer widths to `Int32`/`Int64`; preserve 64-bit values without JS number truncation
+- decimal/numeric to `Numeric` using the representation expected by Prisma
+- binary to `Uint8Array`/`Bytes`
+- date-only, time-only, and timestamp to `Date`, `Time`, and `DateTime`
+- UUID, JSON, enum, arrays, and provider-specific unknown values to their explicit types
+- unsupported native types to `DriverAdapterError({ kind: 'UnsupportedNativeDataType', type })`
+
+Test `null`, empty arrays, array element types, big integers, decimals, byte arrays, JSON, dates, and user-defined/unknown native types.
+
+### Script execution
+
+`executeScript` must execute a migration script as the provider expects. Prefer the driver's native multi-statement/script facility or a real SQL parser. Naively splitting on `;` breaks functions, triggers, quoted strings, and dialect-specific blocks.
+
+## Transaction protocol
+
+`startTransaction` must acquire one dedicated connection, start the database transaction, apply the requested isolation level, and return a `Transaction` bound to that same connection. If setup fails, release it immediately.
+
+```typescript
+async startTransaction(level?: IsolationLevel): Promise {
+ const connection = await this.pool.acquire()
+ try {
+ const tx = new ExampleTransaction(connection, () => connection.release())
+ await tx.executeRaw({ sql: 'BEGIN', args: [], argTypes: [] })
+ if (level) {
+ await tx.executeRaw({
+ sql: `SET TRANSACTION ISOLATION LEVEL ${validateLevel(level)}`,
+ args: [],
+ argTypes: [],
+ })
+ }
+ return tx
+ } catch (error) {
+ connection.release(error)
+ throwAdapterError(error)
+ }
+}
+```
+
+### Commit and rollback
+
+Prisma coordinates the SQL `COMMIT`/`ROLLBACK` through `executeRaw`. The transaction object's `commit()` and `rollback()` methods are lifecycle hooks: detach listeners and release the dedicated connection exactly once. They must not issue a second SQL commit/rollback.
+
+```typescript
+class ExampleTransaction extends ExampleQueryable implements Transaction {
+ readonly options = { usePhantomQuery: false }
+ #closed = false
+
+ constructor(connection: DriverConnection, private readonly release: () => void) {
+ super(connection)
+ }
+
+ async commit() { this.finish() }
+ async rollback() { this.finish() }
+
+ private finish() {
+ if (this.#closed) return
+ this.#closed = true
+ this.release()
+ }
+
+ async createSavepoint(name: string) {
+ await this.control(`SAVEPOINT ${safeSavepoint(name)}`)
+ }
+
+ async rollbackToSavepoint(name: string) {
+ await this.control(`ROLLBACK TO SAVEPOINT ${safeSavepoint(name)}`)
+ }
+
+ async releaseSavepoint(name: string) {
+ await this.control(`RELEASE SAVEPOINT ${safeSavepoint(name)}`)
+ }
+
+ private async control(sql: string) {
+ await this.executeRaw({ sql, args: [], argTypes: [] })
+ }
+}
+```
+
+Implement the optional savepoint methods only where the provider supports them. Validate/quote savepoint identifiers. For providers whose savepoints are intentionally no-ops, document and test that limitation.
+
+Never keep transaction depth on the shared adapter. Parallel transactions make adapter-global depth incorrect; nested state belongs to the returned transaction connection and Prisma's savepoint calls.
+
+## Error mapping
+
+Wrap recognized driver failures in `DriverAdapterError`. Map known conditions to `MappedError` kinds such as constraint violations, authentication/reachability, missing table/column/database, timeouts, closed transactions, invalid input, value range, and write conflicts.
+
+For database errors, preserve `originalCode` and `originalMessage` even when falling back to the provider-specific raw variant:
+
+```typescript
+import {
+ DriverAdapterError,
+ type Error as DriverAdapterErrorObject,
+ type MappedError,
+} from '@prisma/driver-adapter-utils'
+
+function convertDriverError(error: DatabaseError): DriverAdapterErrorObject {
+ return {
+ originalCode: String(error.code),
+ originalMessage: error.message,
+ ...mapKnownOrRaw(error),
+ }
+}
+
+function mapKnownOrRaw(error: DatabaseError): MappedError {
+ if (error.code === '23505') {
+ return { kind: 'UniqueConstraintViolation', constraint: parsedConstraint(error) }
+ }
+ return {
+ kind: 'postgres',
+ code: String(error.code ?? 'N/A'),
+ severity: error.severity ?? 'N/A',
+ message: error.message,
+ detail: error.detail,
+ column: error.column,
+ hint: error.hint,
+ }
+}
+
+function throwAdapterError(error: unknown): never {
+ if (!isDatabaseError(error)) throw error
+ throw new DriverAdapterError(convertDriverError(error))
+}
+```
+
+Prisma uses preserved original details when an unmapped driver error becomes `P2039`. Do not replace every unknown exception with a fabricated `GenericJs` id; rethrow genuinely unexpected non-driver errors so programming bugs remain visible.
+
+## Factory, ownership, and shadow database
+
+- `connect()` returns a fresh usable adapter connection/pool wrapper.
+- Track whether the factory created the pool. `dispose()` closes owned pools and only detaches listeners from caller-owned pools unless an explicit option transfers ownership.
+- Implement `SqlMigrationAwareDriverAdapterFactory` only when `connectToShadowDb()` can create an isolated shadow database, connect to it, and drop it during disposal/failure cleanup.
+- Never point the shadow adapter at the primary database. Quote generated identifiers and use cryptographically unique names.
+- `getConnectionInfo()` should accurately report `schemaName`, `maxBindValues` when applicable, and `supportsRelationJoins`.
+
+## Verification checklist
+
+- [ ] Typecheck against the exact target `@prisma/driver-adapter-utils` version
+- [ ] `queryRaw` preserves column order, types, nulls, and precision
+- [ ] `executeRaw` reports affected rows correctly
+- [ ] `executeScript` handles provider-specific multi-statement syntax
+- [ ] Concurrent interactive transactions use distinct dedicated connections
+- [ ] Success commits and releases once; failure rolls back and releases once
+- [ ] Nested transaction tests exercise create/rollback/release savepoint hooks
+- [ ] Unsupported isolation levels fail as `InvalidIsolationLevel`
+- [ ] Known constraints map to structured errors
+- [ ] Unmapped database errors retain original code/message and surface useful `P2039`
+- [ ] Dispose ownership is tested for internal and external pools
+- [ ] Shadow database creation, use, failure cleanup, and disposal are isolated
+- [ ] Run Prisma Client integration/E2E tests, not only adapter unit tests
+
+## Source references
+
+- [Driver adapter interfaces](https://github.com/prisma/prisma/blob/v7/packages/driver-adapter-utils/src/types.ts)
+- [PostgreSQL adapter transaction implementation](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/pg.ts)
+- [PostgreSQL adapter error mapping](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/errors.ts)
diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md
new file mode 100644
index 0000000..99e1be7
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/SKILL.md
@@ -0,0 +1,92 @@
+---
+name: prisma-mongodb-upgrade
+description: Decision and migration guide for Prisma ORM MongoDB projects on v6, which have no upgrade path to v7. Use when a MongoDB project asks about upgrading Prisma, when "upgrade to prisma 7" comes up in a project with provider = "mongodb", or when evaluating a move to Prisma Next. Triggers on "upgrade prisma mongodb", "prisma 7 mongodb", "mongodb prisma migration", "prisma next mongodb".
+license: MIT
+metadata:
+ author: prisma
+ version: "0.1.0"
+---
+
+# Prisma MongoDB Upgrade Path
+
+MongoDB projects are the one Prisma cohort with no road into Prisma 7: **v6 is the terminal
+classic-ORM major for MongoDB, and v7 never ships a MongoDB connector**. The successor path
+is [Prisma Next](https://github.com/prisma/prisma-next), where MongoDB support is in Early
+Access with GA planned after Postgres. This skill frames the real decision — migrate to
+Prisma Next (the encouraged path), or stay on v6 where a hard blocker applies — and carries
+the migration mechanics.
+
+**Never do either of these:**
+
+- Never advise a MongoDB project to "upgrade to Prisma 7". The connector does not exist
+ there. The `prisma-upgrade-v7` guide does not apply to MongoDB projects.
+- Never solve the version question by rewriting the app onto a SQL database. Changing the
+ database engine is a separate, much larger decision that is not yours to make implicitly.
+
+## The version landscape
+
+| Version | MongoDB status |
+|---------|----------------|
+| Prisma ORM v6 | Fully supported (`mongodb` provider); latest 6.x is the current stable path; maintenance line |
+| Prisma ORM v7 | **No MongoDB connector — not an option, ever** |
+| Prisma Next | MongoDB support in **Early Access**, actively developed, GA planned after Postgres — the successor path for MongoDB projects |
+
+## The decision, up front
+
+**Migrating to Prisma Next is the encouraged path.** MongoDB support in Prisma Next is Early
+Access: functional and moving quickly, with GA planned after Postgres — and the Prisma team
+wants MongoDB users to migrate early and share feedback. The migration mechanics are
+detailed in the references.
+
+**Staying on the latest v6 remains a legitimate choice where a hard blocker applies** —
+stated plainly: the Next Mongo façade does not wrap transactions yet (the underlying driver
+is available directly; this is expected to change soon), and pre-1.0 minors can carry
+breaking changes with published upgrade recipes.
+
+### Decision table
+
+| Signal | Direction |
+|--------|-----------|
+| No blockers below apply | Migrate to Next; run the `verify-cutover-checklist` and share feedback with the Prisma team |
+| Greenfield / prototype / internal tool | Migrate to Next |
+| Codebase uses multi-document transactions (`$transaction`) — check with grep, do not ask | Plan raw-driver session equivalents first (see `client-api-mapping`), or stay on v6 until the façade wrapper lands |
+| Team cannot absorb pre-1.0 breaking upgrades between minors | Stay on v6 until GA |
+| Risk-averse but interested | Run a staged Next round-trip on a copy (see `verify-cutover-checklist`), then migrate |
+
+Note: the transactions gap is expected to close soon — this section will be updated when
+façade transactions merge in Prisma Next.
+
+### If staying on v6: hygiene (a deliberate stay, not neglect)
+
+- Pin the Prisma packages to the latest 6.x line and keep taking 6.x patch releases.
+- Track Prisma release notes and security advisories for the 6.x line.
+- Keep the classic v6 MongoDB setup: `url = env("DATABASE_URL")` in the schema, `db push`
+ workflow, no SQL driver adapters (see `prisma-database-setup` for the v6 MongoDB shape).
+- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved.
+
+## Reference files
+
+| Reference | What it covers |
+|-----------|----------------|
+| `references/decision-stay-or-migrate.md` | The full decision framing, blocker checks, and stay-hygiene detail |
+| `references/schema-contract-mapping.md` | v6 schema (`mongodb` provider, `@db.ObjectId`, composite types) → Next contract concepts |
+| `references/client-api-mapping.md` | v6 client calls → Next equivalents, incl. raw escape hatches and transactions — names map, parity does not |
+| `references/migrations-mapping.md` | v6 `db push`-only story → Next's plan/migrate/verify/sign flow |
+| `references/verify-cutover-checklist.md` | No-data-moves verification: same DB, index parity, staged round-trip before cutover |
+
+## Verified against
+
+Behavioral claims about Prisma Next in this skill were verified against
+[prisma/prisma-next](https://github.com/prisma/prisma-next) at commit
+`a2791c5dd59d579b4b3052942ae7f8fe5e2ee852` (pre-1.0, ~v0.14/0.15 line). Prisma Next moves
+quickly in Early Access: **before acting on any Next-side claim, verify it against the
+version actually installed** (check the project's `@prisma-next/*` versions and the
+prisma-next skills installed with it). Next's Mongo target requires MongoDB 8.0+ and expects
+`mongodb@^7` as a user-supplied peer dependency.
+
+## Hand-off rule
+
+This skill is the **discovery bridge**, not a replacement for Prisma Next's own
+documentation. After a project switches to Prisma Next, run Prisma Next's `init`/skill
+installation and follow its own skills (quickstart, contract, queries, migrations, runtime)
+for day-to-day work — do not keep working from this skill's summaries.
diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/client-api-mapping.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/client-api-mapping.md
new file mode 100644
index 0000000..242d2bd
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/client-api-mapping.md
@@ -0,0 +1,61 @@
+# client-api-mapping
+
+How v6 Prisma Client calls map to Prisma Next's Mongo client — names map, parity does not.
+
+## Priority
+
+CRITICAL
+
+## Why It Matters
+
+The v6 and Next client APIs look superficially similar, but none of the v6 MongoDB raw
+methods exist under their old names, aggregation moved to a different lane entirely, and
+transactions go through the driver rather than a façade wrapper. Assuming parity produces
+code that does not compile — or, in the transactions case, code that silently loses
+atomicity.
+
+## The mapping
+
+| v6 call | Prisma Next equivalent | Notes |
+|---------|------------------------|-------|
+| `prisma.user.findMany(...)` | `db.orm.users.where(...).all()` | Fluent ORM lane; storage-name keys (see `schema-contract-mapping.md`) |
+| `prisma.user.findFirst(...)` | `db.orm.users.where(...).first()` | |
+| `create` / `update` / `upsert` / `delete` / `updateMany` / `deleteMany` | `create` / `update` / `upsert` / `delete` / `updateAll` / `deleteAll` on `db.orm.` | See Prisma Next's `prisma-next-queries` skill |
+| `prisma.user.aggregate(...)`, `groupBy(...)` | **No ORM equivalent.** Use the typed aggregation-pipeline builder: `db.query.from(...).match(...).group(...).build()` | Prisma Next's `prisma-next-queries` skill covers the builder lane |
+| `$runCommandRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#runcommandraw)) | **Name does not exist in Next.** Raw lane is `mongoRaw(...)` → a raw collection with `aggregate`, `insertOne/Many`, `updateOne/Many`, `deleteOne/Many`, `findOneAndUpdate/Delete`. For arbitrary database commands, use the underlying `mongodb` driver directly — it is a user-supplied peer dependency and fully accessible | Check the installed version's raw surface |
+| `.findRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#findraw)) | `mongoRaw(...)` collection reads (e.g. `aggregate` with a `$match` stage) | No direct `findRaw` name |
+| `.aggregateRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#aggregateraw)) | `mongoRaw(...).aggregate(...)` or the typed pipeline builder | |
+| `$transaction(...)` — works on v6 with a replica set ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)) | The façade does not wrap `db.transaction(...)` yet, **but the underlying `mongodb` driver is directly available** (user-supplied peer dependency): multi-document atomicity works today via driver sessions (`client.startSession()` / `session.withTransaction(...)`) on a replica set | A façade wrapper is expected soon; this row will be updated when it merges |
+| `$connect` / `$disconnect` | `connect()` / `close()` on the Mongo façade client | |
+
+## Bad
+
+```typescript
+// Assuming v6 names exist in Prisma Next:
+await db.user.$runCommandRaw({ collStats: 'users' }); // no such method
+await db.transaction(async (tx) => { ... }); // no such method on the Mongo façade
+```
+
+## Good
+
+```typescript
+// Raw lane under its Next name:
+const raw = mongoRaw(db);
+await raw.users.aggregate([{ $match: { status: 'active' } }]);
+
+// Aggregation through the typed pipeline builder:
+const stats = await db.query.from('users').group({ _id: '$role', n: { $count: {} } }).build();
+
+// Multi-document atomicity today: the mongodb driver (a direct dependency of the
+// project) exposes sessions and transactions as usual:
+const session = mongoClient.startSession();
+await session.withTransaction(async () => {
+ // ...writes...
+});
+```
+
+## References
+
+- [v6 MongoDB raw queries](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#raw-queries-with-mongodb)
+- [v6 replica set requirement for transactions](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)
+- Prisma Next queries + runtime skills (`skills/prisma-next-queries`, incl. its dedicated `mongo.md`; `skills/prisma-next-runtime`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`
diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/decision-stay-or-migrate.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/decision-stay-or-migrate.md
new file mode 100644
index 0000000..93feda2
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/decision-stay-or-migrate.md
@@ -0,0 +1,87 @@
+# decision-stay-or-migrate
+
+How to decide between migrating a MongoDB project to Prisma Next and staying on Prisma v6.
+
+## Priority
+
+CRITICAL
+
+## Why It Matters
+
+MongoDB projects cannot follow the general "upgrade Prisma" advice: Prisma 7 has no MongoDB
+connector, so the forward path is Prisma Next. Advising an impossible v7 upgrade, or
+silently rewriting the app onto SQL, are both serious failure modes. The encouraged path is
+migrating to Prisma Next — its MongoDB support is Early Access and the Prisma team wants
+early adopters' feedback — with a deliberate stay on v6 where a hard blocker applies.
+
+## The facts the decision rests on
+
+Prisma Next side (verified against prisma/prisma-next @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`;
+status confirmed by the Prisma team 2026-07):
+
+- **MongoDB support is Early Access**, actively developed, with GA planned after Postgres.
+- The implementation is deep, not a stub: a full package family (ORM, typed
+ aggregation-pipeline builder, raw lane, driver over the official `mongodb` package),
+ first-class contract-driven migrations, and extensive tests against real in-memory MongoDB.
+- **The Mongo client façade does not wrap `db.transaction(...)` yet** — multi-document
+ atomicity is done through the MongoDB driver's session API, which is directly available
+ (the `mongodb` package is a user-supplied peer dependency). A façade wrapper is expected;
+ this skill will be updated when it merges.
+- Early Access means pre-1.0 minors can carry breaking changes, with published upgrade
+ recipes (e.g. 0.11→0.12 changed Mongo validator emission and made `mongodb` a
+ user-supplied peer dependency). Floor: MongoDB 8.0 and `mongodb@^7`.
+
+Prisma v6 side:
+
+- v6 fully supports MongoDB, including transactions on replica sets — "MongoDB only allows
+ you to start a transaction on a replica set. Prisma ORM uses transactions internally"
+ ([replica set configuration](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)).
+- v6 MongoDB has no Prisma Migrate; the workflow is `db push`
+ ([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)).
+
+## Blocker checks before migrating
+
+Run these checks yourself — from the codebase, not by asking the user:
+
+- **Search the codebase for `$transaction` usage** (grep for `$transaction`). If present,
+ plan the raw-driver session equivalents before migrating (see `client-api-mapping.md`) —
+ or stay on v6 until the façade wrapper lands.
+- **Check the MongoDB server version** (must be 8.0+ for Next; v6 tolerated older).
+- **Confirm the team can absorb pre-1.0 upgrades.** Next publishes versioned upgrade recipes
+ between minors; someone has to run them. For a production app, confirm the user accepts
+ Early Access status before migrating.
+
+## Bad
+
+```text
+User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?"
+Agent: "Yes — here's the v7 upgrade guide. Step 1: install a driver adapter..."
+```
+
+Prisma 7 has no MongoDB connector; this migration is impossible and the SQL driver-adapter
+steps corrupt a working v6 setup.
+
+## Good
+
+```text
+User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?"
+Agent: "Prisma 7 does not support MongoDB — v6 is the last classic-ORM
+major for MongoDB. The path forward is Prisma Next, the successor: its MongoDB support is
+Early Access and migrating is encouraged. Let me check the codebase for blockers first —
+searching for $transaction usage and checking the MongoDB server version..."
+```
+
+## Stay-on-v6 hygiene
+
+Staying is a decision, not a default-by-neglect:
+
+- Pin `prisma` and `@prisma/client` to the latest 6.x and keep taking 6.x patches.
+- Watch Prisma release notes and security advisories for the 6.x maintenance line.
+- Keep the classic setup (`url = env("DATABASE_URL")` in the schema; `db push`; no SQL
+ driver adapters).
+- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved.
+
+## References
+
+- [Prisma Next repository](https://github.com/prisma/prisma-next)
+- [Prisma v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/migrations-mapping.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/migrations-mapping.md
new file mode 100644
index 0000000..c666428
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/migrations-mapping.md
@@ -0,0 +1,65 @@
+# migrations-mapping
+
+How the v6 MongoDB "no migrations" story maps onto Prisma Next's first-class migration flow.
+
+## Priority
+
+HIGH
+
+## Why It Matters
+
+This is the largest workflow change in the migration — in v6, MongoDB explicitly has no
+Prisma Migrate, while in Prisma Next MongoDB participates in the full migration lifecycle.
+Teams porting a `db push` habit into Next without understanding the plan/verify/sign flow
+will fight the tooling or bypass its safety rails.
+
+## v6: `db push` only
+
+MongoDB on v6 has no Prisma Migrate and no plans to add it — "MongoDB projects do not rely
+on internal schemas" ([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)).
+The workflow is `prisma db push` to sync indexes and unique constraints, with no migration
+history on disk.
+
+## Prisma Next: first-class, contract-driven migrations (Mongo included)
+
+Migration authoring in Next is first-class for Postgres **and Mongo** (prisma-next
+`skills/prisma-next-migrations/SKILL.md`) — MongoDB is not a push-only special case:
+
+- **Flow:** contract *emit* → diff → *plan* (writes a content-hashed migration package) →
+ *migrate* (apply in graph order) → *verify* (live schema vs destination contract) →
+ *sign* (advance the marker after a verify pass).
+- **Mongo migration ops** come from dedicated factories: `createCollection`,
+ `dropCollection`, `validatedCollection`, `setValidation`, `createIndex`, `dropIndex`,
+ `collMod`, and `dataTransform` for data backfills.
+- **Marker storage:** Next records migration state in a document in the
+ `_prisma_migrations` collection (per space) — the same collection name family v6 users
+ know from SQL, repurposed for Mongo state.
+- **DDL is not transactional on Mongo:** the runner applies operations, verifies the live
+ schema against the destination contract, and only advances the marker on a verify pass —
+ making interrupted runs resumable rather than atomic (see Prisma Next's
+ `prisma-next-migrations` skill).
+- **Push-style alternative still exists:** `db update` diffs the live database against the
+ contract and applies directly without writing a migration directory — the closest
+ analogue to the v6 `db push` habit, at the cost of no history.
+- Validators: Next emits closed `$jsonSchema` validators by default since 0.12 (prisma-next
+ `CHANGELOG.md`) — collections gain schema enforcement v6 never applied.
+
+## Bad
+
+```text
+Porting the v6 habit: run the Next equivalent of `db push` for every change in production,
+accumulating no migration history, and hand-editing collections when verification fails.
+```
+
+## Good
+
+```text
+Adopt the Next lifecycle: emit the contract, plan a migration package, apply it with
+migrate, let verify gate the marker, and sign. Reserve `db update` for local prototyping,
+mirroring how `db push` was used on v6.
+```
+
+## References
+
+- [v6: no Prisma Migrate for MongoDB](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)
+- Prisma Next migrations skill (`skills/prisma-next-migrations`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`
diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/schema-contract-mapping.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/schema-contract-mapping.md
new file mode 100644
index 0000000..fae18bb
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/schema-contract-mapping.md
@@ -0,0 +1,52 @@
+# schema-contract-mapping
+
+How v6 MongoDB schema concepts map onto Prisma Next's contract model.
+
+## Priority
+
+HIGH
+
+## Why It Matters
+
+Prisma Next does not consume the v6 `schema.prisma` as-is: the schema becomes a *contract*
+(authored in PSL or TypeScript via the contract builder), and several v6 MongoDB idioms have
+different — or deliberately absent — equivalents. Translating mechanically without knowing
+the mapping produces contracts that fail verification or, worse, silently change collection
+addressing.
+
+## The mapping
+
+| v6 concept | Prisma Next equivalent | Notes |
+|------------|------------------------|-------|
+| `datasource db { provider = "mongodb" }` + `url = env(...)` ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#example)) | `defineConfig` from `@prisma-next/mongo/config` wiring the mongo family/target/adapter/driver descriptors | Next selects MongoDB by importing the `@prisma-next/mongo` façade, not by a provider string in the schema; `prisma-next init` accepts `mongodb` as a target name |
+| `@id @default(auto()) @map("_id") @db.ObjectId` ([using ObjectId](https://www.prisma.io/docs/orm/overview/databases/mongodb#using-objectid)) | ObjectId-typed id field in the Next contract (PSL or TS builder) | Verify the exact attribute surface against the installed Next version's `prisma-next-contract` skill — the contract builder also exposes `index` and `valueObject` |
+| Composite (embedded) types — MongoDB-only in v6 ([composite types](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types)) | Value objects / embedded shapes in the Next contract (`valueObject` in the Mongo contract builder) | Same conceptual role: documents embedded in a parent document |
+| Model names address the client (`prisma.user`) | **Collection storage names** address the ORM: `db.orm.users`, i.e. the `@@map(...)` name or the lowercased model name — not `db.orm.User` | prisma-next `skills/prisma-next/SKILL.md`, `skills/prisma-next-quickstart/SKILL.md`; the most common porting mistake |
+| Indexes declared in schema, applied by `db push` | Indexes are contract-declared and applied through migrations (`createIndex`/`dropIndex` factories) | See `migrations-mapping.md` |
+| No native polymorphism | No schema-layer polymorphism on Mongo either: `@@base`/`@@discriminator` are SQL-only in Next; model an explicit `discriminator` field | prisma-next `skills/prisma-next-contract/SKILL.md` |
+
+## Bad
+
+```typescript
+// Ported from v6 and addressed by model name:
+const user = await db.orm.User.first(); // undefined — Mongo ORM keys are storage names
+```
+
+## Good
+
+```typescript
+// Mongo ORM keys are collection storage names (@@map or lowercased model name):
+const user = await db.orm.users.first();
+```
+
+## Environment requirements
+
+Prisma Next's Mongo target requires MongoDB 8.0+ and `mongodb@^7` installed by the user as a
+peer dependency (prisma-next `CHANGELOG.md`, 0.11→0.12). v6 supports older MongoDB servers,
+so check the server version before planning a migration.
+
+## References
+
+- [v6 MongoDB schema documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
+- [v6 composite types (MongoDB-only)](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types)
+- Prisma Next contract skill (`skills/prisma-next-contract`) in the prisma-next repository — authoritative for the Next side
diff --git a/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/verify-cutover-checklist.md b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/verify-cutover-checklist.md
new file mode 100644
index 0000000..43144c3
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-mongodb-upgrade/references/verify-cutover-checklist.md
@@ -0,0 +1,60 @@
+# verify-cutover-checklist
+
+Verification checklist for a v6 → Prisma Next cutover: the data never moves — only the code does.
+
+## Priority
+
+CRITICAL
+
+## Why It Matters
+
+A v6 → Next migration is a *client and workflow* migration against the **same MongoDB
+database** — there is no data export/import step, and introducing one (or pointing the new
+stack at a fresh database) turns a code migration into an outage. The checklist below keeps
+the cutover observable and reversible.
+
+## Ground rules
+
+- **No data moves.** The Next contract is authored to describe the existing collections;
+ both stacks read the same database during the staged phase.
+- **v6 stays runnable until cutover is verified.** Do not delete the v6 client, schema, or
+ dependencies until the checklist passes.
+
+## Checklist
+
+1. **Same database, verified:** the Next config points at the same connection string /
+ database name the v6 app uses (minus v6-specific URL parameters that the `mongodb@^7`
+ driver rejects — validate the URL with the driver first).
+2. **Server floor:** MongoDB server is 8.0+ (Next's requirement; v6 tolerated older).
+ Confirm before authoring any contract.
+3. **Contract round-trip on a copy:** on a staging copy (or `mongodb-memory-server`), emit
+ the contract, run plan → migrate → verify → sign, and confirm `verify` passes against
+ data copied from production shape. Verification failures here are contract-mapping bugs,
+ not database problems.
+4. **Index parity:** enumerate indexes on every collection (`db.collection.getIndexes()`)
+ and confirm the Next contract declares the same set — v6 `db push` may have created
+ indexes the new contract must re-declare, or verification and query performance will
+ diverge.
+5. **Validator impact assessed:** Next emits closed `$jsonSchema` validators by default;
+ confirm legacy documents (extra fields, drifted shapes) pass them on the staging copy
+ before applying to production.
+6. **Storage-name addressing audited:** every ported call site uses collection storage
+ names (`db.orm.users`), not model names (see `schema-contract-mapping.md`).
+7. **Transaction inventory mapped:** grep the v6 app for `$transaction`; each hit gets a
+ driver-session equivalent (the `mongodb` driver is directly available; the façade wrapper
+ is expected soon — see `client-api-mapping.md`).
+8. **Raw call inventory mapped:** every `$runCommandRaw` / `findRaw` / `aggregateRaw` call
+ has an explicit Next-side replacement (`mongoRaw(...)` lane or pipeline builder).
+9. **Staged read-only soak:** run the Next stack read-only against staging/production data
+ alongside v6 and compare outputs before allowing writes.
+10. **Cutover + rollback:** switch writes to Next only after the soak; keep the v6 branch
+ deployable as the rollback path. Rolling back is a code rollback — the data was never
+ moved.
+
+After cutover, install and follow Prisma Next's own skills for ongoing work (see the
+hand-off rule in `SKILL.md`).
+
+## References
+
+- [v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
+- Prisma Next migrations + queries skills — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`
diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md b/apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md
new file mode 100644
index 0000000..2f9925e
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres-setup/SKILL.md
@@ -0,0 +1,263 @@
+---
+name: prisma-postgres-setup
+description: Set up a new Prisma Postgres database and connect it to a local project using the Management API. Use when asked to "set up a database", "create a Prisma Postgres project", "get a connection string", "connect my app to Prisma Postgres", or "provision a database".
+license: MIT
+metadata:
+ author: prisma
+ version: "1.1.0"
+---
+
+# Prisma Postgres Setup
+
+Procedural skill that guides you through provisioning a new Prisma Postgres database via the Management API and connecting it to a local project.
+
+## When to Apply
+
+Use this skill when:
+
+- Setting up a new Prisma Postgres database for a project
+- Creating a Prisma Postgres project and connecting it locally
+- Obtaining a connection string for Prisma Postgres
+- Provisioning a database via the Management API (not the Console UI)
+
+Do **not** use this skill when:
+
+- Setting up CI/CD preview databases — use `prisma-postgres-cicd`
+- Building multi-tenant database provisioning into an app — use `prisma-postgres-integrator`
+- Working with a database that already exists and is connected (schema/migration tasks are standard Prisma CLI)
+
+## Prerequisites
+
+- Node.js 18+
+- A Prisma Postgres workspace (create one at https://console.prisma.io if needed)
+- A workspace service token (see `references/auth.md`)
+
+## UX Guidelines
+
+When presenting choices to the user (region selection, project deletion, etc.), **use your platform's interactive selection mechanism** (e.g., `ask` tool in Claude Code, structured prompts in other agents). Do not print static tables and ask the user to type a value — present selectable options so the user can pick with minimal effort.
+
+## Workflow
+
+Follow these steps in order. Each step includes the API call to make and how to handle the response.
+
+### Step 1: Authenticate
+
+You need a service token. Try these methods in order:
+
+**1a. Token in the user's prompt**
+
+Check if the user included a service token in their initial message (e.g., "Set up Prisma Postgres with token eyJ..."). If so, use it **exactly as provided** — do not truncate, re-encode, or round-trip it through a file. Store it in a shell variable for subsequent calls.
+
+**1b. Token in the environment**
+
+Check for `PRISMA_SERVICE_TOKEN` in the environment or `.env` file.
+
+**1c. Ask the user to create one**
+
+If no token is available, instruct the user:
+
+> Create a service token in Prisma Console → Workspace Settings → Service Tokens.
+> Copy the token and paste it here.
+
+Read `references/auth.md` for details on service token creation.
+
+Once you have a token, store it in a shell variable (`PRISMA_SERVICE_TOKEN`) and use it for all subsequent API calls.
+
+### Step 2: List available regions
+
+Fetch the list of available Prisma Postgres regions to let the user choose where to deploy.
+
+```bash
+curl -s -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
+ https://api.prisma.io/v1/regions/postgres
+```
+
+The response contains an array of regions with `id`, `name`, and `status`. Only present regions where `status` is `available`.
+
+**Present the regions as an interactive menu** — let the user pick from options rather than typing a region ID manually.
+
+Read `references/endpoints.md` for the full response shape.
+
+### Step 3: Create a project with a database
+
+```bash
+curl -s -X POST https://api.prisma.io/v1/projects \
+ -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "",
+ "region": "",
+ "createDatabase": true
+ }'
+```
+
+Use the current directory name as the project name by default.
+
+The response is wrapped in `{ "data": { ... } }`. Extract:
+
+- `data.id` — the project ID (prefixed with `proj_`)
+- `data.database.id` — the database ID (prefixed with `db_`)
+- `data.database.connections[0].endpoints.direct.connectionString` — the direct PostgreSQL connection string
+
+Use the **direct** connection string (`endpoints.direct.connectionString`). Do not use the pooled or accelerate endpoints — those are for legacy Accelerate setups and not needed for new projects.
+
+If the response status is `provisioning`, wait a few seconds and poll `GET /v1/databases/` until `status` is `ready`.
+
+**If creation fails due to a database limit**, list the user's existing projects and present them as an interactive menu for deletion. After the user picks one, delete it and retry.
+
+Read `references/endpoints.md` for the full request/response shapes.
+
+### Step 4: Create a named connection (optional)
+
+If you need a dedicated connection (e.g., per-developer or per-environment), create one:
+
+```bash
+curl -s -X POST https://api.prisma.io/v1/databases//connections \
+ -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{ "name": "dev" }'
+```
+
+Extract the direct connection string from `data.endpoints.direct.connectionString`.
+
+### Step 5: Configure the local project
+
+1. Install dependencies:
+
+```bash
+npm install prisma @prisma/client @prisma/adapter-pg pg dotenv
+```
+
+All five packages are required:
+- `prisma` — CLI for migrations, schema push, client generation
+- `@prisma/client` — the generated query client
+- `@prisma/adapter-pg` — Prisma 7 driver adapter for direct PostgreSQL connections
+- `pg` — Node.js PostgreSQL driver (used by the adapter)
+- `dotenv` — loads `.env` variables for `prisma.config.ts`
+
+2. Write the direct connection string to `.env`. **Append** to the file if it already exists — do not overwrite existing entries:
+
+```
+DATABASE_URL=""
+```
+
+3. Verify `.gitignore` includes `.env`. Create `.gitignore` if it does not exist. Warn the user if `.env` is not gitignored.
+
+4. Ensure `package.json` has `"type": "module"` set (Prisma 7 generates ESM output).
+
+5. If `prisma/schema.prisma` does not exist, run `npx prisma init` to scaffold the project. This creates both `prisma/schema.prisma` and `prisma.config.ts`.
+
+6. Ensure `schema.prisma` has the `postgresql` provider and **no** `url` or `directUrl` in the datasource block (Prisma 7 manages connection URLs in `prisma.config.ts`, not in the schema):
+
+```prisma
+datasource db {
+ provider = "postgresql"
+}
+```
+
+7. Ensure `prisma.config.ts` loads the connection URL from the environment:
+
+```typescript
+import path from 'node:path'
+import { defineConfig } from 'prisma/config'
+import 'dotenv/config'
+
+export default defineConfig({
+ earlyAccess: true,
+ schema: path.join(import.meta.dirname, 'prisma', 'schema.prisma'),
+ datasource: {
+ url: process.env.DATABASE_URL!,
+ },
+})
+```
+
+**Important Prisma 7 notes:**
+- Connection URLs go in `prisma.config.ts`, never in `schema.prisma`
+- The provider in `schema.prisma` must be `"postgresql"` (not `"prismaPostgres"`)
+- `dotenv/config` must be imported in `prisma.config.ts` to load `.env` variables
+
+### Step 6: Define schema and push
+
+If the schema already has models, skip to pushing. Otherwise, **present these options as an interactive menu**:
+
+1. **"I'll define my schema manually"** — Tell the user to edit `prisma/schema.prisma` and come back when ready. Wait for them before proceeding.
+2. **"Give me a starter schema"** — Add a Blog starter schema (User, Post, Comment with relations) to `prisma/schema.prisma`. Show the user what was added and ask if they want to adjust it before pushing.
+3. **"I'll describe what I need"** — Ask the user to describe their data model in natural language (e.g., "I'm building a task manager with projects, tasks, and team members"). Generate a schema from the description, show it, and ask for confirmation before pushing.
+
+Once the schema has models and the user is ready, create a migration and generate the client:
+
+```bash
+npx prisma migrate dev --name init
+```
+
+This creates migration files in `prisma/migrations/` **and** generates the client in one step. Migration history is essential for CI/CD workflows (`prisma migrate deploy`) and production deployments.
+
+Only use `npx prisma db push` if the user explicitly asks for prototyping-only mode (no migration history). In that case, follow it with `npx prisma generate`.
+
+### Step 7: Verify the connection
+
+After generating the client, create and run a quick verification script to confirm everything works end-to-end. This is **critical** — do not skip this step.
+
+Create a file named `test-connection.ts`:
+
+```typescript
+import 'dotenv/config'
+import pg from 'pg'
+import { PrismaPg } from '@prisma/adapter-pg'
+import { PrismaClient } from './generated/prisma/client.js'
+
+const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
+const adapter = new PrismaPg(pool)
+const prisma = new PrismaClient({ adapter })
+
+const result = await prisma.$queryRawUnsafe('SELECT 1 as connected')
+console.log('Connected to Prisma Postgres:', result)
+
+await prisma.$disconnect()
+await pool.end()
+```
+
+Run it:
+
+```bash
+npx tsx test-connection.ts
+```
+
+**Prisma 7 client instantiation rules:**
+- Import from `./generated/prisma/client.js` (not `./generated/prisma`)
+- Create a `pg.Pool` with the `DATABASE_URL` connection string
+- Wrap it in a `PrismaPg` adapter
+- Pass `{ adapter }` to the `PrismaClient` constructor
+- Do **not** use `datasourceUrl` — that option does not exist in Prisma 7
+- Do **not** use `new PrismaClient()` with no arguments — it will throw
+
+After verification succeeds, delete `test-connection.ts`.
+
+Then share links for the user to explore their database:
+
+- **Prisma Studio (CLI):** `npx prisma studio` — opens a visual data browser locally
+- **Console:** `https://console.prisma.io////dashboard` — strip the prefixes (`wksp_`, `proj_`, `db_`) from the IDs returned in Step 3 to build this URL
+
+Read `references/prisma7-client.md` for the full client instantiation reference.
+
+## Error Handling
+
+Read `references/api-basics.md` for the full error reference. Key self-correction patterns:
+
+| HTTP Status | Error Code | Action |
+|---|---|---|
+| 401 | `authentication-failed` | Service token is invalid or expired. Ask the user to create a new one in Console → Workspace Settings → Service Tokens. |
+| 404 | `resource-not-found` | Check that the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). |
+| 422 | `validation-error` | Check request body against the endpoint schema. Common: missing `name`, invalid `region`. |
+| 429 | `rate-limit-exceeded` | Back off and retry after a few seconds. |
+
+## Reference Files
+
+Detailed API and usage information is in:
+
+```
+references/auth.md — Service token creation and usage
+references/api-basics.md — Base URL, envelope, IDs, errors, pagination
+references/endpoints.md — Endpoint details for projects, databases, connections, regions
+references/prisma7-client.md — Prisma 7 client instantiation and usage patterns
+```
diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/api-basics.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/api-basics.md
new file mode 100644
index 0000000..272fff4
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/api-basics.md
@@ -0,0 +1,102 @@
+# api-basics
+
+Core conventions for the Prisma Management API. All three `prisma-postgres-*` skills share these patterns.
+
+## Base URL
+
+```
+https://api.prisma.io/v1
+```
+
+API documentation: https://api.prisma.io/v1/doc
+
+## Response Envelope
+
+### Single resource
+
+```json
+{
+ "data": {
+ "id": "proj_clx7abc123def456",
+ "type": "project",
+ "name": "My Project",
+ "createdAt": "2025-06-15T10:30:00.000Z"
+ }
+}
+```
+
+### Collection
+
+```json
+{
+ "data": [
+ { "id": "proj_aaa", "type": "project", "name": "Alpha" },
+ { "id": "proj_bbb", "type": "project", "name": "Beta" }
+ ],
+ "pagination": {
+ "hasMore": true,
+ "nextCursor": "clx7cursor123"
+ }
+}
+```
+
+## Resource ID Prefixes
+
+Every resource ID carries a type prefix:
+
+| Prefix | Resource |
+|---|---|
+| `proj_` | Project |
+| `db_` | Database |
+| `con_` | Connection |
+| `wksp_` | Workspace |
+
+Always include the prefix when sending IDs in API requests.
+
+## Pagination
+
+Collection endpoints use cursor-based pagination:
+
+```
+GET /v1/projects?limit=10
+GET /v1/projects?cursor=clx7abc123&limit=10
+```
+
+| Parameter | Type | Default | Description |
+|---|---|---|---|
+| `cursor` | string | — | Opaque cursor from `nextCursor` |
+| `limit` | number | 100 | Maximum items per page |
+
+Continue fetching while `pagination.hasMore` is `true`, using `pagination.nextCursor` as the `cursor` parameter.
+
+## Error Responses
+
+All errors follow this shape:
+
+```json
+{
+ "error": {
+ "code": "resource-not-found",
+ "message": "database with id db_abc not found"
+ }
+}
+```
+
+### Error codes by HTTP status
+
+| HTTP Status | Error Code | Meaning |
+|---|---|---|
+| 400 | `client-error` | Malformed request |
+| 401 | `authentication-failed` | Missing or invalid token |
+| 403 | `permission-denied` | Token lacks required access |
+| 404 | `resource-not-found` | Resource does not exist or is not accessible |
+| 422 | `validation-error` | Request body failed validation |
+| 429 | `rate-limit-exceeded` | Too many requests |
+| 500 | `internal-server-error` | Server error — retry after a delay |
+
+### Self-correction patterns
+
+- **401**: Token is invalid or expired. Create a new service token in Console → Workspace Settings → Service Tokens.
+- **404**: Verify the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). Use `GET /v1/projects` or `GET /v1/databases` to list available resources.
+- **422**: Check the request body against the endpoint schema. Common issues: missing required fields, invalid region ID, empty `name`.
+- **429**: Wait 2–5 seconds and retry. If repeated, increase the backoff interval.
diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/auth.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/auth.md
new file mode 100644
index 0000000..b341a41
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/auth.md
@@ -0,0 +1,46 @@
+# auth
+
+How to authenticate with the Prisma Management API using service tokens.
+
+## Service Tokens
+
+Service tokens authenticate server-to-server requests. They are scoped to a workspace and grant access to all resources within it.
+
+### Creating a service token
+
+1. Open https://console.prisma.io
+2. Navigate to **Workspace Settings** → **Service Tokens**
+3. Click **Create Token**
+4. Copy the token immediately — it is only shown once
+
+### Using a service token
+
+Set the token as an environment variable:
+
+```bash
+export PRISMA_SERVICE_TOKEN="eyJ..."
+```
+
+Include it in the `Authorization` header of every API request:
+
+```bash
+curl -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
+ https://api.prisma.io/v1/projects
+```
+
+### Token scope
+
+Service tokens are workspace-scoped. A single token grants access to all projects, databases, and connections within the workspace. There are no project-scoped tokens at this time.
+
+### Security practices
+
+- Store tokens in environment variables or secret managers, never in source code
+- Add `.env` to `.gitignore` to prevent accidental commits
+- Rotate tokens periodically via Console → Workspace Settings → Service Tokens
+- In CI/CD, store tokens as encrypted secrets (e.g., GitHub Secrets)
+
+## OAuth 2.0 (for user-scoped access)
+
+OAuth is used when acting on behalf of a user, typically in partner/integrator flows. See the `prisma-postgres-integrator` skill for OAuth details.
+
+For standard database setup, service tokens are the recommended authentication method.
diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/endpoints.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/endpoints.md
new file mode 100644
index 0000000..f5c9713
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/endpoints.md
@@ -0,0 +1,223 @@
+# endpoints
+
+Management API endpoint details for database setup workflows.
+
+## List regions
+
+```
+GET /v1/regions/postgres
+```
+
+No request body. Returns available Prisma Postgres regions.
+
+**Response:**
+
+```json
+{
+ "data": [
+ {
+ "id": "us-east-1",
+ "type": "region",
+ "name": "US East (N. Virginia)",
+ "status": "available"
+ },
+ {
+ "id": "eu-west-1",
+ "type": "region",
+ "name": "EU West (Ireland)",
+ "status": "available"
+ }
+ ]
+}
+```
+
+Only use regions where `status` is `available`.
+
+## Create project (with database)
+
+```
+POST /v1/projects
+```
+
+**Request body:**
+
+```json
+{
+ "name": "my-project",
+ "region": "us-east-1",
+ "createDatabase": true
+}
+```
+
+| Field | Type | Required | Default | Description |
+|---|---|---|---|---|
+| `name` | string | No | Auto-generated | Project display name |
+| `region` | string | No | `us-east-1` | Region for the database |
+| `createDatabase` | boolean | No | `true` | Create a default database with the project |
+
+**Response** (with `createDatabase: true`):
+
+```json
+{
+ "data": {
+ "id": "proj_clx7abc123",
+ "type": "project",
+ "url": "https://api.prisma.io/v1/projects/proj_clx7abc123",
+ "name": "my-project",
+ "createdAt": "2025-06-15T10:30:00.000Z",
+ "defaultRegion": "us-east-1",
+ "workspace": {
+ "id": "wksp_xyz789",
+ "url": "https://api.prisma.io/v1/workspaces/wksp_xyz789",
+ "name": "My Workspace"
+ },
+ "database": {
+ "id": "db_def456",
+ "type": "database",
+ "url": "https://api.prisma.io/v1/databases/db_def456",
+ "name": "my-project",
+ "status": "ready",
+ "createdAt": "2025-06-15T10:30:00.000Z",
+ "isDefault": true,
+ "defaultConnectionId": "con_ghi789",
+ "connections": [
+ {
+ "id": "con_ghi789",
+ "type": "connection",
+ "url": "https://api.prisma.io/v1/connections/con_ghi789",
+ "name": "Default",
+ "createdAt": "2025-06-15T10:30:00.000Z",
+ "kind": "postgres",
+ "endpoints": {
+ "direct": {
+ "host": "db.prisma.io",
+ "port": 5432,
+ "connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require"
+ }
+ }
+ }
+ ],
+ "region": {
+ "id": "us-east-1",
+ "name": "US East (N. Virginia)"
+ }
+ }
+ }
+}
+```
+
+Key field to extract:
+
+- `data.database.connections[0].endpoints.direct.connectionString` → use as `DATABASE_URL`
+
+The response also includes `pooled` and `accelerate` endpoints — ignore these for new projects. The direct connection string is all you need.
+
+If `data.database.status` is `provisioning`, poll `GET /v1/databases/{id}` until `status` is `ready`.
+
+## Get database
+
+```
+GET /v1/databases/{databaseId}
+```
+
+Use to check database status after creation or to retrieve database details.
+
+**Response:**
+
+```json
+{
+ "data": {
+ "id": "db_def456",
+ "type": "database",
+ "url": "https://api.prisma.io/v1/databases/db_def456",
+ "name": "my-project",
+ "status": "ready",
+ "createdAt": "2025-06-15T10:30:00.000Z",
+ "isDefault": true,
+ "defaultConnectionId": "con_ghi789",
+ "connections": [],
+ "project": {
+ "id": "proj_clx7abc123",
+ "url": "https://api.prisma.io/v1/projects/proj_clx7abc123",
+ "name": "my-project"
+ },
+ "region": {
+ "id": "us-east-1",
+ "name": "US East (N. Virginia)"
+ }
+ }
+}
+```
+
+## Create connection
+
+```
+POST /v1/databases/{databaseId}/connections
+```
+
+Creates a new named connection string for a database. Use for per-developer or per-environment connections.
+
+**Request body:**
+
+```json
+{
+ "name": "dev"
+}
+```
+
+| Field | Type | Required | Description |
+|---|---|---|---|
+| `name` | string | Yes | Display name for the connection |
+
+**Response:**
+
+```json
+{
+ "data": {
+ "id": "con_newcon123",
+ "type": "connection",
+ "url": "https://api.prisma.io/v1/connections/con_newcon123",
+ "name": "dev",
+ "createdAt": "2025-06-15T10:31:00.000Z",
+ "kind": "postgres",
+ "endpoints": {
+ "direct": {
+ "host": "db.prisma.io",
+ "port": 5432,
+ "connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require"
+ }
+ },
+ "database": {
+ "id": "db_def456",
+ "url": "https://api.prisma.io/v1/databases/db_def456",
+ "name": "my-project"
+ }
+ }
+}
+```
+
+Extract: `data.endpoints.direct.connectionString` → use as `DATABASE_URL`.
+
+## Delete database
+
+```
+DELETE /v1/databases/{databaseId}
+```
+
+Permanently deletes a database and all its connections. Returns `204 No Content` on success.
+
+## List projects
+
+```
+GET /v1/projects
+```
+
+Returns all projects in the workspace. Supports cursor-based pagination (`?cursor=...&limit=...`).
+
+## Delete project
+
+```
+DELETE /v1/projects/{projectId}
+```
+
+Permanently deletes a project and all its databases. Returns `204 No Content` on success.
diff --git a/apps/backend/.agents/skills/prisma-postgres-setup/references/prisma7-client.md b/apps/backend/.agents/skills/prisma-postgres-setup/references/prisma7-client.md
new file mode 100644
index 0000000..6fbc003
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres-setup/references/prisma7-client.md
@@ -0,0 +1,82 @@
+# Prisma 7 Client Instantiation
+
+Prisma 7 changed how PrismaClient connects to databases. The CLI (`prisma db push`, `prisma migrate`) reads the URL from `prisma.config.ts`. But at **runtime**, you must provide a driver adapter to PrismaClient explicitly.
+
+## Required packages
+
+```bash
+npm install @prisma/client @prisma/adapter-pg pg
+```
+
+- `@prisma/adapter-pg` — the Prisma adapter for the `pg` PostgreSQL driver
+- `pg` — the underlying Node.js PostgreSQL driver
+
+## Basic instantiation
+
+```typescript
+import 'dotenv/config'
+import pg from 'pg'
+import { PrismaPg } from '@prisma/adapter-pg'
+import { PrismaClient } from './generated/prisma/client.js'
+
+const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
+const adapter = new PrismaPg(pool)
+const prisma = new PrismaClient({ adapter })
+```
+
+## Key rules
+
+1. **Import path**: Always `./generated/prisma/client.js` — not `./generated/prisma` and not `@prisma/client`.
+
+2. **Adapter is mandatory**: `new PrismaClient()` with no arguments throws. `new PrismaClient({ datasourceUrl: '...' })` also throws — `datasourceUrl` does not exist in Prisma 7.
+
+3. **ESM required**: The generated client uses ESM. Ensure `package.json` has `"type": "module"`.
+
+4. **Pool lifecycle**: Call `await pool.end()` when shutting down (after `prisma.$disconnect()`).
+
+## Usage in application code
+
+```typescript
+import 'dotenv/config'
+import pg from 'pg'
+import { PrismaPg } from '@prisma/adapter-pg'
+import { PrismaClient } from './generated/prisma/client.js'
+
+const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
+const adapter = new PrismaPg(pool)
+const prisma = new PrismaClient({ adapter })
+
+// Create
+const user = await prisma.user.create({
+ data: { email: 'alice@example.com', name: 'Alice' },
+})
+
+// Read with relations
+const posts = await prisma.post.findMany({
+ where: { published: true },
+ include: { author: true },
+})
+
+// Update
+await prisma.post.update({
+ where: { id: 1 },
+ data: { published: true },
+})
+
+// Delete
+await prisma.post.delete({ where: { id: 1 } })
+
+// Cleanup
+await prisma.$disconnect()
+await pool.end()
+```
+
+## Common mistakes
+
+| Mistake | Error | Fix |
+|---|---|---|
+| `import { PrismaClient } from './generated/prisma'` | `Cannot find module` | Use `./generated/prisma/client.js` |
+| `new PrismaClient()` | `PrismaClient needs non-empty options` | Pass `{ adapter }` |
+| `new PrismaClient({ datasourceUrl: url })` | `Unknown property datasourceUrl` | Use adapter pattern instead |
+| Missing `"type": "module"` in package.json | ESM import errors | Add `"type": "module"` |
+| `import { PrismaClient } from '@prisma/client'` | Wrong export | Use `./generated/prisma/client.js` |
diff --git a/apps/backend/.agents/skills/prisma-postgres/SKILL.md b/apps/backend/.agents/skills/prisma-postgres/SKILL.md
new file mode 100644
index 0000000..568543f
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres/SKILL.md
@@ -0,0 +1,145 @@
+---
+name: prisma-postgres
+description: Prisma Postgres setup and operations guidance across Console, create-db CLI, Management API, and Management API SDK. Use when creating Prisma Postgres databases, working in Prisma Console, provisioning with create-db/create-pg/create-postgres, or integrating programmatic provisioning with service tokens or OAuth.
+license: MIT
+metadata:
+ author: prisma
+ version: "7.9.1"
+---
+
+# Prisma Postgres
+
+Guidance for creating, managing, and integrating Prisma Postgres across interactive and programmatic workflows.
+
+## When to Apply
+
+Reference this skill when:
+- Setting up Prisma Postgres from Prisma Console
+- Provisioning instant temporary databases with `create-db`
+- Linking an existing local project with `prisma postgres link`
+- Managing Prisma Postgres resources via Management API
+- Using `@prisma/management-api-sdk` in TypeScript/JavaScript
+- Handling claim URLs, connection strings, regions, and auth flows
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | CLI Provisioning | CRITICAL | `create-db-cli` |
+| 2 | Management API | CRITICAL | `management-api` |
+| 3 | Management API SDK | HIGH | `management-api-sdk` |
+| 4 | Console and Connections | HIGH | `console-and-connections` |
+
+## Quick Reference
+
+- `create-db-cli` - instant databases and current CLI flags (`--ttl`, `--copy`, `--quiet`, `--open`)
+- `management-api` - service token and OAuth API workflows
+- `management-api-sdk` - typed SDK usage with token storage
+- `console-and-connections` - Console operations, `prisma postgres link`, direct TCP connections, and serverless-driver choices
+
+## Core Workflows
+
+### 1. Console-first workflow
+
+Use Prisma Console for manual setup and operations:
+
+- Open `https://console.prisma.io`
+- Create/select workspace and project
+- Use Studio in the project sidebar to view/edit data
+- Retrieve direct connection details from the project UI
+
+### 2. Quick provisioning with create-db
+
+Use `create-db` when you need a database immediately:
+
+```bash
+npx create-db@latest
+```
+
+Aliases:
+
+```bash
+npx create-pg@latest
+npx create-postgres@latest
+```
+
+For app integrations, you can also use the programmatic API (`create()` / `regions()`) from the `create-db` npm package.
+
+Temporary databases auto-delete after ~24 hours unless claimed.
+
+### 2b. Persistent databases with the Platform CLI
+
+For databases that belong to a Project (not throwaway `create-db` databases), use `@prisma/cli`:
+
+```bash
+npx -y @prisma/cli@latest database create --help
+npx -y @prisma/cli@latest database list --json
+npx -y @prisma/cli@latest database connection create db_123
+npx -y @prisma/cli@latest database usage db_123
+npx -y @prisma/cli@latest database backup list db_123
+```
+
+`database create` and `database connection create` print a one-time connection URL; store it immediately. Destructive commands (`remove`, `restore`) require exact `--confirm `.
+
+For automation, prefer `--json --no-interactive`, resolve ids before mutations, and verify the installed command's help because this CLI is beta.
+
+### 3. Link an existing local project
+
+Use `prisma postgres link` when the database already exists and you want to wire a local project to it:
+
+```bash
+prisma postgres link
+```
+
+For CI or other non-interactive environments:
+
+```bash
+prisma postgres link --api-key "" --database "db_..."
+```
+
+This flow updates your local `.env` with `DATABASE_URL`, then you can run `prisma generate` and `prisma migrate dev`.
+
+### 4. Programmatic provisioning with Management API
+
+Use API endpoints on:
+
+```text
+https://api.prisma.io/v1
+```
+
+Explore the schema and endpoints using:
+
+- OpenAPI docs: `https://api.prisma.io/v1/doc`
+- Swagger Editor: `https://api.prisma.io/v1/swagger-editor`
+
+Auth options:
+
+- Service token (workspace server-to-server)
+- OAuth 2.0 (act on behalf of users)
+
+### 5. Type-safe integration with Management API SDK
+
+Install and use:
+
+```bash
+npm install @prisma/management-api-sdk
+```
+
+Use `createManagementApiClient` for existing tokens, or `createManagementApiSdk` for OAuth + token refresh.
+
+The SDK exposes typed workspace service-token list, create, and revoke routes. A newly created token value is returned exactly once. Let the installed SDK types or OpenAPI document settle exact beta endpoint shapes.
+
+## Rule Files
+
+Detailed guidance lives in:
+
+```
+references/console-and-connections.md
+references/create-db-cli.md
+references/management-api.md
+references/management-api-sdk.md
+```
+
+## How to Use
+
+Start with `references/create-db-cli.md` for fast setup, then switch to `references/management-api.md` or `references/management-api-sdk.md` when you need programmatic provisioning.
diff --git a/apps/backend/.agents/skills/prisma-postgres/references/console-and-connections.md b/apps/backend/.agents/skills/prisma-postgres/references/console-and-connections.md
new file mode 100644
index 0000000..4025d12
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres/references/console-and-connections.md
@@ -0,0 +1,69 @@
+# console-and-connections
+
+Use Prisma Console workflows for project visibility, data inspection, and connection setup.
+
+## Priority
+
+HIGH
+
+## Why It Matters
+
+Many Prisma Postgres tasks are quickest in the Console: viewing Studio data, checking metrics, and retrieving connection details. This avoids unnecessary API or CLI work for simple operational tasks.
+
+## Console workflow
+
+1. Open `https://console.prisma.io`.
+2. Select workspace and project.
+3. Use dashboard metrics for usage and billing visibility.
+4. Open the **Studio** tab in the sidebar to inspect and edit data.
+
+## Local Studio
+
+You can also inspect data locally:
+
+```bash
+npx prisma studio
+```
+
+## Linking an existing project
+
+If the Prisma Postgres database already exists, link the local project instead of provisioning a new one:
+
+```bash
+prisma postgres link
+```
+
+For CI or non-interactive usage:
+
+```bash
+prisma postgres link --api-key "" --database "db_..."
+```
+
+This command updates or creates `.env` with `DATABASE_URL`. If the project is already linked, use `--force` to re-link. After linking, run `prisma generate`, then `prisma migrate dev` if you need to apply the schema.
+
+## Connection setup
+
+For direct PostgreSQL tools and drivers:
+
+- Generate/copy direct connection credentials from the project connection UI.
+- Use the resulting PostgreSQL URL as `DATABASE_URL` for `pg` and `@prisma/adapter-pg`.
+- For Prisma Postgres direct TCP, include `sslmode=require`.
+
+Typical direct TCP format:
+
+```env
+DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require"
+```
+
+Management API connection responses expose both `endpoints.direct` (`db.prisma.io:5432`) and `endpoints.pooled` (`pooled.db.prisma.io:5432`); prefer those fields over the deprecated flat `connectionString`. Connection secrets are shown once at creation (one-time view); store them immediately.
+
+## Adapter choices
+
+- Standard Node.js apps: prefer `@prisma/adapter-pg` with the direct TCP URL above.
+- Edge/serverless runtimes: use `@prisma/adapter-ppg` with `@prisma/ppg` only when you specifically need the Prisma Postgres serverless driver.
+
+## References
+
+- [Prisma Postgres overview](https://www.prisma.io/docs/postgres/introduction/overview)
+- [Viewing data](https://www.prisma.io/docs/postgres/integrations/viewing-data)
+- [Direct connections](https://www.prisma.io/docs/postgres/database/direct-connections)
diff --git a/apps/backend/.agents/skills/prisma-postgres/references/create-db-cli.md b/apps/backend/.agents/skills/prisma-postgres/references/create-db-cli.md
new file mode 100644
index 0000000..7359b78
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres/references/create-db-cli.md
@@ -0,0 +1,136 @@
+# create-db-cli
+
+Use `create-db` for instant Prisma Postgres provisioning from the terminal.
+
+## Priority
+
+CRITICAL
+
+## Why It Matters
+
+`create-db` is the fastest way to get a working Prisma Postgres instance for development, demos, and CI previews. It can also emit machine-readable output and write env variables directly.
+
+## Commands
+
+```bash
+npx create-db@latest
+npx create-db@latest create [options]
+npx create-db@latest regions
+```
+
+Aliases:
+
+```bash
+npx create-pg@latest
+npx create-postgres@latest
+```
+
+## Command discovery (`--help`)
+
+Always use `--help` first when integrating CLI commands:
+
+```bash
+npx create-db@latest --help
+npx create-db@latest create --help
+npx create-db@latest regions --help
+```
+
+Top-level commands currently exposed:
+
+- `create` (default) to provision a database
+- `regions` to list available regions
+
+## `create` options
+
+| Flag | Shorthand | Description |
+|---|---|---|
+| `--region [string]` | `-r` | Region choice: `ap-southeast-1`, `ap-northeast-1`, `eu-central-1`, `eu-west-3`, `us-east-1`, `us-west-1` |
+| `--interactive [boolean]` | `-i` | Open region selector |
+| `--json [boolean]` | `-j` | Output machine-readable JSON |
+| `--env [string]` | `-e` | Write `DATABASE_URL` and `CLAIM_URL` into a target `.env` |
+| `--ttl [string]` | `-t` | Auto-delete after a TTL like `30m` or `1h-24h` |
+| `--copy [boolean]` | `-c` | Copy the connection string to the clipboard |
+| `--quiet [boolean]` | `-q` | Only print the connection string |
+| `--open [boolean]` | `-o` | Open the claim URL in your browser |
+
+## Lifecycle and claim flow
+
+- Databases are temporary by default.
+- Unclaimed databases are auto-deleted after ~24 hours.
+- Claim the database using the URL shown in command output to keep it permanently.
+
+## Programmatic usage (library API)
+
+You can also use `create-db` programmatically in Node.js/Bun instead of shelling out to the CLI.
+
+Install:
+
+```bash
+npm install create-db
+# or
+bun add create-db
+```
+
+Create a database:
+
+```ts
+import { create, isDatabaseSuccess, isDatabaseError } from "create-db";
+
+const result = await create({
+ region: "us-east-1",
+ userAgent: "my-app/1.0.0",
+});
+
+if (isDatabaseSuccess(result)) {
+ console.log(result.connectionString);
+ console.log(result.claimUrl);
+ console.log(result.deletionDate);
+}
+
+if (isDatabaseError(result)) {
+ console.error(result.error, result.message);
+}
+```
+
+List regions programmatically:
+
+```ts
+import { regions } from "create-db";
+
+const available = await regions();
+console.log(available);
+```
+
+Programmatic `create()` defaults to `us-east-1` if no region is passed.
+
+## Common patterns
+
+```bash
+# quick database
+npx create-db@latest
+
+# region-specific database
+npx create-db@latest --region eu-central-1
+
+# interactive region selection
+npx create-db@latest --interactive
+
+# write env vars for app bootstrap
+npx create-db@latest --env .env
+
+# auto-delete sooner
+npx create-db@latest --ttl 2h
+
+# copy connection string to clipboard
+npx create-db@latest --copy
+
+# print only the connection string
+npx create-db@latest --quiet
+
+# CI-friendly output
+npx create-db@latest --json
+```
+
+## References
+
+- [npx create-db docs](https://www.prisma.io/docs/postgres/introduction/npx-create-db)
diff --git a/apps/backend/.agents/skills/prisma-postgres/references/management-api-sdk.md b/apps/backend/.agents/skills/prisma-postgres/references/management-api-sdk.md
new file mode 100644
index 0000000..026aa5f
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres/references/management-api-sdk.md
@@ -0,0 +1,70 @@
+# management-api-sdk
+
+Use `@prisma/management-api-sdk` for typed API integration with optional OAuth and token refresh.
+
+The Platform API evolves independently from Prisma ORM. Inspect the installed package's generated `api.d.ts` for exact paths and request/response shapes.
+
+## Priority
+
+HIGH
+
+## Why It Matters
+
+The SDK provides typed endpoint methods and removes boilerplate around auth and refresh handling, which reduces errors in production provisioning flows.
+
+## Install
+
+```bash
+npm install @prisma/management-api-sdk
+```
+
+## Simple client (existing token)
+
+```typescript
+import { createManagementApiClient } from '@prisma/management-api-sdk'
+
+const client = createManagementApiClient({ token: process.env.PRISMA_SERVICE_TOKEN! })
+const { data: workspaces } = await client.GET('/v1/workspaces')
+```
+
+Check the generated client result before using `data`; typed clients surface HTTP failures separately. Never log a full response from connection/key creation because it may contain one-time credentials.
+
+## Workspace service tokens
+
+The typed client exposes routes to list, create, and revoke workspace service tokens:
+
+- `GET /v1/workspaces/{workspaceId}/service-tokens`
+- `POST /v1/workspaces/{workspaceId}/service-tokens`
+- `DELETE /v1/workspaces/{workspaceId}/service-tokens/{serviceTokenId}`
+
+Creation accepts a display `name`. The response's `data.value` is the complete token and is returned exactly once; transfer it directly to the intended secret store without logging the response. Later list calls return metadata and `valueHint`, not the token value. Treat revocation as destructive and resolve both ids explicitly.
+
+## Full SDK (OAuth + refresh)
+
+```typescript
+import { createManagementApiSdk, type TokenStorage } from '@prisma/management-api-sdk'
+
+const tokenStorage: TokenStorage = {
+ async getTokens() { return null },
+ async setTokens(tokens) {},
+ async clearTokens() {},
+}
+
+const api = createManagementApiSdk({
+ clientId: process.env.PRISMA_CLIENT_ID!,
+ redirectUri: 'https://your-app.com/auth/callback',
+ tokenStorage,
+})
+```
+
+## OAuth SDK flow
+
+1. Call `getLoginUrl()` and persist `state` + `verifier`.
+2. Redirect user to login URL.
+3. Handle callback with `handleCallback()`.
+4. Use `api.client` for typed endpoint calls.
+5. Call `logout()` when needed.
+
+## References
+
+- [Management API SDK docs](https://www.prisma.io/docs/postgres/introduction/management-api-sdk)
diff --git a/apps/backend/.agents/skills/prisma-postgres/references/management-api.md b/apps/backend/.agents/skills/prisma-postgres/references/management-api.md
new file mode 100644
index 0000000..4e4e76f
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-postgres/references/management-api.md
@@ -0,0 +1,79 @@
+# management-api
+
+Use Prisma Management API for programmatic provisioning and workspace/project/database management.
+
+## Priority
+
+CRITICAL
+
+## Why It Matters
+
+When you need backend automation, multi-tenant onboarding flows, or controlled resource provisioning, the Management API is the source of truth and is more reliable than interactive workflows.
+
+## Base URL
+
+```text
+https://api.prisma.io/v1
+```
+
+## API exploration
+
+- OpenAPI docs: `https://api.prisma.io/v1/doc`
+- Swagger Editor: `https://api.prisma.io/v1/swagger-editor`
+
+## Authentication methods
+
+- Service token: best for server-to-server operations in your own workspace
+- OAuth 2.0: best for acting on behalf of users across workspaces
+
+## Service token flow
+
+1. Create token in Prisma Console workspace settings.
+2. Send token as Bearer auth:
+
+```text
+Authorization: Bearer $TOKEN
+```
+
+## OAuth flow summary
+
+1. Redirect user to `https://auth.prisma.io/authorize` with `client_id`, `redirect_uri`, `response_type=code`, and scopes.
+2. Receive `code` on callback.
+3. Exchange code at `https://auth.prisma.io/token`.
+4. Use returned access token in Management API requests.
+
+## Resource model
+
+Workspace -> Project -> Branch -> Database. Branches are a first-class resource: databases attach to a Branch, and branch-scoped env/databases are how preview isolation works.
+
+## Current resource inventory
+
+The 1.55 OpenAPI surface includes:
+
+- workspaces, subscriptions, workspace integrations, workspace service tokens, and current-user metadata
+- projects, transfers, project databases, and project/branch environment variables
+- branches under a project plus branch get/update/delete operations
+- databases, usage, backups, restore, connections, and connection rotation
+- apps, deployments, promotion/rollback, runtime logs, domains, and build logs
+- buckets and bucket keys
+- source repositories, SCM installations/install intents, and repositories
+- integrations and regions
+
+App/deployment, branch mutation, SCM, and bucket routes include experimental surfaces. Read the installed SDK types or live OpenAPI before building durable automation around them.
+
+Connection create/rotate responses reveal credentials once. Later reads redact or omit the secret, so store the URL immediately. Use the structured direct/pooled endpoint returned by the concrete operation; do not assume a historical flat response shape.
+
+Workspace service-token creation also returns the complete token value exactly once. List calls expose only metadata and a `valueHint`; delete revokes the token. Keep workspace and token ids opaque, and never log a create response.
+
+Database create supports explicit project, region, branch, and source context. A source may be empty, a backup, or another database. Backup records are incremental; rely on current fields and documented units rather than old full-backup examples.
+
+## Notes
+
+- Management API mutation responses may include direct connection credentials; treat the entire response as secret until redacted.
+- Prefer an API-provided connection string over manually assembling one from fields.
+
+## References
+
+- [Management API docs](https://www.prisma.io/docs/postgres/introduction/management-api)
+- [OpenAPI docs](https://api.prisma.io/v1/doc)
+- [Swagger Editor](https://api.prisma.io/v1/swagger-editor)
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md b/apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md
new file mode 100644
index 0000000..23d4956
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/SKILL.md
@@ -0,0 +1,259 @@
+---
+name: prisma-upgrade-v7
+description: Complete migration guide from Prisma ORM v6 to v7 covering all breaking changes. Use when upgrading Prisma versions, encountering v7 errors, or migrating existing projects. Triggers on "upgrade to prisma 7", "prisma 7 migration", "prisma-client generator", "driver adapter required".
+license: MIT
+metadata:
+ author: prisma
+ version: "7.6.0"
+---
+
+# Upgrade to Prisma ORM 7
+
+Complete guide for migrating from Prisma ORM v6 to v7. This upgrade introduces significant breaking changes around the new `prisma-client` generator, driver adapters, `prisma.config.ts`, explicit environment loading, and generated client entrypoints.
+
+## When to Apply
+
+Reference this skill when:
+- Upgrading from Prisma v6 to v7
+- Updating to the `prisma-client` generator
+- Setting up driver adapters
+- Configuring `prisma.config.ts`
+- Fixing import errors after upgrade
+
+## Rule Categories by Priority
+
+| Priority | Category | Impact | Prefix |
+|----------|----------|--------|--------|
+| 1 | Schema Migration | CRITICAL | `schema-changes` |
+| 2 | Database Connectivity | CRITICAL | `driver-adapters` |
+| 3 | Module System | CRITICAL | `esm-support` |
+| 4 | Config and Env | HIGH | `prisma-config`, `env-variables` |
+| 5 | Removed Features | HIGH | `removed-features` |
+| 6 | Accelerate | HIGH | `accelerate-users` |
+
+## Quick Reference
+
+- `schema-changes` - generator migration, required output paths, generated entrypoints, and `Prisma.validator` replacement
+- `driver-adapters` - required adapter installation for SQL providers, pool differences, and Prisma Postgres adapter choices
+- `esm-support` - ESM-first setup plus CommonJS fallback with `moduleFormat = "cjs"`
+- `prisma-config` - creating and using `prisma.config.ts`
+- `env-variables` - explicit environment loading
+- `removed-features` - removed middleware, metrics, and legacy CLI behavior
+- `accelerate-users` - migration notes for Accelerate users
+
+## Using MongoDB? This guide does not apply
+
+Prisma 7 has no MongoDB connector. Do not apply any step in this guide to a project with
+`provider = "mongodb"` — see the `prisma-mongodb-upgrade` skill for the actual decision
+(stay on v6 deliberately vs migrate to Prisma Next).
+
+## Important Notes
+
+- **MongoDB projects should stay on Prisma 6.x or migrate to Prisma Next** - do not migrate MongoDB apps to Prisma 7's SQL client path (see `prisma-mongodb-upgrade`)
+- **Node.js 20.19.0+** required
+- **TypeScript 5.4.0+** required
+- **Latest stable Prisma ORM version**: `7.6.0`
+
+## Upgrade Steps Overview
+
+1. Update packages to v7
+2. Choose your module format (`esm` by default, `cjs` if needed)
+3. Update TypeScript configuration
+4. Update the schema generator block
+5. Create `prisma.config.ts`
+6. Install and configure a driver adapter for SQL providers
+7. Update Prisma Client imports
+8. Update client instantiation
+9. Replace deprecated helper patterns like `Prisma.validator`
+10. Run `prisma generate` and test
+
+## Quick Upgrade Commands
+
+```bash
+# Update packages
+npm install @prisma/client@7
+npm install -D prisma@7
+
+# Install a driver adapter (PostgreSQL or Prisma Postgres via direct TCP)
+npm install @prisma/adapter-pg pg
+
+# Install dotenv for env loading
+npm install dotenv
+
+# Regenerate client
+npx prisma generate
+```
+
+## Breaking Changes Summary
+
+| Change | v6 | v7 |
+|--------|----|----|
+| Module format | Implicit / mixed | ESM-first, `moduleFormat = "cjs"` supported |
+| Generator provider | `prisma-client-js` | `prisma-client` is the default, while `prisma-client-js` still exists for legacy setups |
+| Output path | Auto (node_modules) | Required explicit |
+| Driver adapters | Optional | Required for SQL providers |
+| Config file | `.env` + schema | `prisma.config.ts` |
+| Env loading | Automatic | Manual (dotenv) |
+| Generated entrypoints | Single package export | `client`, `browser`, `models`, `enums` entrypoints |
+| Type-safe query fragments | `Prisma.validator()` | TypeScript `satisfies` |
+| Middleware | `$use()` | Client Extensions |
+| Metrics | Preview feature | Removed |
+
+## Rule Files
+
+Detailed migration guides for each breaking change:
+
+```
+references/esm-support.md - ESM and CommonJS configuration
+references/schema-changes.md - Generator, output, imports, and generated entrypoints
+references/driver-adapters.md - Required driver adapter setup
+references/prisma-config.md - New configuration file
+references/env-variables.md - Environment variable loading
+references/removed-features.md - Middleware, metrics, and CLI flags
+references/accelerate-users.md - Special handling for Accelerate
+```
+
+## Step-by-Step Migration
+
+### 1. Update package.json for ESM-first projects
+
+```json
+{
+ "type": "module"
+}
+```
+
+If you need to stay on CommonJS, keep your app as CJS and set `moduleFormat = "cjs"` in the generator block instead of forcing ESM.
+
+### 2. Update tsconfig.json
+
+```json
+{
+ "compilerOptions": {
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "target": "ES2023",
+ "strict": true,
+ "esModuleInterop": true
+ }
+}
+```
+
+### 3. Update schema.prisma
+
+```prisma
+// Before (v6)
+generator client {
+ provider = "prisma-client-js"
+}
+
+// After (v7)
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+ // Optional if you need CommonJS:
+ // moduleFormat = "cjs"
+}
+```
+
+### 4. Create prisma.config.ts
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ migrations: {
+ path: 'prisma/migrations',
+ },
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+### 5. Install a driver adapter (SQL providers only)
+
+```bash
+# PostgreSQL
+npm install @prisma/adapter-pg pg
+
+# MySQL
+npm install @prisma/adapter-mariadb mariadb
+
+# SQLite
+npm install @prisma/adapter-better-sqlite3 better-sqlite3
+
+# Prisma Postgres in standard Node.js apps (recommended)
+npm install @prisma/adapter-pg pg
+
+# Prisma Postgres serverless driver (edge/serverless)
+npm install @prisma/adapter-ppg @prisma/ppg
+
+# Neon
+npm install @prisma/adapter-neon
+```
+
+MongoDB does not have a SQL `@prisma/adapter-*` package in the published Prisma 7.6.0 packages. If you're upgrading a MongoDB project, stop and keep that project on the latest Prisma 6.x release instead of following the standard Prisma 7 migration path.
+
+### 6. Update client instantiation
+
+```typescript
+// Before (v6)
+import { PrismaClient } from '@prisma/client'
+const prisma = new PrismaClient()
+
+// After (v7)
+import { PrismaClient } from '../generated/prisma/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### 7. Replace Prisma.validator with satisfies
+
+```typescript
+import { Prisma } from '../generated/prisma/client'
+
+const userSelect = {
+ id: true,
+ email: true,
+ name: true,
+} satisfies Prisma.UserSelect
+```
+
+### 8. Run migrations and generate
+
+```bash
+npx prisma generate
+npx prisma migrate dev # if needed
+```
+
+## Troubleshooting
+
+### "Cannot find module" errors
+- Check that the generator `output` path matches your import path
+- Ensure `prisma generate` ran successfully
+
+### SSL certificate errors
+- Add `ssl: { rejectUnauthorized: false }` to the adapter config if you need to preserve old behavior
+- Or configure your certificates properly with `NODE_EXTRA_CA_CERTS` / OpenSSL CA settings
+
+### Connection timeout issues
+- Driver adapters use the underlying driver's defaults, which differ from v6
+- Configure pool settings explicitly on the adapter if needed
+
+## Resources
+
+- [Official v7 Upgrade Guide](https://www.prisma.io/docs/orm/more/upgrades/to-v7)
+- [Driver Adapters Documentation](https://www.prisma.io/docs/orm/core-concepts/supported-databases/database-drivers)
+- [Prisma Config Reference](https://www.prisma.io/docs/orm/reference/prisma-config-reference)
+
+## How to Use
+
+Follow `references/schema-changes.md` and `references/driver-adapters.md` first, then apply the remaining reference files based on your project setup.
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/accelerate-users.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/accelerate-users.md
new file mode 100644
index 0000000..893e341
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/accelerate-users.md
@@ -0,0 +1,151 @@
+# Prisma Accelerate Users
+
+Special migration instructions for users of Prisma Accelerate or Prisma Postgres with `prisma://` or `prisma+postgres://` URLs.
+
+## Important
+
+**Do NOT pass Accelerate URLs to driver adapters.**
+
+Driver adapters (like `PrismaPg`) expect direct database connection strings. They will fail with `prisma://` or `prisma+postgres://` URLs.
+
+## Correct v7 Setup for Accelerate
+
+### 1. Keep your Accelerate URL
+
+```env
+# .env
+DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=..."
+# or
+DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..."
+```
+
+### 2. Install Accelerate extension
+
+```bash
+npm install @prisma/extension-accelerate
+```
+
+### 3. Configure prisma.config.ts
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'), // Accelerate URL works here
+ },
+})
+```
+
+### 4. Instantiate client with accelerateUrl
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { withAccelerate } from '@prisma/extension-accelerate'
+
+// Use accelerateUrl instead of adapter
+export const prisma = new PrismaClient({
+ accelerateUrl: process.env.DATABASE_URL,
+}).$extends(withAccelerate())
+```
+
+## What NOT to Do
+
+```typescript
+// ❌ WRONG - Don't use adapter with Accelerate URL
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL // This will fail with prisma://
+})
+```
+
+## Migrations with Accelerate
+
+For migrations, you may need a direct database connection:
+
+### Option 1: Use Accelerate URL for everything
+
+Accelerate URLs work with Prisma CLI commands:
+
+```bash
+# Works with Accelerate URL
+prisma migrate deploy
+prisma db push
+```
+
+### Option 2: Use direct URL for migrations
+
+```env
+DATABASE_URL="prisma+postgres://..." # For app
+DIRECT_DATABASE_URL="postgresql://..." # For migrations
+```
+
+```typescript
+// prisma.config.ts
+export default defineConfig({
+ datasource: {
+ url: env('DIRECT_DATABASE_URL'), // Direct URL for CLI
+ },
+})
+```
+
+## Prisma Postgres (Cloud)
+
+If using Prisma Postgres cloud database:
+
+### Same approach
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { withAccelerate } from '@prisma/extension-accelerate'
+
+export const prisma = new PrismaClient({
+ accelerateUrl: process.env.DATABASE_URL, // prisma+postgres:// URL
+}).$extends(withAccelerate())
+```
+
+## Switching Away from Accelerate
+
+If you later switch to direct TCP connection:
+
+```typescript
+// Change from accelerateUrl to adapter
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL // Direct postgres:// URL
+})
+
+export const prisma = new PrismaClient({ adapter })
+```
+
+## Caching with Accelerate
+
+The extension enables caching:
+
+```typescript
+const users = await prisma.user.findMany({
+ cacheStrategy: {
+ ttl: 60, // Cache for 60 seconds
+ swr: 120, // Stale-while-revalidate for 120 seconds
+ },
+})
+```
+
+## Edge Runtime
+
+Accelerate works great in edge runtimes:
+
+```typescript
+// Works in Vercel Edge, Cloudflare Workers, etc.
+import { PrismaClient } from '../generated/client'
+import { withAccelerate } from '@prisma/extension-accelerate'
+
+export const prisma = new PrismaClient({
+ accelerateUrl: process.env.DATABASE_URL,
+}).$extends(withAccelerate())
+```
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/driver-adapters.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/driver-adapters.md
new file mode 100644
index 0000000..bc5b892
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/driver-adapters.md
@@ -0,0 +1,267 @@
+# Driver Adapters
+
+Prisma v7 requires driver adapters for SQL database connections. This is the standard SQL execution path in current Prisma releases.
+
+MongoDB should not follow this path. There is no published MongoDB `@prisma/adapter-*` package, and MongoDB projects should remain on the latest Prisma 6.x release instead of trying to fit into the Prisma 7 SQL adapter model.
+
+## Why Driver Adapters?
+
+- No native engine binary in the Prisma Client SQL path
+- Smaller bundle size
+- Better serverless/edge compatibility
+- Uses native Node.js database drivers
+- More control over connection pooling
+
+## Available Adapters
+
+| Database | Adapter Package | Underlying Driver |
+|----------|-----------------|-------------------|
+| PostgreSQL | `@prisma/adapter-pg` | `pg` |
+| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
+| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
+| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
+| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
+| SQL Server | `@prisma/adapter-mssql` | `mssql` |
+| Neon | `@prisma/adapter-neon` | `@neondatabase/serverless` |
+| PlanetScale | `@prisma/adapter-planetscale` | `@planetscale/database` |
+| Turso/libSQL | `@prisma/adapter-libsql` | `@libsql/client` |
+| D1 (Cloudflare) | `@prisma/adapter-d1` | Cloudflare D1 |
+
+## Installation
+
+### PostgreSQL
+
+```bash
+npm install @prisma/adapter-pg
+```
+
+### MySQL
+
+```bash
+npm install @prisma/adapter-mariadb mariadb
+```
+
+### SQLite
+
+```bash
+npm install @prisma/adapter-better-sqlite3
+```
+
+### Prisma Postgres
+
+```bash
+npm install @prisma/adapter-pg pg
+```
+
+### SQL Server
+
+```bash
+npm install @prisma/adapter-mssql mssql
+```
+
+## Configuration
+
+### PostgreSQL
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### MySQL
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaMariaDb } from '@prisma/adapter-mariadb'
+
+const adapter = new PrismaMariaDb({
+ host: 'localhost',
+ port: 3306,
+ connectionLimit: 5,
+ user: process.env.MYSQL_USER,
+ password: process.env.MYSQL_PASSWORD,
+ database: process.env.MYSQL_DATABASE,
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### SQLite
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
+
+const adapter = new PrismaBetterSqlite3({
+ url: process.env.DATABASE_URL || 'file:./dev.db'
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### Neon (Serverless PostgreSQL)
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaNeon } from '@prisma/adapter-neon'
+
+const adapter = new PrismaNeon({
+ connectionString: process.env.DATABASE_URL
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### Prisma Postgres
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL,
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### Prisma Postgres serverless driver
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
+
+const prisma = new PrismaClient({
+ adapter: new PrismaPostgresAdapter({
+ connectionString: process.env.PRISMA_DIRECT_TCP_URL,
+ }),
+})
+```
+
+### SQL Server
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaMssql } from '@prisma/adapter-mssql'
+
+const adapter = new PrismaMssql({
+ server: 'localhost',
+ port: 1433,
+ database: 'mydb',
+ user: process.env.SQLSERVER_USER,
+ password: process.env.SQLSERVER_PASSWORD,
+ options: {
+ encrypt: true,
+ trustServerCertificate: true,
+ },
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+## Connection Pool Configuration
+
+Driver adapters use the underlying driver's pool settings, which differ from v6 defaults.
+
+### PostgreSQL with custom pool
+
+```typescript
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL,
+ // Pool configuration
+ max: 10, // Maximum connections
+ idleTimeoutMillis: 30000, // Close idle connections after 30s
+ connectionTimeoutMillis: 5000, // Connection timeout (v6 default was 5s)
+})
+```
+
+### Matching v6 behavior
+
+```typescript
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL,
+ connectionTimeoutMillis: 5000, // v6 used 5 second timeout
+})
+```
+
+## SSL Configuration
+
+### Accept self-signed certificates
+
+```typescript
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL,
+ ssl: {
+ rejectUnauthorized: false // Accept self-signed certs
+ }
+})
+```
+
+### Proper SSL configuration
+
+```typescript
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL,
+ ssl: {
+ ca: fs.readFileSync('/path/to/ca-cert.pem'),
+ rejectUnauthorized: true
+ }
+})
+```
+
+## Migration from v6
+
+### Before (v6)
+
+```typescript
+import { PrismaClient } from '@prisma/client'
+
+const prisma = new PrismaClient({
+ datasources: {
+ db: { url: process.env.DATABASE_URL }
+ }
+})
+```
+
+### After (v7)
+
+```typescript
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+## Singleton Pattern
+
+```typescript
+// lib/prisma.ts
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const globalForPrisma = globalThis as unknown as {
+ prisma: PrismaClient | undefined
+}
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL!
+})
+
+export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter })
+
+if (process.env.NODE_ENV !== 'production') {
+ globalForPrisma.prisma = prisma
+}
+```
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/env-variables.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/env-variables.md
new file mode 100644
index 0000000..fb67e89
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/env-variables.md
@@ -0,0 +1,161 @@
+# Environment Variables
+
+Prisma v7 no longer automatically loads environment variables. You must load them explicitly.
+
+## The Change
+
+### v6 Behavior
+
+Prisma CLI automatically loaded `.env` files.
+
+### v7 Behavior
+
+You must manually load environment variables using `dotenv` or similar.
+
+## Setup
+
+### 1. Install dotenv
+
+```bash
+npm install dotenv
+```
+
+### 2. Import in prisma.config.ts
+
+```typescript
+import 'dotenv/config' // Must be first import
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Bun Users
+
+Bun automatically loads `.env` files. No additional setup needed:
+
+```typescript
+// prisma.config.ts (Bun)
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Multiple .env Files
+
+### Using dotenv-cli
+
+```bash
+npm install -D dotenv-cli
+```
+
+```json
+{
+ "scripts": {
+ "db:migrate": "dotenv -e .env.local -- prisma migrate dev",
+ "db:push": "dotenv -e .env.development -- prisma db push"
+ }
+}
+```
+
+### Using dotenv with path
+
+```typescript
+// prisma.config.ts
+import { config } from 'dotenv'
+import path from 'path'
+
+// Load specific .env file
+config({ path: path.join(__dirname, '.env.local') })
+
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Application Code
+
+For your application, load env vars at startup:
+
+### Entry point
+
+```typescript
+// index.ts
+import 'dotenv/config'
+
+import { PrismaClient } from '../generated/client'
+import { PrismaPg } from '@prisma/adapter-pg'
+
+const adapter = new PrismaPg({
+ connectionString: process.env.DATABASE_URL!
+})
+
+const prisma = new PrismaClient({ adapter })
+```
+
+### Or use dotenv explicitly
+
+```typescript
+import { config } from 'dotenv'
+config()
+
+// Now process.env.DATABASE_URL is available
+```
+
+## Removed Environment Variables
+
+These Prisma-specific env vars are removed in v7:
+
+| Removed Variable | Alternative |
+|-----------------|-------------|
+| `PRISMA_CLI_QUERY_ENGINE_TYPE` | Not needed (no engines) |
+| `PRISMA_CLIENT_ENGINE_TYPE` | Not needed (no engines) |
+| `PRISMA_QUERY_ENGINE_BINARY` | Not needed |
+| `PRISMA_QUERY_ENGINE_LIBRARY` | Not needed |
+| `PRISMA_GENERATE_SKIP_AUTOINSTALL` | Not needed |
+| `PRISMA_SKIP_POSTINSTALL_GENERATE` | Not needed |
+| `PRISMA_GENERATE_IN_POSTINSTALL` | Not needed |
+| `PRISMA_GENERATE_DATAPROXY` | Migrate to `prisma-client` with driver adapters |
+| `PRISMA_GENERATE_NO_ENGINE` | Migrate to `prisma-client` with driver adapters |
+| `PRISMA_CLIENT_NO_RETRY` | Configure on adapter |
+| `PRISMA_MIGRATE_SKIP_GENERATE` | Not needed (auto-generate removed) |
+| `PRISMA_MIGRATE_SKIP_SEED` | Not needed (auto-seed removed) |
+
+## TypeScript env() Helper
+
+The `env()` function from `prisma/config` provides type safety:
+
+```typescript
+import { env } from 'prisma/config'
+
+// Type-safe environment variable access
+const url = env('DATABASE_URL') // string
+```
+
+Note: This only works within `prisma.config.ts`, not in your application code.
+
+## CI/CD Considerations
+
+Ensure environment variables are set in your CI environment:
+
+```yaml
+# GitHub Actions
+env:
+ DATABASE_URL: ${{ secrets.DATABASE_URL }}
+
+steps:
+ - run: npx prisma migrate deploy
+```
+
+No need for dotenv in CI if variables are set directly.
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/esm-support.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/esm-support.md
new file mode 100644
index 0000000..bf2697b
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/esm-support.md
@@ -0,0 +1,128 @@
+# ESM and CommonJS Support
+
+Prisma ORM v7 is ESM-first, but the `prisma-client` generator can target either ESM or CommonJS. Use ESM by default, and opt into CommonJS with `moduleFormat = "cjs"` if your project still needs it.
+
+## ESM Projects
+
+Add `"type": "module"` to `package.json` and use an ESM-compatible `tsconfig.json`:
+
+```json
+{
+ "type": "module",
+ "scripts": {
+ "build": "tsc",
+ "start": "node dist/index.js"
+ }
+}
+```
+
+```json
+{
+ "compilerOptions": {
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "target": "ES2023",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "outDir": "dist"
+ },
+ "include": ["src/**/*", "prisma/**/*"]
+}
+```
+
+## CommonJS Projects
+
+If the rest of your app is still CommonJS, keep that setup and make the generated Prisma Client CommonJS too:
+
+```json
+{
+ "compilerOptions": {
+ "module": "CommonJS",
+ "moduleResolution": "node",
+ "target": "ES2022",
+ "esModuleInterop": true
+ }
+}
+```
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+ moduleFormat = "cjs"
+}
+```
+
+## Generator Fields That Matter
+
+- `moduleFormat`: `esm` or `cjs`
+- `runtime`: `nodejs`, `bun`, `deno`, `workerd`, `vercel-edge`, `react-native`
+- `generatedFileExtension`: `ts`, `mts`, or `cts`
+- `importFileExtension`: `ts`, `mts`, `cts`, `js`, `mjs`, `cjs`, or empty
+
+Example:
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+ runtime = "nodejs"
+ moduleFormat = "esm"
+ generatedFileExtension = "ts"
+ importFileExtension = "ts"
+}
+```
+
+## Import Paths
+
+### Server Code
+
+```typescript
+import { PrismaClient } from '../generated/prisma/client'
+```
+
+### Browser-Safe Types
+
+```typescript
+import { Prisma } from '../generated/prisma/browser'
+import { Role } from '../generated/prisma/enums'
+import type { UserModel } from '../generated/prisma/models/User'
+```
+
+## File Extensions
+
+With `moduleResolution: "Node16"` or `"NodeNext"`, use `.js`/`.mjs`/`.cjs` extensions that match your emitted files.
+
+With `moduleResolution: "bundler"`, bare relative imports are usually fine.
+
+## Minimum Versions
+
+| Requirement | Minimum Version |
+|-------------|-----------------|
+| Node.js | 20.19.0 |
+| TypeScript | 5.4.0 |
+
+## Framework Considerations
+
+### Next.js
+
+Next.js works well with the default ESM output. If you need generated types in client components, import them from `browser`, `models`, or `enums`, not from `client`.
+
+### Bun
+
+Bun loads `.env` files automatically, so ESM plus `env()` is the smoothest default. You can still choose `moduleFormat = "cjs"` if the rest of your project requires it.
+
+## Troubleshooting
+
+### "ERR_REQUIRE_ESM"
+
+Your generated client is ESM, but your app is requiring it as CommonJS. Either switch the project to ESM or set `moduleFormat = "cjs"` and regenerate.
+
+### "Cannot use import statement outside a module"
+
+Your app is still being executed as CommonJS. Add `"type": "module"` or use `moduleFormat = "cjs"` instead.
+
+### TypeScript compilation errors
+
+Ensure `module`, `moduleResolution`, and your generator's `moduleFormat` agree with one another.
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/prisma-config.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/prisma-config.md
new file mode 100644
index 0000000..65b5128
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/prisma-config.md
@@ -0,0 +1,203 @@
+# Prisma Config
+
+Prisma v7 introduces `prisma.config.ts` as the central configuration file for the Prisma CLI.
+
+## Location
+
+Place `prisma.config.ts` at your project root (next to `package.json`).
+
+## Basic Configuration
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ migrations: {
+ path: 'prisma/migrations',
+ },
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
+
+## Configuration Options
+
+### schema
+
+Path to your Prisma schema file:
+
+```typescript
+schema: 'prisma/schema.prisma'
+```
+
+### datasource.url
+
+Database connection URL:
+
+```typescript
+datasource: {
+ url: env('DATABASE_URL'),
+}
+```
+
+### datasource.directUrl
+
+Direct connection URL (bypassing connection pooler):
+
+```typescript
+datasource: {
+ url: env('DATABASE_URL'),
+ directUrl: env('DIRECT_DATABASE_URL'),
+}
+```
+
+### datasource.shadowDatabaseUrl
+
+Shadow database for migrations:
+
+```typescript
+datasource: {
+ url: env('DATABASE_URL'),
+ shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
+}
+```
+
+### migrations.path
+
+Directory for migration files:
+
+```typescript
+migrations: {
+ path: 'prisma/migrations',
+}
+```
+
+### migrations.seed
+
+Seed command for `prisma db seed`:
+
+```typescript
+migrations: {
+ path: 'prisma/migrations',
+ seed: 'tsx prisma/seed.ts',
+}
+```
+
+## Full Example
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ // Schema location
+ schema: 'prisma/schema.prisma',
+
+ // Migration configuration
+ migrations: {
+ path: 'prisma/migrations',
+ seed: 'tsx prisma/seed.ts',
+ },
+
+ // Database connection
+ datasource: {
+ url: env('DATABASE_URL'),
+ directUrl: env('DIRECT_DATABASE_URL'),
+ shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
+ },
+})
+```
+
+## Environment Variables
+
+### The env() helper
+
+Use `env()` to reference environment variables:
+
+```typescript
+import { env } from 'prisma/config'
+
+datasource: {
+ url: env('DATABASE_URL'),
+}
+```
+
+This provides type safety but does NOT load .env files automatically.
+
+### Loading .env files
+
+Install and import dotenv:
+
+```bash
+npm install dotenv
+```
+
+```typescript
+import 'dotenv/config' // Must be first import
+import { defineConfig, env } from 'prisma/config'
+```
+
+## Migrating from v6
+
+### Before (v6) - schema.prisma
+
+```prisma
+datasource db {
+ provider = "postgresql"
+ url = env("DATABASE_URL")
+ directUrl = env("DIRECT_URL")
+}
+```
+
+### After (v7) - prisma.config.ts
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+
+export default defineConfig({
+ schema: 'prisma/schema.prisma',
+ datasource: {
+ url: env('DATABASE_URL'),
+ directUrl: env('DIRECT_URL'),
+ },
+})
+```
+
+And update schema.prisma:
+
+```prisma
+datasource db {
+ provider = "postgresql"
+ // URLs now in prisma.config.ts
+}
+```
+
+## Custom Config Path
+
+Use `--config` flag with CLI commands:
+
+```bash
+prisma migrate dev --config ./config/prisma.config.ts
+```
+
+## Monorepo Configuration
+
+```typescript
+import 'dotenv/config'
+import { defineConfig, env } from 'prisma/config'
+import path from 'path'
+
+export default defineConfig({
+ schema: path.join(__dirname, 'packages/database/prisma/schema.prisma'),
+ migrations: {
+ path: path.join(__dirname, 'packages/database/prisma/migrations'),
+ },
+ datasource: {
+ url: env('DATABASE_URL'),
+ },
+})
+```
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/removed-features.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/removed-features.md
new file mode 100644
index 0000000..0d77eaf
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/removed-features.md
@@ -0,0 +1,230 @@
+# Removed Features
+
+Several features have been removed in Prisma v7. Here's how to migrate.
+
+## Client Middleware
+
+### Removed
+
+```typescript
+// ❌ No longer works in v7
+prisma.$use(async (params, next) => {
+ const before = Date.now()
+ const result = await next(params)
+ const after = Date.now()
+ console.log(`Query took ${after - before}ms`)
+ return result
+})
+```
+
+### Use Client Extensions Instead
+
+```typescript
+// ✅ v7 approach
+const prisma = new PrismaClient({ adapter }).$extends({
+ query: {
+ $allModels: {
+ async $allOperations({ operation, model, args, query }) {
+ const before = Date.now()
+ const result = await query(args)
+ const after = Date.now()
+ console.log(`${model}.${operation} took ${after - before}ms`)
+ return result
+ },
+ },
+ },
+})
+```
+
+### Common Middleware Patterns
+
+#### Soft delete
+
+```typescript
+const prisma = new PrismaClient({ adapter }).$extends({
+ query: {
+ user: {
+ async delete({ args, query }) {
+ // Convert delete to soft delete
+ return prisma.user.update({
+ where: args.where,
+ data: { deletedAt: new Date() },
+ })
+ },
+ async findMany({ args, query }) {
+ // Filter out soft-deleted records
+ args.where = { ...args.where, deletedAt: null }
+ return query(args)
+ },
+ },
+ },
+})
+```
+
+#### Logging
+
+```typescript
+const prisma = new PrismaClient({ adapter }).$extends({
+ query: {
+ $allModels: {
+ async $allOperations({ operation, model, args, query }) {
+ console.log(`${model}.${operation}`, JSON.stringify(args))
+ return query(args)
+ },
+ },
+ },
+})
+```
+
+## Metrics
+
+### Removed
+
+The Metrics preview feature has been removed.
+
+```typescript
+// ❌ No longer works
+const metrics = await prisma.$metrics.json()
+```
+
+### Alternatives
+
+#### Custom counter with extensions
+
+```typescript
+let totalQueries = 0
+
+const prisma = new PrismaClient({ adapter }).$extends({
+ client: {
+ async $totalQueries() {
+ return totalQueries
+ },
+ },
+ query: {
+ $allModels: {
+ async $allOperations({ query, args }) {
+ totalQueries += 1
+ return query(args)
+ },
+ },
+ },
+})
+
+// Usage
+const count = await prisma.$totalQueries()
+```
+
+#### Use driver-level metrics
+
+Access metrics from the underlying driver adapter.
+
+## CLI Flags Removed
+
+### --skip-generate
+
+Removed from `migrate dev` and `db push`.
+
+```bash
+# v6
+prisma migrate dev --skip-generate
+
+# v7 - generate is not run automatically
+prisma migrate dev
+prisma generate # Run explicitly if needed
+```
+
+Local verification with Prisma `7.6.0` showed no generated client files emitted by `migrate dev` or `db push`, even though some CLI help text still says `migrate dev` "trigger[s] generators".
+
+### --skip-seed
+
+Removed from `migrate dev`. More importantly, Prisma v7 no longer auto-runs seeds during `migrate dev` or `migrate reset`, so seed explicitly when you need it.
+
+```bash
+# v6
+prisma migrate dev --skip-seed
+
+# v7 - seed is not run automatically
+prisma migrate dev
+prisma db seed # Run explicitly if needed
+```
+
+### --schema and --url from db execute
+
+```bash
+# v6
+prisma db execute --file ./script.sql --url "$DATABASE_URL"
+
+# v7 - configure in prisma.config.ts
+prisma db execute --file ./script.sql
+```
+
+## migrate diff Options
+
+| Removed | Replacement |
+|---------|-------------|
+| `--from-url` | `--from-config-datasource` |
+| `--to-url` | `--to-config-datasource` |
+| `--from-schema-datasource` | `--from-config-datasource` |
+| `--to-schema-datasource` | `--to-config-datasource` |
+| `--shadow-database-url` | Configure in `prisma.config.ts` |
+
+### Example
+
+```bash
+# v6
+prisma migrate diff --from-url "$DATABASE_URL" --to-schema schema.prisma
+
+# v7
+prisma migrate diff --from-config-datasource --to-schema schema.prisma
+```
+
+## Automatic Behaviors Removed
+
+### Auto-generate after migrate
+
+```bash
+# v7 workflow
+prisma migrate dev --name add_field
+prisma generate # Must run explicitly
+```
+
+### Auto-seed after migrate
+
+```bash
+# v7 workflow
+prisma migrate reset --force
+prisma db seed # Must run explicitly
+```
+
+## Prisma.validator
+
+The `prisma-client` generator no longer exposes `Prisma.validator`. Use TypeScript's `satisfies` operator instead.
+
+```typescript
+import { Prisma } from '../generated/prisma/client'
+
+const userSelect = {
+ id: true,
+ email: true,
+} satisfies Prisma.UserSelect
+```
+
+## rejectOnNotFound
+
+Removed in v5.0.0 (already deprecated).
+
+```typescript
+// ❌ Removed
+const prisma = new PrismaClient({
+ rejectOnNotFound: true,
+})
+
+// ✅ Use OrThrow methods
+const user = await prisma.user.findUniqueOrThrow({
+ where: { id: 1 },
+})
+
+const user = await prisma.user.findFirstOrThrow({
+ where: { email: 'test@example.com' },
+})
+```
diff --git a/apps/backend/.agents/skills/prisma-upgrade-v7/references/schema-changes.md b/apps/backend/.agents/skills/prisma-upgrade-v7/references/schema-changes.md
new file mode 100644
index 0000000..6c817a5
--- /dev/null
+++ b/apps/backend/.agents/skills/prisma-upgrade-v7/references/schema-changes.md
@@ -0,0 +1,164 @@
+# Schema Changes
+
+Prisma v7 promotes `prisma-client` to the default generator. Update your generator block, output path, and imports accordingly.
+
+This guide is for projects that are actually migrating to Prisma 7. Do not apply these schema changes to MongoDB projects; keep those on Prisma 6.x.
+
+## Generator Block (v7)
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+}
+```
+
+## Key Changes
+
+### 1. Provider name
+
+Use `prisma-client` in Prisma v7. The older `prisma-client-js` generator still exists in the repo for legacy setups, but `prisma-client` is the default path for current projects.
+
+### 2. Output is required
+
+The `output` field is mandatory when using `prisma-client`. Prisma Client no longer generates to `node_modules` with this generator.
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+}
+```
+
+### 3. engineType changed
+
+Legacy Rust engine settings are gone. With `prisma-client`, the relevant value is `engineType = "client"` if you want to state it explicitly, although it is typically inferred and can be omitted.
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+ engineType = "client"
+}
+```
+
+### 4. moduleFormat is explicit when needed
+
+If you must stay on CommonJS:
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+ moduleFormat = "cjs"
+}
+```
+
+## Example Output Paths
+
+### Standard project
+
+```prisma
+output = "../generated/prisma"
+```
+
+Creates files like:
+
+```text
+generated/prisma/
+ client.ts
+ browser.ts
+ enums.ts
+ models.ts
+ models/
+```
+
+### Monorepo
+
+```prisma
+output = "../../packages/database/generated/prisma"
+```
+
+### Same directory as schema
+
+```prisma
+output = "./generated/prisma"
+```
+
+Creates: `prisma/generated/prisma/client.ts`
+
+## Datasource Block
+
+The `url`, `directUrl`, and `shadowDatabaseUrl` fields in the `datasource` block are deprecated in Prisma v7. Move them to `prisma.config.ts` and keep only the provider in `schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "postgresql"
+}
+```
+
+```typescript
+export default defineConfig({
+ datasource: {
+ url: env('DATABASE_URL'),
+ directUrl: env('DIRECT_URL'),
+ shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
+ },
+})
+```
+
+## After Schema Changes
+
+1. Run `prisma generate`:
+ ```bash
+ npx prisma generate
+ ```
+
+2. Update imports throughout your codebase:
+ ```typescript
+ import { PrismaClient } from '../generated/prisma/client'
+ ```
+
+3. Update `.gitignore` if you manage this manually:
+ ```
+ /generated/prisma
+ ```
+
+4. Replace `Prisma.validator()` with TypeScript `satisfies` when using `prisma-client`:
+ ```typescript
+ import { Prisma } from '../generated/prisma/client'
+
+ const userSelect = {
+ id: true,
+ email: true,
+ } satisfies Prisma.UserSelect
+ ```
+
+## Generated Entrypoints
+
+- `client` - server-side Prisma Client and Prisma namespace
+- `browser` - browser-safe types and enums without a real `PrismaClient`
+- `enums` - slim enum-only entrypoint
+- `models` - model types and derived helper types
+
+## Preview Features
+
+Preview features still work as before:
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+ previewFeatures = ["relationJoins", "fullTextSearch"]
+}
+```
+
+Recent preview-feature examples also include `partialIndexes` for PostgreSQL, SQLite, SQL Server, and CockroachDB:
+
+```prisma
+generator client {
+ provider = "prisma-client"
+ output = "../generated/prisma"
+ previewFeatures = ["partialIndexes"]
+}
+```
diff --git a/apps/backend/.env.example b/apps/backend/.env.example
index 951c986..891ba73 100644
--- a/apps/backend/.env.example
+++ b/apps/backend/.env.example
@@ -18,4 +18,79 @@ EMAIL_SERVER_HOST=""
EMAIL_SERVER_PORT="587"
EMAIL_SERVER_USER=""
EMAIL_SERVER_PASSWORD=""
-EMAIL_FROM="Gruperly "
\ No newline at end of file
+EMAIL_FROM="Gruperly "
+
+# 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"
diff --git a/apps/backend/docker-entrypoint.sh b/apps/backend/docker-entrypoint.sh
new file mode 100755
index 0000000..d30ad75
--- /dev/null
+++ b/apps/backend/docker-entrypoint.sh
@@ -0,0 +1,42 @@
+#!/bin/sh
+# Production entrypoint for the backend: applies the migrations and starts the
+# server in the same container.
+#
+# This is POSIX sh, not bash: the image is alpine and does not ship bash
+# installed (adding it would be ~10MB for a shebang).
+#
+# 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}"
+
+if [ "${RUN_MIGRATIONS:-true}" = "false" ]; then
+ echo "migrate: omitido (RUN_MIGRATIONS=false)"
+else
+ attempts="${MIGRATE_ATTEMPTS:-30}"
+ delay="${MIGRATE_RETRY_DELAY:-5}"
+ i=1
+
+ # 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"
+ break
+ fi
+
+ if [ "$i" -eq "$attempts" ]; then
+ echo "migrate: fallo tras $attempts intentos; no se levanta el servidor" >&2
+ exit 1
+ fi
+
+ echo "migrate: intento $i/$attempts fallo; reintento en ${delay}s" >&2
+ i=$((i + 1))
+ sleep "$delay"
+ done
+fi
+
+# 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 "$@"
diff --git a/apps/backend/package.json b/apps/backend/package.json
index a8cd5f6..acabfd0 100644
--- a/apps/backend/package.json
+++ b/apps/backend/package.json
@@ -9,11 +9,13 @@
"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",
"db:generate": "prisma generate",
"db:migrate": "prisma migrate dev",
+ "db:deploy": "prisma migrate deploy",
"db:push": "prisma db push",
"db:studio": "prisma studio"
},
@@ -22,11 +24,15 @@
"@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",
+ "nanoid": "^3.3.19",
"nodemailer": "^9.0.6",
"pino": "^9.5.0",
"pino-pretty": "^13.0.0",
+ "prisma": "^7.10.0",
"zod": "3.24.2"
},
"devDependencies": {
@@ -35,8 +41,6 @@
"@types/bun": "^1.4.0",
"@types/node": "^20.17.0",
"@types/nodemailer": "^8.0.1",
- "dotenv": "^16.4.5",
- "prisma": "^7.10.0",
"typescript": "^5.7.0"
}
}
\ No newline at end of file
diff --git a/apps/backend/prisma/migrations/20260917120000_rename_student_to_attendee/migration.sql b/apps/backend/prisma/migrations/20260917120000_rename_student_to_attendee/migration.sql
new file mode 100644
index 0000000..377bea5
--- /dev/null
+++ b/apps/backend/prisma/migrations/20260917120000_rename_student_to_attendee/migration.sql
@@ -0,0 +1,16 @@
+-- Rename Student model (students table) to Attendee (attendees table)
+
+-- AlterTable
+ALTER TABLE "students" RENAME TO "attendees";
+
+-- AlterTable
+ALTER TABLE "payments" RENAME COLUMN "studentId" TO "attendeeId";
+
+-- RenameIndex
+ALTER INDEX "students_groupId_idx" RENAME TO "attendees_groupId_idx";
+
+-- RenameIndex
+ALTER INDEX "payments_studentId_idx" RENAME TO "payments_attendeeId_idx";
+
+-- RenameForeignKey
+ALTER TABLE "payments" RENAME CONSTRAINT "payments_studentId_fkey" TO "payments_attendeeId_fkey";
\ No newline at end of file
diff --git a/apps/backend/prisma/migrations/20260918123119_add_onboarding_complete/migration.sql b/apps/backend/prisma/migrations/20260918123119_add_onboarding_complete/migration.sql
new file mode 100644
index 0000000..084b0f7
--- /dev/null
+++ b/apps/backend/prisma/migrations/20260918123119_add_onboarding_complete/migration.sql
@@ -0,0 +1,45 @@
+-- CreateEnum
+CREATE TYPE "WeekDay" AS ENUM ('MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY');
+
+-- CreateEnum
+CREATE TYPE "BillingType" AS ENUM ('MONTHLY', 'PER_CLASS');
+
+-- CreateEnum
+CREATE TYPE "PaymentProvider" AS ENUM ('MERCADO_PAGO', 'STRIPE');
+
+-- AlterTable
+ALTER TABLE "attendees" RENAME CONSTRAINT "students_pkey" TO "attendees_pkey";
+
+-- AlterTable
+ALTER TABLE "groups" ADD COLUMN "billingType" "BillingType",
+ADD COLUMN "capacity" INTEGER,
+ADD COLUMN "days" "WeekDay"[],
+ADD COLUMN "dueDay" INTEGER,
+ADD COLUMN "price" DECIMAL(10,2),
+ADD COLUMN "time" TEXT;
+
+-- AlterTable
+ALTER TABLE "users" ADD COLUMN "onboardingCompleted" BOOLEAN NOT NULL DEFAULT false;
+
+-- CreateTable
+CREATE TABLE "merchant_accounts" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "provider" "PaymentProvider" NOT NULL,
+ "accessToken" TEXT,
+ "sandbox" BOOLEAN NOT NULL DEFAULT true,
+ "connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "merchant_accounts_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "merchant_accounts_userId_key" ON "merchant_accounts"("userId");
+
+-- RenameForeignKey
+ALTER TABLE "attendees" RENAME CONSTRAINT "students_groupId_fkey" TO "attendees_groupId_fkey";
+
+-- AddForeignKey
+ALTER TABLE "merchant_accounts" ADD CONSTRAINT "merchant_accounts_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/apps/backend/prisma/migrations/20260918130000_add_group_invite_token/migration.sql b/apps/backend/prisma/migrations/20260918130000_add_group_invite_token/migration.sql
new file mode 100644
index 0000000..13b84c6
--- /dev/null
+++ b/apps/backend/prisma/migrations/20260918130000_add_group_invite_token/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "groups" ADD COLUMN "inviteToken" TEXT;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "groups_inviteToken_key" ON "groups"("inviteToken");
diff --git a/apps/backend/prisma/migrations/20260922191756_add_group_waitlist/migration.sql b/apps/backend/prisma/migrations/20260922191756_add_group_waitlist/migration.sql
new file mode 100644
index 0000000..a1dc578
--- /dev/null
+++ b/apps/backend/prisma/migrations/20260922191756_add_group_waitlist/migration.sql
@@ -0,0 +1,23 @@
+-- CreateTable
+CREATE TABLE "group_waitlist_entries" (
+ "id" TEXT NOT NULL,
+ "groupId" TEXT NOT NULL,
+ "fullName" TEXT NOT NULL,
+ "phone" TEXT NOT NULL,
+ "email" TEXT,
+ "notes" TEXT,
+ "status" "WaitlistStatus" NOT NULL DEFAULT 'PENDING',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "group_waitlist_entries_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "group_waitlist_entries_groupId_idx" ON "group_waitlist_entries"("groupId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "group_waitlist_entries_groupId_phone_key" ON "group_waitlist_entries"("groupId", "phone");
+
+-- AddForeignKey
+ALTER TABLE "group_waitlist_entries" ADD CONSTRAINT "group_waitlist_entries_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql b/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql
new file mode 100644
index 0000000..6384f24
--- /dev/null
+++ b/apps/backend/prisma/migrations/20260923120000_add_class_sessions_attendance/migration.sql
@@ -0,0 +1,68 @@
+-- CreateEnum
+CREATE TYPE "AttendanceStatus" AS ENUM ('PRESENT', 'ABSENT', 'EXCUSED');
+
+-- AlterTable
+ALTER TABLE "attendees" ADD COLUMN "notifyToken" TEXT;
+
+-- CreateTable
+CREATE TABLE "class_sessions" (
+ "id" TEXT NOT NULL,
+ "groupId" TEXT NOT NULL,
+ "startsAt" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "class_sessions_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "attendances" (
+ "id" TEXT NOT NULL,
+ "attendeeId" TEXT NOT NULL,
+ "classSessionId" TEXT NOT NULL,
+ "status" "AttendanceStatus" NOT NULL,
+ "markedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "attendances_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "slot_releases" (
+ "id" TEXT NOT NULL,
+ "attendeeId" TEXT NOT NULL,
+ "classSessionId" TEXT NOT NULL,
+ "isClaimed" BOOLEAN NOT NULL DEFAULT false,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "slot_releases_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "class_sessions_groupId_startsAt_key" ON "class_sessions"("groupId", "startsAt");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "attendances_attendeeId_classSessionId_key" ON "attendances"("attendeeId", "classSessionId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "slot_releases_attendeeId_classSessionId_key" ON "slot_releases"("attendeeId", "classSessionId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "attendees_notifyToken_key" ON "attendees"("notifyToken");
+
+-- AddForeignKey
+ALTER TABLE "class_sessions" ADD CONSTRAINT "class_sessions_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "attendances" ADD CONSTRAINT "attendances_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "attendances" ADD CONSTRAINT "attendances_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_attendeeId_fkey" FOREIGN KEY ("attendeeId") REFERENCES "attendees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "slot_releases" ADD CONSTRAINT "slot_releases_classSessionId_fkey" FOREIGN KEY ("classSessionId") REFERENCES "class_sessions"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- Backfill: tokens de aviso de ausencia para alumnos existentes
+UPDATE "attendees" SET "notifyToken" = gen_random_uuid()::text WHERE "notifyToken" IS NULL;
diff --git a/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql b/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql
new file mode 100644
index 0000000..66cabe9
--- /dev/null
+++ b/apps/backend/prisma/migrations/20260923172527_add_attendee_status/migration.sql
@@ -0,0 +1,5 @@
+-- CreateEnum
+CREATE TYPE "AttendeeStatus" AS ENUM ('ACTIVE', 'PAUSED', 'DROPPED');
+
+-- AlterTable
+ALTER TABLE "attendees" ADD COLUMN "status" "AttendeeStatus" NOT NULL DEFAULT 'ACTIVE';
diff --git a/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql b/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql
new file mode 100644
index 0000000..1c25d68
--- /dev/null
+++ b/apps/backend/prisma/migrations/20260929180102_add_group_pre_registrations/migration.sql
@@ -0,0 +1,26 @@
+-- CreateEnum
+CREATE TYPE "PreRegistrationStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED');
+
+-- CreateTable
+CREATE TABLE "group_pre_registrations" (
+ "id" TEXT NOT NULL,
+ "groupId" TEXT NOT NULL,
+ "fullName" TEXT NOT NULL,
+ "phone" TEXT NOT NULL,
+ "email" TEXT,
+ "status" "PreRegistrationStatus" NOT NULL DEFAULT 'PENDING',
+ "reviewedAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "group_pre_registrations_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "group_pre_registrations_groupId_idx" ON "group_pre_registrations"("groupId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "group_pre_registrations_groupId_phone_key" ON "group_pre_registrations"("groupId", "phone");
+
+-- AddForeignKey
+ALTER TABLE "group_pre_registrations" ADD CONSTRAINT "group_pre_registrations_groupId_fkey" FOREIGN KEY ("groupId") REFERENCES "groups"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/apps/backend/prisma/migrations/20261001162911_snake_case_columns/migration.sql b/apps/backend/prisma/migrations/20261001162911_snake_case_columns/migration.sql
new file mode 100644
index 0000000..5204a2a
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261001162911_snake_case_columns/migration.sql
@@ -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";
diff --git a/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql b/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql
new file mode 100644
index 0000000..dd94bf1
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261005092123_add_mp_accounts/migration.sql
@@ -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";
diff --git a/apps/backend/prisma/migrations/20261007120000_add_country_and_payment_links/migration.sql b/apps/backend/prisma/migrations/20261007120000_add_country_and_payment_links/migration.sql
new file mode 100644
index 0000000..18e8659
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261007120000_add_country_and_payment_links/migration.sql
@@ -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");
\ No newline at end of file
diff --git a/apps/backend/prisma/migrations/20261021233531_add_whatsapp_messaging/migration.sql b/apps/backend/prisma/migrations/20261021233531_add_whatsapp_messaging/migration.sql
new file mode 100644
index 0000000..733ad96
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261021233531_add_whatsapp_messaging/migration.sql
@@ -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;
diff --git a/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql b/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql
new file mode 100644
index 0000000..826d695
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261022231252_add_billing_subscriptions/migration.sql
@@ -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;
diff --git a/apps/backend/prisma/migrations/20261026120000_add_billing_providers/migration.sql b/apps/backend/prisma/migrations/20261026120000_add_billing_providers/migration.sql
new file mode 100644
index 0000000..9f6504f
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261026120000_add_billing_providers/migration.sql
@@ -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:` or `stripe`)
+ALTER TABLE "billing_webhook_events" RENAME COLUMN "country_code" TO "source";
+UPDATE "billing_webhook_events" SET "source" = 'mp:' || "source";
diff --git a/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql b/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql
new file mode 100644
index 0000000..cd6de18
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261027175804_add_attendee_alert_resolutions/migration.sql
@@ -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;
diff --git a/apps/backend/prisma/migrations/20261027212531_add_student_access/migration.sql b/apps/backend/prisma/migrations/20261027212531_add_student_access/migration.sql
new file mode 100644
index 0000000..158166d
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261027212531_add_student_access/migration.sql
@@ -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;
diff --git a/apps/backend/prisma/migrations/20261028120000_add_reported_payment_note/migration.sql b/apps/backend/prisma/migrations/20261028120000_add_reported_payment_note/migration.sql
new file mode 100644
index 0000000..28c4ff1
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261028120000_add_reported_payment_note/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "reported_payments" ADD COLUMN "note" TEXT;
diff --git a/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql b/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql
new file mode 100644
index 0000000..a67892f
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261102180000_add_people/migration.sql
@@ -0,0 +1,182 @@
+-- A person (contact data, per teacher) can now be in several groups: `attendees`
+-- becomes the membership and points to `people`. Existing attendees of the same
+-- teacher with the same phone (digits only) are merged into one person, and
+-- their student-app accounts into one account.
+
+-- All or nothing: a half-applied data migration cannot be retried.
+BEGIN;
+
+-- CreateTable
+CREATE TABLE "people" (
+ "id" TEXT NOT NULL,
+ "created_by_id" TEXT NOT NULL,
+ "full_name" TEXT NOT NULL,
+ "email" TEXT,
+ "phone" TEXT,
+ "guardian_name" TEXT,
+ "guardian_phone" TEXT,
+ "notes" TEXT,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "people_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "student_account_people" (
+ "account_id" TEXT NOT NULL,
+ "person_id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "student_account_people_pkey" PRIMARY KEY ("account_id","person_id")
+);
+
+-- Grouping: same teacher + same phone digits. `group_rank` splits the (rare)
+-- rows that already shared a phone inside one group, which the per-group unique
+-- membership would reject: the extra ones become their own person.
+CREATE TEMP TABLE "_attendee_keys" AS
+SELECT
+ a."id" AS attendee_id,
+ a."group_id",
+ a."created_at",
+ g."created_by_id",
+ NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '') AS phone_digits,
+ ROW_NUMBER() OVER (
+ PARTITION BY g."created_by_id", a."group_id", NULLIF(regexp_replace(COALESCE(a."phone", ''), '\D', '', 'g'), '')
+ ORDER BY a."created_at", a."id"
+ ) AS group_rank
+FROM "attendees" a
+JOIN "groups" g ON g."id" = a."group_id";
+
+CREATE TEMP TABLE "_attendee_person" AS
+SELECT
+ k.attendee_id,
+ k.created_by_id,
+ -- The person reuses the id of its oldest attendee.
+ FIRST_VALUE(k.attendee_id) OVER (
+ PARTITION BY k.created_by_id,
+ CASE WHEN k.phone_digits IS NULL THEN k.attendee_id ELSE k.phone_digits || '#' || k.group_rank END
+ ORDER BY k.created_at, k.attendee_id
+ ) AS person_id,
+ (k.phone_digits IS NOT NULL AND k.group_rank > 1) AS phone_clash
+FROM "_attendee_keys" k;
+
+INSERT INTO "people" ("id", "created_by_id", "full_name", "email", "phone", "guardian_name", "guardian_phone", "notes", "created_at", "updated_at")
+SELECT
+ p.person_id,
+ MIN(p.created_by_id),
+ MIN(rep."full_name"),
+ (ARRAY_AGG(a."email" ORDER BY a."created_at") FILTER (WHERE a."email" IS NOT NULL))[1],
+ CASE WHEN BOOL_OR(p.phone_clash) THEN NULL ELSE NULLIF(TRIM(MIN(rep."phone")), '') END,
+ (ARRAY_AGG(a."guardian_name" ORDER BY a."created_at") FILTER (WHERE a."guardian_name" IS NOT NULL))[1],
+ (ARRAY_AGG(a."guardian_phone" ORDER BY a."created_at") FILTER (WHERE a."guardian_phone" IS NOT NULL))[1],
+ NULLIF(CONCAT_WS(E'\n\n',
+ STRING_AGG(DISTINCT NULLIF(TRIM(a."notes"), ''), E'\n\n'),
+ CASE WHEN BOOL_OR(p.phone_clash) THEN 'Teléfono: ' || MIN(rep."phone") END
+ ), ''),
+ MIN(a."created_at"),
+ CURRENT_TIMESTAMP
+FROM "_attendee_person" p
+JOIN "attendees" a ON a."id" = p.attendee_id
+JOIN "attendees" rep ON rep."id" = p.person_id
+GROUP BY p.person_id;
+
+-- AlterTable: attendees -> membership
+ALTER TABLE "attendees" ADD COLUMN "person_id" TEXT;
+UPDATE "attendees" a SET "person_id" = p.person_id FROM "_attendee_person" p WHERE p.attendee_id = a."id";
+ALTER TABLE "attendees" ALTER COLUMN "person_id" SET NOT NULL;
+
+-- Student accounts: link them to the person instead of the membership.
+INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
+SELECT sa."account_id", p.person_id, MIN(sa."created_at")
+FROM "student_account_attendees" sa
+JOIN "_attendee_person" p ON p.attendee_id = sa."attendee_id"
+GROUP BY sa."account_id", p.person_id;
+
+-- A merged person may end up with several accounts: keep the one used most
+-- recently (else the oldest) and fold the others into it.
+CREATE TEMP TABLE "_account_merge" AS
+WITH ranked AS (
+ SELECT
+ sap."person_id",
+ sap."account_id",
+ ROW_NUMBER() OVER (
+ PARTITION BY sap."person_id"
+ ORDER BY (
+ SELECT MAX(s."last_used_at") FROM "student_sessions" s
+ WHERE s."account_id" = sap."account_id" AND s."revoked_at" IS NULL
+ ) DESC NULLS LAST, acc."created_at", acc."id"
+ ) AS rn
+ FROM "student_account_people" sap
+ JOIN "student_accounts" acc ON acc."id" = sap."account_id"
+)
+SELECT DISTINCT ON (d."account_id") d."account_id" AS old_id, k."account_id" AS keep_id
+FROM ranked d
+JOIN ranked k ON k."person_id" = d."person_id" AND k.rn = 1
+WHERE d.rn > 1 AND d."account_id" <> k."account_id"
+ORDER BY d."account_id";
+
+INSERT INTO "student_account_people" ("account_id", "person_id", "created_at")
+SELECT m.keep_id, sap."person_id", sap."created_at"
+FROM "student_account_people" sap
+JOIN "_account_merge" m ON m.old_id = sap."account_id"
+ON CONFLICT DO NOTHING;
+
+UPDATE "absence_notices" n SET "account_id" = m.keep_id FROM "_account_merge" m WHERE n."account_id" = m.old_id;
+UPDATE "reported_payments" r SET "account_id" = m.keep_id FROM "_account_merge" m WHERE r."account_id" = m.old_id;
+
+UPDATE "student_accounts" k
+SET "recovery_email" = o."recovery_email", "recovery_email_verified_at" = o."recovery_email_verified_at"
+FROM "_account_merge" m
+JOIN "student_accounts" o ON o."id" = m.old_id
+WHERE k."id" = m.keep_id AND k."recovery_email" IS NULL AND o."recovery_email" IS NOT NULL;
+
+-- Sessions, tokens and passkeys of the folded accounts go with them (cascade);
+-- their links are removed by hand because that FK is created further down.
+DELETE FROM "student_account_people" WHERE "account_id" IN (SELECT old_id FROM "_account_merge");
+DELETE FROM "student_accounts" WHERE "id" IN (SELECT old_id FROM "_account_merge");
+
+-- DropTable
+DROP TABLE "student_account_attendees";
+
+-- AlterTable
+ALTER TABLE "attendees"
+ DROP COLUMN "full_name",
+ DROP COLUMN "email",
+ DROP COLUMN "phone",
+ DROP COLUMN "guardian_name",
+ DROP COLUMN "guardian_phone",
+ DROP COLUMN "notes";
+
+-- CreateIndex
+CREATE INDEX "people_created_by_id_idx" ON "people"("created_by_id");
+
+-- One person per phone and teacher. Partial: Prisma does not model it.
+CREATE UNIQUE INDEX "people_owner_phone_key" ON "people"("created_by_id", "phone") WHERE "phone" IS NOT NULL;
+
+-- CreateIndex
+CREATE INDEX "student_account_people_person_id_idx" ON "student_account_people"("person_id");
+
+-- CreateIndex
+CREATE INDEX "attendees_person_id_idx" ON "attendees"("person_id");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "attendees_group_id_person_id_key" ON "attendees"("group_id", "person_id");
+
+-- AddForeignKey
+ALTER TABLE "people" ADD CONSTRAINT "people_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "attendees" ADD CONSTRAINT "attendees_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "student_accounts"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "student_account_people" ADD CONSTRAINT "student_account_people_person_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+DROP TABLE "_account_merge";
+DROP TABLE "_attendee_person";
+DROP TABLE "_attendee_keys";
+
+COMMIT;
diff --git a/apps/backend/prisma/migrations/20261103130000_add_user_locale/migration.sql b/apps/backend/prisma/migrations/20261103130000_add_user_locale/migration.sql
new file mode 100644
index 0000000..ab20115
--- /dev/null
+++ b/apps/backend/prisma/migrations/20261103130000_add_user_locale/migration.sql
@@ -0,0 +1 @@
+ALTER TABLE "users" ADD COLUMN "locale" TEXT;
diff --git a/apps/backend/prisma/models/attendance.prisma b/apps/backend/prisma/models/attendance.prisma
new file mode 100644
index 0000000..02f95e3
--- /dev/null
+++ b/apps/backend/prisma/models/attendance.prisma
@@ -0,0 +1,51 @@
+// Attendance & class sessions
+
+enum AttendanceStatus {
+ PRESENT
+ ABSENT
+ EXCUSED
+}
+
+model ClassSession {
+ id String @id @default(cuid())
+ 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, map: "class_sessions_groupId_fkey")
+ attendances Attendance[]
+ slotReleases SlotRelease[]
+ absenceNotices AbsenceNotice[]
+
+ @@unique([groupId, startsAt], map: "class_sessions_groupId_startsAt_key")
+ @@map("class_sessions")
+}
+
+model Attendance {
+ id String @id @default(cuid())
+ attendeeId String @map("attendee_id")
+ classSessionId String @map("class_session_id")
+ status AttendanceStatus
+ markedAt DateTime @default(now()) @map("marked_at")
+
+ 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], map: "attendances_attendeeId_classSessionId_key")
+ @@map("attendances")
+}
+
+model SlotRelease {
+ id String @id @default(cuid())
+ 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, map: "slot_releases_attendeeId_fkey")
+ classSession ClassSession @relation(fields: [classSessionId], references: [id], onDelete: Cascade, map: "slot_releases_classSessionId_fkey")
+
+ @@unique([attendeeId, classSessionId], map: "slot_releases_attendeeId_classSessionId_key")
+ @@map("slot_releases")
+}
diff --git a/apps/backend/prisma/models/auth.prisma b/apps/backend/prisma/models/auth.prisma
index cc10dc1..c7cc6eb 100644
--- a/apps/backend/prisma/models/auth.prisma
+++ b/apps/backend/prisma/models/auth.prisma
@@ -1,61 +1,75 @@
// Auth (Better Auth) - required tables
model User {
- id String @id @default(cuid())
- name String
- email String @unique
- emailVerified Boolean @default(false)
- image String?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ name String
+ email String @unique
+ emailVerified Boolean @default(false) @map("email_verified")
+ image String?
+ onboardingCompleted Boolean @default(false) @map("onboarding_completed")
+ country String? @map("country_code")
+ // UI language the person chose (es-AR, es-419, pt-BR, en); null follows the device.
+ locale String? @map("locale")
+ // When the professor chose Free or Pro in the onboarding (mandatory step).
+ 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[]
- passkeys Passkey[]
- groupsMember GroupMember[]
- groupsOwner Group[] @relation("OwnerGroups")
- orgMemberships Member[]
- orgInvitations Invitation[] @relation("InvitedBy")
- waitlist WaitlistEntry[]
+ accounts Account[]
+ sessions Session[]
+ passkeys Passkey[]
+ groupsMember GroupMember[]
+ groupsOwner Group[] @relation("OwnerGroups")
+ orgMemberships Member[]
+ orgInvitations Invitation[] @relation("InvitedBy")
+ waitlist WaitlistEntry[]
+ mpAccount MpAccount?
+ whatsappAccount WhatsappAccount?
+ subscription BillingSubscription?
+ studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
+ people Person[] @relation("OwnerPeople")
@@map("users")
}
model Account {
- id String @id @default(cuid())
- userId String
- providerId String
- accountId String
+ id String @id @default(cuid())
+ 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")
}
@@ -64,9 +78,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")
@@ -79,8 +93,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[]
@@ -90,32 +104,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")
}
@@ -123,18 +137,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")
-}
\ No newline at end of file
+}
diff --git a/apps/backend/prisma/models/billing.prisma b/apps/backend/prisma/models/billing.prisma
new file mode 100644
index 0000000..895bab2
--- /dev/null
+++ b/apps/backend/prisma/models/billing.prisma
@@ -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:`
+// (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")
+}
diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma
index 1b13f2c..3dacdf2 100644
--- a/apps/backend/prisma/models/domain.prisma
+++ b/apps/backend/prisma/models/domain.prisma
@@ -1,32 +1,62 @@
// Domain models
model Group {
- id String @id @default(cuid())
- name String
- description String?
- createdById String
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ name String
+ description String?
+ days WeekDay[]
+ time String?
+ capacity Int?
+ price Decimal? @db.Decimal(10, 2)
+ 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)
- members GroupMember[]
- students Student[]
- payments Payment[]
+ 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")
}
+enum WeekDay {
+ MONDAY
+ TUESDAY
+ WEDNESDAY
+ THURSDAY
+ FRIDAY
+ SATURDAY
+ SUNDAY
+}
+
+enum BillingType {
+ MONTHLY
+ PER_CLASS
+}
+
model GroupMember {
- id String @id @default(cuid())
- groupId String
- userId String
- role Role @default(MEMBER) // OWNER, ADMIN, MEMBER
- joinedAt DateTime @default(now())
+ id String @id @default(cuid())
+ groupId String @map("group_id")
+ userId String @map("user_id")
+ role Role @default(MEMBER) // OWNER, ADMIN, MEMBER
+ 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")
}
@@ -36,42 +66,109 @@ enum Role {
MEMBER
}
-model Student {
- id String @id @default(cuid())
- groupId String
- fullName String
- email String?
- phone String?
- guardianName String?
- guardianPhone String?
- notes String?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+enum AttendeeStatus {
+ ACTIVE
+ PAUSED
+ DROPPED
+}
- group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
- payments Payment[]
+// A person the teacher works with (student, or the guardian's child). Contact
+// data lives here once; `Attendee` is their membership in each group, so one
+// person can be in several groups of the same teacher. The phone is unique per
+// teacher through a hand-written partial index (`people_owner_phone_key`,
+// `WHERE phone IS NOT NULL`): Prisma does not model it.
+model Person {
+ id String @id @default(cuid())
+ createdById String @map("created_by_id")
+ fullName String @map("full_name")
+ email String?
+ phone String?
+ guardianName String? @map("guardian_name")
+ guardianPhone String? @map("guardian_phone")
+ notes String?
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
- @@index([groupId])
- @@map("students")
+ owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
+ attendees Attendee[]
+ studentAccounts StudentAccountPerson[]
+
+ @@index([createdById])
+ @@map("people")
+}
+
+// Membership of a person in a group. Status, attendance, fees and the absence
+// link (`notifyToken`) are per group.
+model Attendee {
+ id String @id @default(cuid())
+ groupId String @map("group_id")
+ personId String @map("person_id")
+ notifyToken String? @unique(map: "attendees_notifyToken_key") @default(cuid()) @map("notify_token")
+ status AttendeeStatus @default(ACTIVE)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
+ person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
+ payments Payment[]
+ attendances Attendance[]
+ slotReleases SlotRelease[]
+ outboundMessages OutboundMessage[]
+ alertResolutions AttendeeAlertResolution[]
+ absenceNotices AbsenceNotice[]
+ reportedPayments ReportedPayment[]
+
+ @@unique([groupId, personId])
+ @@index([groupId], map: "attendees_groupId_idx")
+ @@index([personId])
+ @@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
- studentId String
- amount Decimal @db.Decimal(10, 2)
- currency String @default("MXN")
- status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
- dueDate DateTime
- paidAt DateTime?
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ id String @id @default(cuid())
+ groupId String @map("group_id")
+ attendeeId String @map("attendee_id")
+ amount Decimal @db.Decimal(10, 2)
+ currency String @default("ARS")
+ status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
+ dueDate DateTime @map("due_date")
+ description String? @map("description")
+ checkoutUrl String? @map("checkout_url")
+ mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
+ mpPaymentId String? @map("mp_payment_id")
+ paidAt DateTime? @map("paid_at")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
- group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
- student Student @relation(fields: [studentId], 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([studentId])
+ @@index([groupId], map: "payments_groupId_idx")
+ @@index([attendeeId], map: "payments_attendeeId_idx")
@@map("payments")
}
@@ -83,24 +180,113 @@ enum PaymentStatus {
}
model WaitlistEntry {
- id String @id @default(cuid())
+ id String @id @default(cuid())
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")
}
+model GroupWaitlistEntry {
+ id String @id @default(cuid())
+ 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()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "group_waitlist_entries_groupId_fkey")
+
+ @@unique([groupId, phone], map: "group_waitlist_entries_groupId_phone_key")
+ @@index([groupId], map: "group_waitlist_entries_groupId_idx")
+ @@map("group_waitlist_entries")
+}
+
enum WaitlistStatus {
PENDING
INVITED
JOINED
DECLINED
-}
\ No newline at end of file
+}
+
+enum PreRegistrationStatus {
+ PENDING
+ APPROVED
+ REJECTED
+}
+
+model GroupPreRegistration {
+ id String @id @default(cuid())
+ groupId String @map("group_id")
+ fullName String @map("full_name")
+ phone String
+ email String?
+ status PreRegistrationStatus @default(PENDING)
+ 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, map: "group_pre_registrations_groupId_fkey")
+
+ @@unique([groupId, phone], map: "group_pre_registrations_groupId_phone_key")
+ @@index([groupId], map: "group_pre_registrations_groupId_idx")
+ @@map("group_pre_registrations")
+}
+
+enum MpAccountStatus {
+ ACTIVE
+ REQUIRES_REAUTH
+ REVOKED
+}
+
+// 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())
+ 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")
+
+ owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey")
+
+ // 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")
+}
diff --git a/apps/backend/prisma/models/student-access.prisma b/apps/backend/prisma/models/student-access.prisma
new file mode 100644
index 0000000..0dd705b
--- /dev/null
+++ b/apps/backend/prisma/models/student-access.prisma
@@ -0,0 +1,240 @@
+// 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)
+ people StudentAccountPerson[]
+ tokens StudentAccessToken[]
+ sessions StudentSession[]
+ passkeys StudentPasskey[]
+ challenges StudentWebauthnChallenge[]
+ absenceNotices AbsenceNotice[]
+ reportedPayments ReportedPayment[]
+
+ @@index([recoveryEmail])
+ @@index([createdById])
+ @@map("student_accounts")
+}
+
+// The account is linked to people, not to memberships: it sees every group the
+// person is in (also the ones added later). A guardian may be linked to several
+// children (N:N).
+model StudentAccountPerson {
+ accountId String @map("account_id")
+ personId String @map("person_id")
+ createdAt DateTime @default(now()) @map("created_at")
+
+ account StudentAccount @relation(fields: [accountId], references: [id], onDelete: Cascade)
+ person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
+
+ @@id([accountId, personId])
+ @@index([personId])
+ @@map("student_account_people")
+}
+
+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:", "recovery: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")
+ // Optional message from the student to the teacher.
+ note String?
+ 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")
+}
diff --git a/apps/backend/prisma/models/whatsapp.prisma b/apps/backend/prisma/models/whatsapp.prisma
new file mode 100644
index 0000000..e653073
--- /dev/null
+++ b/apps/backend/prisma/models/whatsapp.prisma
@@ -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")
+}
diff --git a/apps/backend/prisma/schema.prisma b/apps/backend/prisma/schema.prisma
index 9415ac3..06c7663 100644
--- a/apps/backend/prisma/schema.prisma
+++ b/apps/backend/prisma/schema.prisma
@@ -7,4 +7,4 @@ generator client {
datasource db {
provider = "postgresql"
-}
\ No newline at end of file
+}
diff --git a/apps/backend/skills-lock.json b/apps/backend/skills-lock.json
new file mode 100644
index 0000000..56573ed
--- /dev/null
+++ b/apps/backend/skills-lock.json
@@ -0,0 +1,59 @@
+{
+ "version": 1,
+ "skills": {
+ "prisma-cli": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-cli/SKILL.md",
+ "computedHash": "129e77cba93984b88d66cf0f66d5788f5487431f17f189a1ab2d839976874e3b"
+ },
+ "prisma-client-api": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-client-api/SKILL.md",
+ "computedHash": "cbbabff961c8e16b2d59f8c1ffb4e7e20be52154e778ab95121e0211d6d09969"
+ },
+ "prisma-compute": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-compute/SKILL.md",
+ "computedHash": "c84ca5f84cc5cfca9f8e2dada066b1833143d6f325f70c12a16746c3c4eee2ed"
+ },
+ "prisma-database-setup": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-database-setup/SKILL.md",
+ "computedHash": "6a991a2530a6da7131e3fc71c353e8278702d0146b8b6e1d2fdfc2d3d0a21bd2"
+ },
+ "prisma-driver-adapter-implementation": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-driver-adapter-implementation/SKILL.md",
+ "computedHash": "cc487f1bf36f616ddb3a9478b3527d288dd706d77a9e5dbee9af52dca1eee8e4"
+ },
+ "prisma-mongodb-upgrade": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-mongodb-upgrade/SKILL.md",
+ "computedHash": "b94149ad5f1ec269dfd717b321538de6d39943b2ae6721a0d82302057f57ae18"
+ },
+ "prisma-postgres": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-postgres/SKILL.md",
+ "computedHash": "0422727e18019add9208b86ce862964025acc011ff31fba1d59a01b836bd6272"
+ },
+ "prisma-postgres-setup": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-postgres-setup/SKILL.md",
+ "computedHash": "5dbcf5a488d7cb7136340b86dcf781d6d92cf793f92c105ef644ac31ccac4d3b"
+ },
+ "prisma-upgrade-v7": {
+ "source": "prisma/skills",
+ "sourceType": "github",
+ "skillPath": "prisma-upgrade-v7/SKILL.md",
+ "computedHash": "0e07dc2831f86cf27627df914db43d862b0fc75d72c1f9070434aab7940bad7c"
+ }
+ }
+}
diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts
index 4faf921..3a064d7 100644
--- a/apps/backend/src/app.ts
+++ b/apps/backend/src/app.ts
@@ -10,12 +10,27 @@ 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 { studentsRoutes } from './modules/students';
+import { peopleRoutes } from './modules/people';
+import { studentPortalRoutes } from './modules/student-portal';
import { waitlistRoutes } from './modules/waitlist';
+import { whatsappRoutes } from './modules/whatsapp';
const app = new Hono();
@@ -30,12 +45,32 @@ 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('/students', studentsRoutes);
+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('/people', peopleRoutes);
+api.route('/student-portal', studentPortalRoutes);
app.notFound((c) => {
return problemJson(c, notFoundProblem(c.req.path));
diff --git a/apps/backend/src/assets/logotipo-y-organica.png b/apps/backend/src/assets/logotipo-y-organica.png
new file mode 100644
index 0000000..4179ead
Binary files /dev/null and b/apps/backend/src/assets/logotipo-y-organica.png differ
diff --git a/apps/backend/src/http/env.ts b/apps/backend/src/http/env.ts
index d68d3d7..4e6288a 100644
--- a/apps/backend/src/http/env.ts
+++ b/apps/backend/src/http/env.ts
@@ -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;
}
}
\ No newline at end of file
diff --git a/apps/backend/src/http/problem-builders.ts b/apps/backend/src/http/problem-builders.ts
index 1b63bd7..6db2820 100644
--- a/apps/backend/src/http/problem-builders.ts
+++ b/apps/backend/src/http/problem-builders.ts
@@ -21,6 +21,7 @@ export function conflictProblem(params: {
detail: string;
code?: string;
instance?: string;
+ params?: ProblemDetails['params'];
}): ProblemDetails {
return {
type: `${PROBLEM_DOMAIN}/problems/conflict`,
@@ -29,6 +30,7 @@ export function conflictProblem(params: {
detail: params.detail,
instance: params.instance,
code: params.code,
+ ...(params.params ? { params: params.params } : {}),
};
}
@@ -47,23 +49,6 @@ export function forbiddenProblem(params: {
};
}
-export function organizationNotFoundProblem(id: string): ProblemDetails {
- return {
- type: `${PROBLEM_DOMAIN}/problems/organization-not-found`,
- title: 'Not Found',
- status: 404,
- detail: `Organization ${id} was not found.`,
- code: 'organization_not_found',
- };
-}
-
-export function groupOwnerRequiredProblem(): ProblemDetails {
- return forbiddenProblem({
- detail: 'Only the organization owner can create the group.',
- code: 'group_owner_required',
- });
-}
-
export function databaseUnavailableProblem(params?: {
instance?: string;
}): ProblemDetails {
@@ -86,4 +71,251 @@ export function noGroupAccessProblem(): ProblemDetails {
export function notFoundResourceProblem(resourceName: string, id: string): ProblemDetails {
return notFoundProblem(`${resourceName} ${id}`);
-}
\ No newline at end of file
+}
+
+export function mpNotConnectedProblem(): ProblemDetails {
+ return conflictProblem({
+ 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.',
+ code: 'onboarding_already_completed',
+ });
+}
+
+export function capacityReachedProblem(capacity: number | null): ProblemDetails {
+ return conflictProblem({
+ detail: capacity
+ ? `El grupo alcanzó su cupo máximo de ${capacity} miembros.`
+ : 'El grupo alcanzó su cupo máximo de miembros.',
+ code: 'group_capacity_reached',
+ ...(capacity ? { params: { capacity } } : {}),
+ });
+}
+
+export function alreadyWaitlistedProblem(): ProblemDetails {
+ return conflictProblem({
+ detail: 'Este número de teléfono ya está en la lista de espera del grupo.',
+ code: 'already_waitlisted',
+ });
+}
+
+export function attendeeHasPaymentsProblem(): ProblemDetails {
+ return conflictProblem({
+ detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.',
+ 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;
+ params?: ProblemDetails['params'];
+}): ProblemDetails {
+ return {
+ type: `${PROBLEM_DOMAIN}/problems/plan`,
+ title: 'Payment Required',
+ status: 402,
+ detail: params.detail,
+ code: params.code,
+ ...(params.params ? { params: params.params } : {}),
+ };
+}
+
+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',
+ params: { limit, max },
+ });
+}
+
+/** 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',
+ params: { feature },
+ });
+}
+
+/** 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',
+ });
+}
diff --git a/apps/backend/src/http/security-headers.ts b/apps/backend/src/http/security-headers.ts
index a659b24..83b3ba4 100644
--- a/apps/backend/src/http/security-headers.ts
+++ b/apps/backend/src/http/security-headers.ts
@@ -14,7 +14,7 @@ export const corsMiddleware: MiddlewareHandler = honoCors({
return '';
},
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
- allowHeaders: ['Content-Type', 'Authorization'],
+ allowHeaders: ['Content-Type', 'Authorization', 'Cache-Control'],
maxAge: 600,
credentials: true,
});
diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts
index fe459df..cf0c3f7 100644
--- a/apps/backend/src/http/session-auth.ts
+++ b/apps/backend/src/http/session-auth.ts
@@ -27,10 +27,39 @@ export function isPublicApiRequest(method: string, path: string): boolean {
const normalizedPath = normalizePath(path);
+ // 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')
);
}
@@ -39,5 +68,8 @@ function matchesPublicPrefix(path: string, prefix: string): boolean {
}
function normalizePath(path: string): string {
- return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
+ const withoutQuery = path.split('?')[0]?.split('#')[0] ?? path;
+ return withoutQuery.length > 1 && withoutQuery.endsWith('/')
+ ? withoutQuery.slice(0, -1)
+ : withoutQuery;
}
\ No newline at end of file
diff --git a/apps/backend/src/lib/email.ts b/apps/backend/src/lib/email.ts
index e2269e9..dd62ad2 100644
--- a/apps/backend/src/lib/email.ts
+++ b/apps/backend/src/lib/email.ts
@@ -1,13 +1,61 @@
+import { readFileSync } from 'node:fs'
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
+}
-interface EmailProvider {
+// 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
+
+// Logo embedded as a data URI so the emails don't depend on hosting.
+function loadLogoTypoDataUri(): string {
+ try {
+ const base64 = readFileSync(
+ new URL('../assets/logotipo-y-organica.png', import.meta.url),
+ ).toString('base64')
+ return `data:image/png;base64,${base64}`
+ } catch {
+ return ''
+ }
+}
+
+const LOGO_DATA_URI = loadLogoTypoDataUri()
+
+export interface EmailProvider {
sendVerificationEmail(data: VerificationEmailData): Promise
sendPasswordResetEmail(data: PasswordResetEmailData): Promise
sendOrganizationInvitation(data: InvitationEmailData): Promise
+ sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise
+ sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise
+ sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise
+}
+
+// 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, ''')
+}
+
+function button(url: string, label: string): string {
+ return `${escapeHtml(label)}`
}
class SMTPEmailProvider implements EmailProvider {
@@ -30,17 +78,21 @@ class SMTPEmailProvider implements EmailProvider {
}
private layout(title: string, body: string) {
+ const header = LOGO_DATA_URI
+ ? `
`
+ : 'Gruperly
'
+
return `
-
- Gruperly
- ${title}
- ${body}
+
+ ${header}
+ ${title}
+ ${body}
`
}
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
@@ -49,7 +101,7 @@ class SMTPEmailProvider implements EmailProvider {
}
async sendVerificationEmail({ email, url, name }: VerificationEmailData) {
- const link = `Verificar email`
+ const link = `Verificar email`
await this.send(
email,
'Verifica tu email en Gruperly',
@@ -61,7 +113,7 @@ class SMTPEmailProvider implements EmailProvider {
}
async sendPasswordResetEmail({ email, url, name }: PasswordResetEmailData) {
- const link = `Restablecer contraseña`
+ const link = `Restablecer contraseña`
await this.send(
email,
'Restablece tu contraseña en Gruperly',
@@ -73,7 +125,7 @@ class SMTPEmailProvider implements EmailProvider {
}
async sendOrganizationInvitation({ email, url, organizationName }: InvitationEmailData) {
- const link = `Unirme a ${organizationName}`
+ const link = `Unirme a ${organizationName}`
await this.send(
email,
`Te invitaron a ${organizationName} en Gruperly`,
@@ -83,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.
${button(url, 'Confirmar mail')}`,
+ ),
+ )
+ }
+
+ async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) {
+ // A guardian may have one account per child with the same email: one button each.
+ const buttons = links
+ .map((link) =>
+ links.length > 1
+ ? `${escapeHtml(link.name)}
${button(link.url, 'Ingresar')}`
+ : button(link.url, 'Ingresar'),
+ )
+ .join('
')
+ 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.
${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 ? `
Motivo: ${escapeHtml(reason)}` : ''}
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),
+ )
+ }
}
-// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark).
-// Añadir implementaciones y alternar con EMAIL_PROVIDER.
+// Future: transactional providers (Resend, SendGrid, Postmark).
+// Add implementations and switch between them with EMAIL_PROVIDER.
export function createEmailProvider(): EmailProvider {
return new SMTPEmailProvider()
}
diff --git a/apps/backend/src/lib/file-type.ts b/apps/backend/src/lib/file-type.ts
new file mode 100644
index 0000000..23bc7fa
--- /dev/null
+++ b/apps/backend/src/lib/file-type.ts
@@ -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 = {
+ '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;
+}
diff --git a/apps/backend/src/lib/storage.ts b/apps/backend/src/lib/storage.ts
new file mode 100644
index 0000000..bd8612c
--- /dev/null
+++ b/apps/backend/src/lib/storage.ts
@@ -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;
+ /** GET URL valid for `expiresInSeconds`. */
+ signedUrl(key: string, expiresInSeconds: number): string;
+ remove(key: string): Promise;
+}
+
+/* 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 {
+ 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 {
+ 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;
+}
diff --git a/apps/backend/src/modules/admin/features/get-account/route.ts b/apps/backend/src/modules/admin/features/get-account/route.ts
new file mode 100644
index 0000000..5ec9959
--- /dev/null
+++ b/apps/backend/src/modules/admin/features/get-account/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/admin/features/get-account/use-case.ts b/apps/backend/src/modules/admin/features/get-account/use-case.ts
new file mode 100644
index 0000000..fab9353
--- /dev/null
+++ b/apps/backend/src/modules/admin/features/get-account/use-case.ts
@@ -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;
+ 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> {
+ 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),
+ });
+ }
+}
diff --git a/apps/backend/src/modules/admin/features/list-accounts/route.ts b/apps/backend/src/modules/admin/features/list-accounts/route.ts
new file mode 100644
index 0000000..f6cb10e
--- /dev/null
+++ b/apps/backend/src/modules/admin/features/list-accounts/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/admin/features/list-accounts/use-case.ts b/apps/backend/src/modules/admin/features/list-accounts/use-case.ts
new file mode 100644
index 0000000..0343d35
--- /dev/null
+++ b/apps/backend/src/modules/admin/features/list-accounts/use-case.ts
@@ -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;
+ 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> {
+ 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();
+ 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),
+ });
+ }
+}
diff --git a/apps/backend/src/modules/admin/features/me/route.ts b/apps/backend/src/modules/admin/features/me/route.ts
new file mode 100644
index 0000000..f36974c
--- /dev/null
+++ b/apps/backend/src/modules/admin/features/me/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/admin/index.ts b/apps/backend/src/modules/admin/index.ts
new file mode 100644
index 0000000..bd2b614
--- /dev/null
+++ b/apps/backend/src/modules/admin/index.ts
@@ -0,0 +1 @@
+export { default as adminRoutes } from './routes';
diff --git a/apps/backend/src/modules/admin/lib/access.ts b/apps/backend/src/modules/admin/lib/access.ts
new file mode 100644
index 0000000..0534bda
--- /dev/null
+++ b/apps/backend/src/modules/admin/lib/access.ts
@@ -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 = 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 = process.env,
+): MiddlewareHandler {
+ 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();
+ };
+}
diff --git a/apps/backend/src/modules/admin/lib/account-summary.ts b/apps/backend/src/modules/admin/lib/account-summary.ts
new file mode 100644
index 0000000..52e1bb8
--- /dev/null
+++ b/apps/backend/src/modules/admin/lib/account-summary.ts
@@ -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,
+ { 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,
+ { 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 } : {};
+}
diff --git a/apps/backend/src/modules/admin/lib/index.ts b/apps/backend/src/modules/admin/lib/index.ts
new file mode 100644
index 0000000..08efd7f
--- /dev/null
+++ b/apps/backend/src/modules/admin/lib/index.ts
@@ -0,0 +1,9 @@
+export { adminOnlyMiddleware, isAdminEmail } from './access';
+export {
+ type AccountRecord,
+ type AccountUsage,
+ accountPlan,
+ buildAccountWhere,
+ type PlanContext,
+ toAccountListItem,
+} from './account-summary';
diff --git a/apps/backend/src/modules/admin/routes.ts b/apps/backend/src/modules/admin/routes.ts
new file mode 100644
index 0000000..1abc5a9
--- /dev/null
+++ b/apps/backend/src/modules/admin/routes.ts
@@ -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;
diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts
new file mode 100644
index 0000000..b023827
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-attendee-history/route.ts
@@ -0,0 +1,21 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { GetAttendeeHistory } from './use-case';
+
+const route = new Hono();
+
+route.get('/:groupId/attendees/:attendeeId/history', async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+
+ const groupId = c.req.param('groupId');
+ const attendeeId = c.req.param('attendeeId');
+ const useCase = new GetAttendeeHistory();
+ const result = await useCase.execute(groupId, attendeeId, user.id);
+
+ return resultJson(c, result);
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts
new file mode 100644
index 0000000..67733fa
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-attendee-history/use-case.ts
@@ -0,0 +1,97 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ AttendanceStatus,
+ AttendeeHistory,
+ ProblemDetails,
+ Result,
+} from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { notFoundResourceProblem } from '@/http/problem-builders';
+import prisma from '@/lib/prisma';
+import { flattenPerson } from '@/modules/attendees/lib/helpers';
+import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
+
+export const HISTORY_SESSIONS_LIMIT = 20;
+
+type GetAttendeeHistoryDeps = {
+ db?: AnalyticsAccessDb & Pick;
+};
+
+export class GetAttendeeHistory {
+ constructor(private readonly deps: GetAttendeeHistoryDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ attendeeId: string,
+ userId: string,
+ ): Promise> {
+ 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 },
+ select: { id: true, createdAt: true, person: { select: { fullName: true } } },
+ }).then((row) => row && flattenPerson(row));
+ 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, startsAt: { gte: since } },
+ orderBy: { startsAt: 'desc' },
+ take: HISTORY_SESSIONS_LIMIT,
+ select: { id: true, startsAt: true },
+ });
+ const sessionIds = sessions.map((session) => session.id);
+
+ const attendances = sessionIds.length
+ ? await db.attendance.findMany({
+ where: { attendeeId, classSessionId: { in: sessionIds } },
+ select: { classSessionId: true, status: true },
+ })
+ : [];
+
+ const statusBySession = new Map(
+ attendances.map((record) => [record.classSessionId, record.status]),
+ );
+
+ const orderedSessions = sessions
+ .slice()
+ .reverse()
+ .map((session) => ({
+ classSessionId: session.id,
+ startsAt: session.startsAt.toISOString(),
+ status: statusBySession.get(session.id) ?? null,
+ }));
+
+ const presentCount = attendances.filter((record) => record.status === 'PRESENT').length;
+ const attendanceRate =
+ sessions.length > 0 ? Math.round((presentCount / sessions.length) * 100) : 0;
+
+ return ok({
+ attendeeId: attendee.id,
+ fullName: attendee.fullName,
+ groupId,
+ groupName: access.value.name,
+ attendanceRate,
+ sessions: orderedSessions,
+ });
+ }
+}
diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts
new file mode 100644
index 0000000..af7e136
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/route.ts
@@ -0,0 +1,19 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { GetGroupsRiskOverview } from './use-case';
+
+const route = new Hono();
+
+route.get('/overview', async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+
+ const useCase = new GetGroupsRiskOverview();
+ const result = await useCase.execute(user.id);
+
+ return resultJson(c, result);
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts
new file mode 100644
index 0000000..4521b38
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-groups-risk-overview/use-case.ts
@@ -0,0 +1,198 @@
+import { Prisma } from '@generated/prisma/client';
+import type {
+ AttendanceStatus,
+ GroupRiskLevel,
+ GroupRiskSummary,
+ GroupsRiskOverview,
+ ProblemDetails,
+ Result,
+ UrgentMemberSummary,
+} from '@gruperly/shared';
+import {
+ ATTENDANCE_RISK_RULES,
+ getGroupAttendanceSummary,
+ ok,
+ URGENT_MEMBERS_LIMIT,
+} from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { flattenPerson } from '@/modules/attendees/lib/helpers';
+import { buildGroupWhereForUser } from '@/modules/groups/lib';
+import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
+import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
+
+type GetGroupsRiskOverviewDeps = {
+ db?: {
+ group: Prisma.GroupDelegate;
+ classSession: Prisma.ClassSessionDelegate;
+ attendee: Prisma.AttendeeDelegate;
+ attendance: Prisma.AttendanceDelegate;
+ };
+ now?: Date;
+};
+
+type GroupRow = {
+ id: string;
+ name: string;
+ capacity: number | null;
+ /** The ones still waiting for a spot (`GroupWaitlistEntry` in PENDING). */
+ _count: { waitlist: number };
+};
+type AttendeeRow = { id: string; groupId: string; fullName: string; createdAt: Date };
+type SessionRow = { id: string; groupId: string; startsAt: Date };
+type AttendanceRow = {
+ attendeeId: string;
+ classSessionId: string;
+ status: AttendanceStatus;
+ classSession: { startsAt: Date };
+};
+
+// 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 = {}) {}
+
+ async execute(userId: string): Promise> {
+ const db = this.deps.db ?? prisma;
+ const now = this.deps.now ?? new Date();
+ const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
+
+ const groups = (await db.group.findMany({
+ where: buildGroupWhereForUser(userId) as Prisma.GroupWhereInput,
+ select: {
+ id: true,
+ name: true,
+ capacity: true,
+ _count: { select: { waitlist: { where: { status: 'PENDING' } } } },
+ },
+ })) as unknown as GroupRow[];
+
+ if (groups.length === 0) {
+ return ok({ items: [] });
+ }
+
+ const groupIds = groups.map((group) => group.id);
+
+ const [attendees, sessions, attendances] = await Promise.all([
+ db.attendee.findMany({
+ where: { groupId: { in: groupIds }, status: 'ACTIVE' },
+ select: { id: true, groupId: true, createdAt: true, person: { select: { fullName: true } } },
+ }).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
+ db.classSession.findMany({
+ where: { groupId: { in: groupIds }, startsAt: { gte: since } },
+ select: { id: true, groupId: true, startsAt: true },
+ orderBy: { startsAt: 'desc' },
+ }) as Promise,
+ /* 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: {
+ attendeeId: true,
+ classSessionId: true,
+ status: true,
+ classSession: { select: { startsAt: true } },
+ },
+ orderBy: { classSession: { startsAt: 'desc' } },
+ }) as Promise,
+ ]);
+
+ const sessionsByGroup = new Map();
+ for (const session of sessions) {
+ const list = sessionsByGroup.get(session.groupId) ?? [];
+ list.push(session);
+ sessionsByGroup.set(session.groupId, list);
+ }
+
+ const streamByAttendee = groupAttendanceByAttendee(attendances);
+
+ const items: GroupRiskSummary[] = groups.map((group) =>
+ buildSummary(group, attendees, sessionsByGroup, streamByAttendee, now),
+ );
+
+ return ok({ items });
+ }
+}
+
+/**
+ * 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` 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 buildSummary(
+ group: GroupRow,
+ attendees: AttendeeRow[],
+ sessionsByGroup: Map,
+ attendanceByAttendee: Map,
+ now: Date,
+): GroupRiskSummary {
+ const resumen = getGroupAttendanceSummary({
+ groupId: group.id,
+ capacity: group.capacity,
+ waitlistCount: group._count.waitlist,
+ now,
+ members: attendees
+ .filter((attendee) => attendee.groupId === group.id)
+ .map((attendee) =>
+ toMemberAttendance(
+ attendee,
+ sessionsByGroup.get(group.id) ?? [],
+ 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) => ({
+ attendeeId: urgente.attendeeId,
+ fullName: urgente.fullName,
+ level: urgente.level,
+ consecutiveAbsences: urgente.consecutiveAbsences,
+ daysSinceLastAttendance: urgente.daysSinceLastAttendance,
+ 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,
+ libres: resumen.libres,
+ enEspera: resumen.enEspera,
+ asistencia: resumen.asistencia,
+ urgentes,
+ };
+}
+
+function groupAttendanceByAttendee(rows: AttendanceRow[]): Map {
+ const byAttendee = new Map();
+ for (const row of rows) {
+ const list = byAttendee.get(row.attendeeId) ?? [];
+ list.push(row);
+ byAttendee.set(row.attendeeId, list);
+ }
+ return byAttendee;
+}
diff --git a/apps/backend/src/modules/analytics/features/get-overview/route.ts b/apps/backend/src/modules/analytics/features/get-overview/route.ts
new file mode 100644
index 0000000..94e4997
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-overview/route.ts
@@ -0,0 +1,20 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { GetGroupAnalytics } from './use-case';
+
+const route = new Hono();
+
+route.get('/:groupId/analytics', async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+
+ const groupId = c.req.param('groupId');
+ const useCase = new GetGroupAnalytics();
+ const result = await useCase.execute(groupId, user.id);
+
+ return resultJson(c, result);
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/features/get-overview/use-case.ts b/apps/backend/src/modules/analytics/features/get-overview/use-case.ts
new file mode 100644
index 0000000..6d848eb
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-overview/use-case.ts
@@ -0,0 +1,55 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { GroupAnalytics, ProblemDetails, Result } from '@gruperly/shared';
+import { ok } from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
+
+export const ANALYTICS_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
+
+type GetGroupAnalyticsDeps = {
+ db?: AnalyticsAccessDb & Pick;
+ now?: Date;
+};
+
+export class GetGroupAnalytics {
+ constructor(private readonly deps: GetGroupAnalyticsDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ userId: string,
+ ): Promise> {
+ 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 [sessions, attendances, recoveredSlots] = await Promise.all([
+ db.classSession.findMany({
+ where: { groupId, startsAt: { gte: since } },
+ select: { id: true },
+ }),
+ db.attendance.findMany({
+ where: { classSession: { groupId, startsAt: { gte: since } } },
+ select: { status: true },
+ }),
+ db.slotRelease.count({
+ where: { classSession: { groupId, startsAt: { gte: since } } },
+ }),
+ ]);
+
+ const totalClasses = sessions.length;
+ const totalMarked = attendances.length;
+ const totalPresent = attendances.filter((record) => record.status === 'PRESENT').length;
+
+ return ok({
+ attendanceRate: totalMarked > 0 ? Math.round((totalPresent / totalMarked) * 100) : 0,
+ totalPresent,
+ totalClasses,
+ recoveredSlots,
+ });
+ }
+}
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts
new file mode 100644
index 0000000..bcec58c
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/route.ts
@@ -0,0 +1,20 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { GetStudentsAtRisk } from './use-case';
+
+const route = new Hono();
+
+route.get('/:groupId/students-at-risk', async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+
+ const groupId = c.req.param('groupId');
+ const useCase = new GetStudentsAtRisk();
+ const result = await useCase.execute(groupId, user.id);
+
+ return resultJson(c, result);
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts
new file mode 100644
index 0000000..d3ea984
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/get-students-at-risk/use-case.ts
@@ -0,0 +1,143 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ AttendanceStatus,
+ ProblemDetails,
+ Result,
+ StudentAtRisk,
+ StudentsAtRisk,
+} from '@gruperly/shared';
+import { ok, summarizeMemberAttendance } from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { flattenPerson } from '@/modules/attendees/lib/helpers';
+import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
+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 & StudentsAtRiskDb;
+ now?: Date;
+};
+
+type AttendanceStreamRow = {
+ attendeeId: string;
+ classSessionId: string;
+ status: AttendanceStatus;
+ classSession: { startsAt: Date };
+};
+
+export class GetStudentsAtRisk {
+ constructor(private readonly deps: GetStudentsAtRiskDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ userId: string,
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+ const now = this.deps.now ?? new Date();
+
+ 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;
+
+/**
+ * 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 {
+ const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
+
+ const [windowSessions, attendees, attendances] = await Promise.all([
+ db.classSession.findMany({
+ where: { groupId, startsAt: { gte: since } },
+ select: { id: true, startsAt: true },
+ orderBy: { startsAt: 'desc' },
+ }),
+ db.attendee.findMany({
+ where: { groupId, status: 'ACTIVE' },
+ select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
+ }).then((rows) => rows.map(flattenPerson)),
+ db.attendance.findMany({
+ where: { attendee: { groupId } },
+ select: {
+ attendeeId: true,
+ classSessionId: true,
+ status: true,
+ classSession: { select: { startsAt: true } },
+ },
+ orderBy: { classSession: { startsAt: 'desc' } },
+ }),
+ ]);
+
+ const totalWindowSessions = windowSessions.length;
+ const streamByAttendee = groupAttendanceByAttendee(attendances);
+
+ const atRisk: StudentAtRisk[] = [];
+ for (const attendee of attendees) {
+ const rows = streamByAttendee.get(attendee.id) ?? [];
+ const signals = summarizeMemberAttendance(toMemberAttendance(attendee, windowSessions, rows), now);
+ const riskLevel = toRiskLevel(signals.level);
+ if (!riskLevel) {
+ continue;
+ }
+ // Display only: the verdict is the domain's. The rate keeps counting
+ // unrecorded classes as missed, which is what "asistencia mensual" says.
+ const stream = rows.map((row) => ({ status: row.status, occurredAt: row.classSession.startsAt }));
+ const consecutiveAbsences = signals.consecutiveAbsences;
+ const attendedAt = lastAttendedAt(stream);
+ const monthlyRate = monthlyAttendanceRate(
+ stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
+ totalWindowSessions,
+ );
+ atRisk.push({
+ attendeeId: attendee.id,
+ fullName: attendee.fullName,
+ phone: attendee.phone,
+ riskLevel,
+ consecutiveAbsences,
+ lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
+ monthlyAttendanceRate: monthlyRate,
+ });
+ }
+
+ atRisk.sort((a, b) => {
+ if (a.riskLevel !== b.riskLevel) {
+ return a.riskLevel === 'HIGH' ? -1 : 1;
+ }
+ if (a.consecutiveAbsences !== b.consecutiveAbsences) {
+ return b.consecutiveAbsences - a.consecutiveAbsences;
+ }
+ return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
+ });
+
+ return atRisk;
+}
+
+function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map {
+ const byAttendee = new Map();
+ for (const row of rows) {
+ const list = byAttendee.get(row.attendeeId) ?? [];
+ list.push(row);
+ byAttendee.set(row.attendeeId, list);
+ }
+ return byAttendee;
+}
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts b/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts
new file mode 100644
index 0000000..d46c4b8
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/update-attendee-status/route.ts
@@ -0,0 +1,24 @@
+import type { UpdateStudentStatus } from '@gruperly/shared';
+import { UpdateStudentStatusSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { UpdateAttendeeStatus } from './use-case';
+
+const route = new Hono();
+
+route.post('/:studentId/status', validate.json(UpdateStudentStatusSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+
+ const studentId = c.req.param('studentId');
+ const payload = c.req.valid('json') as UpdateStudentStatus;
+ const useCase = new UpdateAttendeeStatus();
+ const result = await useCase.execute(studentId, user.id, payload);
+
+ return resultJson(c, result);
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts b/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts
new file mode 100644
index 0000000..30cc3c7
--- /dev/null
+++ b/apps/backend/src/modules/analytics/features/update-attendee-status/use-case.ts
@@ -0,0 +1,53 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ ProblemDetails,
+ Result,
+ UpdateStudentStatus,
+ UpdateStudentStatusResult,
+} from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
+import prisma from '@/lib/prisma';
+
+type UpdateAttendeeStatusDeps = {
+ db?: Pick;
+};
+
+export class UpdateAttendeeStatus {
+ constructor(private readonly deps: UpdateAttendeeStatusDeps = {}) {}
+
+ async execute(
+ studentId: string,
+ userId: string,
+ payload: UpdateStudentStatus,
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+
+ const attendee = await db.attendee.findUnique({
+ where: { id: studentId },
+ include: { group: { include: { members: { where: { userId } } } } },
+ });
+
+ if (!attendee) {
+ return err(notFoundResourceProblem('Attendee', studentId));
+ }
+
+ const isOwner = attendee.group.createdById === userId;
+ const isMember = attendee.group.members.length > 0;
+ if (!isOwner && !isMember) {
+ return err(noGroupAccessProblem());
+ }
+
+ if (attendee.status === payload.status) {
+ return ok({ attendeeId: studentId, status: payload.status });
+ }
+
+ const updated = await db.attendee.update({
+ where: { id: studentId },
+ data: { status: payload.status },
+ select: { id: true, status: true },
+ });
+
+ return ok({ attendeeId: updated.id, status: updated.status });
+ }
+}
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/index.ts b/apps/backend/src/modules/analytics/index.ts
new file mode 100644
index 0000000..4b66d93
--- /dev/null
+++ b/apps/backend/src/modules/analytics/index.ts
@@ -0,0 +1,3 @@
+export { default as groupsRiskOverviewRoute } from './features/get-groups-risk-overview/route';
+export { default as studentStatusRoutes } from './features/update-attendee-status/route';
+export { default as analyticsRoutes } from './routes';
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/lib/access.ts b/apps/backend/src/modules/analytics/lib/access.ts
new file mode 100644
index 0000000..91c803a
--- /dev/null
+++ b/apps/backend/src/modules/analytics/lib/access.ts
@@ -0,0 +1,37 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { ProblemDetails, Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { noGroupAccessProblem, notFoundResourceProblem } from '@/http/problem-builders';
+
+export type AnalyticsAccessDb = Pick;
+
+type GroupWithAccess = {
+ id: string;
+ name: string;
+ createdById: string;
+ members: { userId: string }[];
+};
+
+// 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,
+ userId: string,
+): Promise> {
+ const group = await db.group.findUnique({
+ where: { id: groupId },
+ include: { members: { where: { userId } } },
+ });
+
+ if (!group) {
+ return err(notFoundResourceProblem('Group', groupId));
+ }
+
+ const isOwner = group.createdById === userId;
+ const isMember = group.members.length > 0;
+ if (!isOwner && !isMember) {
+ return err(noGroupAccessProblem());
+ }
+
+ return ok(group);
+}
\ No newline at end of file
diff --git a/apps/backend/src/modules/analytics/lib/member-attendance.ts b/apps/backend/src/modules/analytics/lib/member-attendance.ts
new file mode 100644
index 0000000..cc3cd65
--- /dev/null
+++ b/apps/backend/src/modules/analytics/lib/member-attendance.ts
@@ -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(
+ (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,
+ }));
+}
diff --git a/apps/backend/src/modules/analytics/lib/risk.ts b/apps/backend/src/modules/analytics/lib/risk.ts
new file mode 100644
index 0000000..26fb94c
--- /dev/null
+++ b/apps/backend/src/modules/analytics/lib/risk.ts
@@ -0,0 +1,27 @@
+export type AttendanceStreamEntry = {
+ status: 'PRESENT' | 'ABSENT' | 'EXCUSED';
+ occurredAt: Date;
+};
+
+// 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') {
+ return entry.occurredAt;
+ }
+ }
+ return null;
+}
+
+// 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,
+): number {
+ if (totalSessions <= 0) {
+ return 0;
+ }
+ const present = entries.filter((entry) => entry.status === 'PRESENT').length;
+ return Math.round((present / totalSessions) * 100);
+}
diff --git a/apps/backend/src/modules/analytics/routes.ts b/apps/backend/src/modules/analytics/routes.ts
new file mode 100644
index 0000000..7054589
--- /dev/null
+++ b/apps/backend/src/modules/analytics/routes.ts
@@ -0,0 +1,12 @@
+import { Hono } from 'hono';
+import getAttendeeHistoryRoute from './features/get-attendee-history/route';
+import getOverviewRoute from './features/get-overview/route';
+import getStudentsAtRiskRoute from './features/get-students-at-risk/route';
+
+const routes = new Hono();
+
+routes.route('/', getOverviewRoute);
+routes.route('/', getStudentsAtRiskRoute);
+routes.route('/', getAttendeeHistoryRoute);
+
+export default routes;
\ No newline at end of file
diff --git a/apps/backend/src/modules/attendees/features/add-to-group/route.ts b/apps/backend/src/modules/attendees/features/add-to-group/route.ts
new file mode 100644
index 0000000..9e17479
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/add-to-group/route.ts
@@ -0,0 +1,24 @@
+import type { AddAttendeeToGroup as AddAttendeeToGroupBody } from '@gruperly/shared';
+import { AddAttendeeToGroupSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { AddAttendeeToGroup } from './use-case';
+
+const route = new Hono();
+
+route.post('/:groupId/attendees/:attendeeId/add-to-group', validate.json(AddAttendeeToGroupSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
+
+ const useCase = new AddAttendeeToGroup();
+ const result = await useCase.execute({
+ groupId: c.req.param('groupId'),
+ attendeeId: c.req.param('attendeeId'),
+ userId: user.id,
+ targetGroupId: (c.req.valid('json') as AddAttendeeToGroupBody).targetGroupId,
+ });
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts b/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts
new file mode 100644
index 0000000..af24c3b
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/add-to-group/use-case.ts
@@ -0,0 +1,88 @@
+import type { Prisma, PrismaClient } from '@generated/prisma/client';
+import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
+import { default as prisma, UnitOfWork } from '@/lib/prisma';
+import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
+import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
+import { alreadyInGroupProblem, isUniqueViolation } from '@/modules/people/lib/people';
+import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
+
+type AddAttendeeToGroupDeps = {
+ db?: Pick;
+ unitOfWork?: Pick;
+};
+
+type AddAttendeeToGroupCommand = {
+ groupId: string;
+ attendeeId: string;
+ userId: string;
+ targetGroupId: string;
+};
+
+/* "Agregar a otro grupo": the same person gets a membership in another group of
+ the teacher and keeps this one. It does not take a new student slot of the
+ plan (the person is already counted) but the target's capacity applies. A
+ former membership there (DROPPED) is reactivated, history included. */
+export class AddAttendeeToGroup {
+ constructor(private readonly deps: AddAttendeeToGroupDeps = {}) {}
+
+ async execute(command: AddAttendeeToGroupCommand): Promise> {
+ const { groupId, attendeeId, userId, targetGroupId } = command;
+ const db = this.deps.db ?? prisma;
+ const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
+
+ const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
+ if (!sourceResult.ok) return sourceResult;
+
+ const attendee = await db.attendee.findFirst({
+ where: { id: attendeeId, groupId },
+ select: { personId: true },
+ });
+ if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
+
+ if (targetGroupId === groupId) {
+ return err(
+ conflictProblem({
+ detail: 'El miembro ya pertenece a este grupo.',
+ code: 'attendee_same_group',
+ }),
+ );
+ }
+
+ const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
+ if (!targetResult.ok) return targetResult;
+ const target = targetResult.value;
+
+ try {
+ return await unitOfWork.executeResult(
+ async (tx: Prisma.TransactionClient): Promise> => {
+ const former = await tx.attendee.findFirst({
+ where: { groupId: targetGroupId, personId: attendee.personId },
+ select: { id: true, status: true },
+ });
+ if (former && former.status !== 'DROPPED') return err(alreadyInGroupProblem());
+
+ const canJoin = await checkCanJoinGroup(tx, target, null);
+ if (!canJoin.ok) return canJoin;
+
+ const membership = former
+ ? await tx.attendee.update({
+ where: { id: former.id },
+ data: { status: 'ACTIVE' },
+ include: attendeeWithPerson,
+ })
+ : await tx.attendee.create({
+ data: { groupId: targetGroupId, personId: attendee.personId },
+ include: attendeeWithPerson,
+ });
+ return ok(toAttendeeDto(membership));
+ },
+ );
+ } catch (error) {
+ // Two clicks at once: the unique (group, person) lets only one through.
+ if (isUniqueViolation(error)) return err(alreadyInGroupProblem());
+ throw error;
+ }
+ }
+}
diff --git a/apps/backend/src/modules/attendees/features/add-to-waitlist/route.ts b/apps/backend/src/modules/attendees/features/add-to-waitlist/route.ts
new file mode 100644
index 0000000..e03c04e
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/add-to-waitlist/route.ts
@@ -0,0 +1,21 @@
+import { type CreateGroupWaitlistEntry, CreateGroupWaitlistEntrySchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { AddToGroupWaitlist } from './use-case';
+
+const route = new Hono();
+
+route.post('/:groupId/waitlist', validate.json(CreateGroupWaitlistEntrySchema), async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+ const groupId = c.req.param('groupId');
+ const body = c.req.valid('json') as CreateGroupWaitlistEntry;
+ const useCase = new AddToGroupWaitlist();
+ const result = await useCase.execute(groupId, user.id, body);
+ return resultJson(c, result, { status: 201 });
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts b/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts
new file mode 100644
index 0000000..c4e186c
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/add-to-waitlist/use-case.ts
@@ -0,0 +1,110 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { CreateGroupWaitlistEntry, GroupWaitlistEntryDto, ProblemDetails, Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import {
+ alreadyWaitlistedProblem,
+ conflictProblem,
+ noGroupAccessProblem,
+ notFoundResourceProblem,
+} from '@/http/problem-builders';
+import prisma from '@/lib/prisma';
+import { phoneVariants } from '@/modules/people/lib/people';
+import { normalizePhone } from '../../lib/helpers';
+
+type AddToGroupWaitlistDeps = {
+ db?: Pick;
+};
+
+type GroupWaitlistRecord = {
+ id: string;
+ groupId: string;
+ fullName: string;
+ phone: string;
+ email: string | null;
+ notes: string | null;
+ status: GroupWaitlistEntryDto['status'];
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+function toGroupWaitlistEntryDto(record: GroupWaitlistRecord): GroupWaitlistEntryDto {
+ return {
+ id: record.id,
+ groupId: record.groupId,
+ fullName: record.fullName,
+ phone: record.phone,
+ email: record.email,
+ notes: record.notes,
+ status: record.status,
+ createdAt: record.createdAt.toISOString(),
+ updatedAt: record.updatedAt.toISOString(),
+ };
+}
+
+export class AddToGroupWaitlist {
+ constructor(private readonly deps: AddToGroupWaitlistDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ userId: string,
+ payload: CreateGroupWaitlistEntry,
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+
+ const group = await db.group.findUnique({
+ where: { id: groupId },
+ include: {
+ members: { where: { userId } },
+ },
+ });
+
+ if (!group) {
+ return err(notFoundResourceProblem('Group', groupId));
+ }
+
+ const isOwner = group.createdById === userId;
+ const isMember = group.members.length > 0;
+ if (!isOwner && !isMember) {
+ return err(noGroupAccessProblem());
+ }
+
+ const phone = normalizePhone(payload.phone);
+
+ const existingAttendee = await db.attendee.findFirst({
+ where: {
+ groupId,
+ person: { phone: { in: phoneVariants(payload.phone) } },
+ },
+ });
+
+ if (existingAttendee) {
+ return err(
+ conflictProblem({
+ detail: 'Ya existe un alumno registrado con este número de teléfono en este grupo.',
+ code: 'attendee_already_registered',
+ }),
+ );
+ }
+
+ const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
+ where: { groupId, phone },
+ });
+
+ if (existingWaitlistEntry) {
+ return err(alreadyWaitlistedProblem());
+ }
+
+ const fullName = `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
+ const entry = await db.groupWaitlistEntry.create({
+ data: {
+ groupId,
+ fullName,
+ phone,
+ email: payload.email?.trim() || null,
+ notes: payload.notes?.trim() || null,
+ },
+ });
+
+ return ok(toGroupWaitlistEntryDto(entry as unknown as GroupWaitlistRecord));
+ }
+}
\ No newline at end of file
diff --git a/apps/backend/src/modules/attendees/features/bulk-create/route.ts b/apps/backend/src/modules/attendees/features/bulk-create/route.ts
new file mode 100644
index 0000000..bafd8b3
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/bulk-create/route.ts
@@ -0,0 +1,21 @@
+import { type BulkCreateAttendees, BulkCreateAttendeesSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { BulkCreateAttendeesUseCase } from './use-case';
+
+const route = new Hono();
+
+route.post('/:groupId/attendees/bulk', validate.json(BulkCreateAttendeesSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+ const groupId = c.req.param('groupId');
+ const body = c.req.valid('json') as BulkCreateAttendees;
+ const useCase = new BulkCreateAttendeesUseCase();
+ const result = await useCase.execute(groupId, user.id, body);
+ return resultJson(c, result, { status: 201 });
+});
+
+export default route;
diff --git a/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts
new file mode 100644
index 0000000..0edc689
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/bulk-create/use-case.ts
@@ -0,0 +1,154 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ BulkCreateAttendees,
+ BulkCreateAttendeesResult,
+ ProblemDetails,
+ Result,
+} from '@gruperly/shared';
+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, attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
+
+type BulkCreateAttendeesDeps = {
+ db?: Pick;
+ planGuard?: Pick;
+};
+
+export class BulkCreateAttendeesUseCase {
+ constructor(private readonly deps: BulkCreateAttendeesDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ userId: string,
+ payload: BulkCreateAttendees,
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+
+ const group = await db.group.findUnique({
+ where: { id: groupId },
+ include: {
+ members: { where: { userId } },
+ },
+ });
+
+ if (!group) {
+ return err(notFoundResourceProblem('Group', groupId));
+ }
+
+ const isOwner = group.createdById === userId;
+ const isMember = group.members.length > 0;
+ if (!isOwner && !isMember) {
+ return err(noGroupAccessProblem());
+ }
+
+ /* The teacher's people by phone: a row whose phone is already someone they
+ have is added to this group as that person (linked), unless that person
+ is already in the group (duplicate). */
+ const people = await db.person.findMany({
+ where: { createdById: group.createdById, phone: { not: null } },
+ select: {
+ id: true,
+ phone: true,
+ attendees: { select: { groupId: true, status: true } },
+ },
+ });
+ const peopleByPhone = new Map();
+ for (const person of people) {
+ if (person.phone) peopleByPhone.set(normalizePhone(person.phone), person);
+ }
+
+ let duplicatesCount = 0;
+ let invalidCount = 0;
+ // Only people not active in any group take a new slot of the plan.
+ let newlyCounted = 0;
+ const seenPhones = new Set();
+ const toLink: string[] = [];
+ const toCreate: Array<{
+ fullName: string;
+ phone: string;
+ email: string | null;
+ notes: string | null;
+ }> = [];
+
+ for (const item of payload.attendees) {
+ const phone = normalizePhone(item.phone || '');
+ const rawFullName = item.fullName?.trim() || `${item.firstName?.trim() ?? ''} ${item.lastName?.trim() ?? ''}`.trim();
+
+ if (!rawFullName || !phone) {
+ invalidCount++;
+ continue;
+ }
+
+ const existing = peopleByPhone.get(phone);
+ if (seenPhones.has(phone) || existing?.attendees.some((membership) => membership.groupId === groupId)) {
+ duplicatesCount++;
+ continue;
+ }
+ seenPhones.add(phone);
+
+ if (existing) {
+ toLink.push(existing.id);
+ if (!existing.attendees.some((membership) => membership.status === 'ACTIVE')) newlyCounted++;
+ continue;
+ }
+
+ newlyCounted++;
+ toCreate.push({
+ fullName: rawFullName,
+ phone,
+ email: item.email?.trim() || null,
+ notes: item.notes?.trim() || null,
+ });
+ }
+
+ // 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,
+ newlyCounted,
+ );
+ if (!allowed.ok) {
+ return allowed;
+ }
+
+ const createdRecords: AttendeeRecord[] = [];
+ for (const personId of toLink) {
+ createdRecords.push(
+ await db.attendee.create({
+ data: { groupId, personId },
+ include: attendeeWithPerson,
+ }),
+ );
+ }
+ for (const data of toCreate) {
+ createdRecords.push(
+ await db.attendee.create({
+ data: {
+ group: { connect: { id: groupId } },
+ person: { create: { ...data, createdById: group.createdById } },
+ },
+ include: attendeeWithPerson,
+ }),
+ );
+ }
+
+ const createdCount = createdRecords.length;
+ const linkedCount = toLink.length;
+ const linkedNote = linkedCount > 0 ? ` (${linkedCount} ya estaban en otros de tus grupos)` : '';
+ const message = duplicatesCount > 0
+ ? `${createdCount} alumnos agregados con éxito${linkedNote}, ${duplicatesCount} duplicados omitidos.`
+ : `${createdCount} alumnos agregados con éxito${linkedNote}.`;
+
+ return ok({
+ totalProcessed: payload.attendees.length,
+ createdCount,
+ linkedCount,
+ duplicatesCount,
+ invalidCount,
+ message,
+ created: createdRecords.map(toAttendeeDto),
+ });
+ }
+}
diff --git a/apps/backend/src/modules/attendees/features/create/route.ts b/apps/backend/src/modules/attendees/features/create/route.ts
new file mode 100644
index 0000000..8f6f33a
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/create/route.ts
@@ -0,0 +1,22 @@
+import { type CreateAttendee, CreateAttendeeSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { CreateAttendeeUseCase } from './use-case';
+
+const route = new Hono();
+
+route.post('/:groupId/attendees', validate.json(CreateAttendeeSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+ const groupId = c.req.param('groupId');
+ const body = c.req.valid('json') as CreateAttendee;
+ const allowOverflow = c.req.query('allowOverflow') === 'true';
+ const useCase = new CreateAttendeeUseCase();
+ const result = await useCase.execute(groupId, user.id, body, { allowOverflow });
+ return resultJson(c, result, { status: 201 });
+});
+
+export default route;
diff --git a/apps/backend/src/modules/attendees/features/create/use-case.ts b/apps/backend/src/modules/attendees/features/create/use-case.ts
new file mode 100644
index 0000000..814600d
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/create/use-case.ts
@@ -0,0 +1,175 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { CreateAttendee, CreateAttendeeResult, ProblemDetails, Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import {
+ alreadyWaitlistedProblem,
+ capacityReachedProblem,
+ noGroupAccessProblem,
+ notFoundResourceProblem,
+} from '@/http/problem-builders';
+import prisma from '@/lib/prisma';
+import { PlanGuard } from '@/modules/billing/lib/entitlements';
+import {
+ alreadyInGroupProblem,
+ findPersonByPhone,
+ isUniqueViolation,
+ personExistsProblem,
+} from '@/modules/people/lib/people';
+import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
+
+type CreateAttendeeDeps = {
+ db?: Pick;
+ planGuard?: Pick;
+};
+
+type CreateAttendeeOptions = {
+ allowOverflow?: boolean;
+};
+
+export class CreateAttendeeUseCase {
+ constructor(private readonly deps: CreateAttendeeDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ userId: string,
+ payload: CreateAttendee,
+ options: CreateAttendeeOptions = {},
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+
+ const group = await db.group.findUnique({
+ where: { id: groupId },
+ include: {
+ members: { where: { userId } },
+ },
+ });
+
+ if (!group) {
+ return err(notFoundResourceProblem('Group', groupId));
+ }
+
+ const isOwner = group.createdById === userId;
+ const isMember = group.members.length > 0;
+ if (!isOwner && !isMember) {
+ return err(noGroupAccessProblem());
+ }
+
+ const phone = normalizePhone(payload.phone);
+
+ /* The person: the one the form picked (`personId`, after the "ya existe"
+ hint) or a new one. A phone the teacher already has is never duplicated. */
+ let person: { id: string; fullName: string } | null = null;
+ if (payload.personId) {
+ person = await db.person.findFirst({
+ where: { id: payload.personId, createdById: group.createdById },
+ select: { id: true, fullName: true },
+ });
+ if (!person) {
+ return err(notFoundResourceProblem('Person', payload.personId));
+ }
+ } else {
+ const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
+ if (samePhone) {
+ return err(
+ samePhone.attendees.some((membership) => membership.groupId === groupId)
+ ? alreadyInGroupProblem()
+ : personExistsProblem(),
+ );
+ }
+ }
+
+ // A former member (DROPPED) comes back on the same membership: history included.
+ const membership = person
+ ? await db.attendee.findFirst({ where: { groupId, personId: person.id }, select: { id: true, status: true } })
+ : null;
+ if (membership && membership.status !== 'DROPPED') {
+ return err(alreadyInGroupProblem());
+ }
+
+ const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
+
+ if (group.capacity !== null) {
+ const currentCount = await db.attendee.count({
+ where: { groupId, status: 'ACTIVE' },
+ });
+
+ if (currentCount >= group.capacity) {
+ if (isOwner && !options.allowOverflow) {
+ return err(capacityReachedProblem(group.capacity));
+ }
+
+ if (!isOwner) {
+ const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
+ where: { groupId, phone },
+ });
+
+ if (existingWaitlistEntry) {
+ return err(alreadyWaitlistedProblem());
+ }
+
+ await db.groupWaitlistEntry.create({
+ data: {
+ groupId,
+ fullName,
+ phone,
+ email: payload.email?.trim() || null,
+ notes: payload.notes?.trim() || null,
+ },
+ });
+
+ return ok({
+ outcome: 'waitlisted',
+ message: `${fullName} fue agregado a la lista de espera del grupo.`,
+ });
+ }
+ }
+ }
+
+ // The owner's plan pays for the attendee, whoever adds it. It counts people:
+ // someone already active in another group does not take a new slot.
+ const alreadyCounted = person
+ ? (await db.attendee.count({ where: { personId: person.id, status: 'ACTIVE' } })) > 0
+ : false;
+ const allowed = await (this.deps.planGuard ?? new PlanGuard()).canAddAttendees(
+ group.createdById,
+ alreadyCounted ? 0 : 1,
+ );
+ if (!allowed.ok) {
+ return allowed;
+ }
+
+ try {
+ const attendee = membership
+ ? await db.attendee.update({
+ where: { id: membership.id },
+ data: { status: 'ACTIVE' },
+ include: attendeeWithPerson,
+ })
+ : await db.attendee.create({
+ data: {
+ group: { connect: { id: groupId } },
+ person: person
+ ? { connect: { id: person.id } }
+ : {
+ create: {
+ createdById: group.createdById,
+ fullName,
+ phone,
+ email: payload.email?.trim() || null,
+ notes: payload.notes?.trim() || null,
+ },
+ },
+ },
+ include: attendeeWithPerson,
+ });
+
+ return ok({ outcome: 'created', attendee: toAttendeeDto(attendee) });
+ } catch (error) {
+ // Lost a race: someone created that person or membership meanwhile.
+ if (isUniqueViolation(error)) {
+ return err(person ? alreadyInGroupProblem() : personExistsProblem());
+ }
+ throw error;
+ }
+ }
+}
diff --git a/apps/backend/src/modules/attendees/features/get-all/route.ts b/apps/backend/src/modules/attendees/features/get-all/route.ts
new file mode 100644
index 0000000..4f91c26
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/get-all/route.ts
@@ -0,0 +1,18 @@
+import type { AttendeeQuery } from '@gruperly/shared';
+import { AttendeeQuerySchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { resultJson } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { ListAttendees } from './use-case';
+
+const route = new Hono();
+
+route.get('/', validate.query(AttendeeQuerySchema), async (c) => {
+ const query = c.req.valid('query') as AttendeeQuery;
+ const useCase = new ListAttendees();
+ const result: Awaited> = await useCase.execute(query);
+
+ return resultJson(c, result);
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/attendees/features/get-all/use-case.ts b/apps/backend/src/modules/attendees/features/get-all/use-case.ts
new file mode 100644
index 0000000..e9e4726
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/get-all/use-case.ts
@@ -0,0 +1,55 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { AttendeeList, AttendeeQuery, ProblemDetails, Result } from '@gruperly/shared';
+import { ok, RECENT_ATTENDANCE_LIMIT } from '@gruperly/shared';
+import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
+import prisma from '@/lib/prisma';
+
+import { attendeeWithPerson, toAttendeeListItemDto } from '../../lib/helpers';
+
+type ListAttendeesDeps = {
+ db?: Pick;
+};
+
+export class ListAttendees {
+ constructor(private readonly deps: ListAttendeesDeps = {}) {}
+
+ async execute(query: AttendeeQuery): Promise> {
+ const db = this.deps.db ?? prisma;
+ const where = query.groupId ? { groupId: query.groupId } : undefined;
+
+ const [records, total] = await Promise.all([
+ /* 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: {
+ ...attendeeWithPerson,
+ // 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,
+ select: { status: true },
+ },
+ payments: {
+ where: { status: { not: 'CANCELLED' } },
+ orderBy: { dueDate: 'desc' },
+ take: 3,
+ select: { status: true, dueDate: true },
+ },
+ },
+ }),
+ where ? db.attendee.count({ where }) : db.attendee.count(),
+ ]);
+
+ return ok({
+ data: records.map((record) => toAttendeeListItemDto(record)),
+ pagination: getPaginationMetadata(query, total),
+ });
+ }
+}
diff --git a/apps/backend/src/modules/attendees/features/get-by-id/route.ts b/apps/backend/src/modules/attendees/features/get-by-id/route.ts
new file mode 100644
index 0000000..a954c68
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/get-by-id/route.ts
@@ -0,0 +1,20 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { GetAttendee } from './use-case';
+
+const route = new Hono();
+
+route.get('/:groupId/attendees/:attendeeId', async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+ const groupId = c.req.param('groupId');
+ const attendeeId = c.req.param('attendeeId');
+ const useCase = new GetAttendee();
+ const result = await useCase.execute(groupId, attendeeId, user.id);
+
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts
new file mode 100644
index 0000000..60b220e
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/get-by-id/use-case.ts
@@ -0,0 +1,66 @@
+import type { PrismaClient } from '@generated/prisma/client';
+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 { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
+import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
+
+type GetAttendeeDeps = {
+ db?: Pick;
+ now?: () => Date;
+};
+
+export class GetAttendee {
+ constructor(private readonly deps: GetAttendeeDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ attendeeId: string,
+ userId: string,
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+
+ const access = await findGroupForUser(db, groupId, userId);
+ if (!access.ok) {
+ return access;
+ }
+
+ const billingPeriod = currentMonthRange((this.deps.now ?? (() => new Date()))());
+ const attendee = await db.attendee.findFirst({
+ where: { id: attendeeId, groupId },
+ include: {
+ person: { select: { ...personContactSelect, ...personMembershipsSelect } },
+ 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));
+ }
+
+ const { attendees: memberships, ...person } = attendee.person;
+ return ok(
+ toAttendeeDetailDto({
+ ...attendee,
+ person,
+ otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
+ }),
+ );
+ }
+}
+
+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)),
+ };
+}
diff --git a/apps/backend/src/modules/attendees/features/get-stats/route.ts b/apps/backend/src/modules/attendees/features/get-stats/route.ts
new file mode 100644
index 0000000..6bf75f3
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/get-stats/route.ts
@@ -0,0 +1,20 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { GetAttendeeStats } from './use-case';
+
+const route = new Hono();
+
+route.get('/:groupId/attendees/:attendeeId/stats', async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+ const groupId = c.req.param('groupId');
+ const attendeeId = c.req.param('attendeeId');
+ const useCase = new GetAttendeeStats();
+ const result = await useCase.execute(groupId, attendeeId, user.id);
+
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/attendees/features/get-stats/use-case.ts b/apps/backend/src/modules/attendees/features/get-stats/use-case.ts
new file mode 100644
index 0000000..95144b1
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/get-stats/use-case.ts
@@ -0,0 +1,59 @@
+import type { AttendanceStatus, PrismaClient } from '@generated/prisma/client';
+import type { AttendeeStats, 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';
+
+type GetAttendeeStatsDeps = {
+ db?: Pick;
+};
+
+export class GetAttendeeStats {
+ constructor(private readonly deps: GetAttendeeStatsDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ attendeeId: string,
+ userId: string,
+ ): Promise> {
+ 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 },
+ select: { id: true },
+ });
+ if (!attendee) {
+ return err(notFoundResourceProblem('Attendee', attendeeId));
+ }
+
+ const rows = await db.attendance.groupBy({
+ by: ['status'],
+ where: { attendeeId },
+ _count: { _all: true },
+ });
+
+ const countByStatus = (status: AttendanceStatus): number =>
+ rows.find((row) => row.status === status)?._count._all ?? 0;
+
+ const presentCount = countByStatus('PRESENT');
+ const absentCount = countByStatus('ABSENT');
+ const excusedCount = countByStatus('EXCUSED');
+ const totalMarked = presentCount + absentCount + excusedCount;
+
+ return ok({
+ attendeeId,
+ groupId,
+ presentCount,
+ absentCount,
+ excusedCount,
+ totalMarked,
+ attendanceRate: totalMarked > 0 ? Math.round((presentCount / totalMarked) * 100) : 0,
+ });
+ }
+}
diff --git a/apps/backend/src/modules/attendees/features/move/route.ts b/apps/backend/src/modules/attendees/features/move/route.ts
new file mode 100644
index 0000000..2b74ba0
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/move/route.ts
@@ -0,0 +1,24 @@
+import type { MoveAttendee as MoveAttendeeBody } from '@gruperly/shared';
+import { MoveAttendeeSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { MoveAttendee } from './use-case';
+
+const route = new Hono();
+
+route.post('/:groupId/attendees/:attendeeId/move', validate.json(MoveAttendeeSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
+
+ const useCase = new MoveAttendee();
+ const result = await useCase.execute({
+ groupId: c.req.param('groupId'),
+ attendeeId: c.req.param('attendeeId'),
+ userId: user.id,
+ targetGroupId: (c.req.valid('json') as MoveAttendeeBody).targetGroupId,
+ });
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/attendees/features/move/use-case.ts b/apps/backend/src/modules/attendees/features/move/use-case.ts
new file mode 100644
index 0000000..5fd2394
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/move/use-case.ts
@@ -0,0 +1,77 @@
+import type { Prisma, PrismaClient } from '@generated/prisma/client';
+import type { AttendeeDto, ProblemDetails, Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { conflictProblem, notFoundResourceProblem } from '@/http/problem-builders';
+import { default as prisma, UnitOfWork } from '@/lib/prisma';
+import { findGroupOwnedByUser } from '@/modules/group-waitlist/lib/helpers';
+import { checkCanJoinGroup } from '@/modules/group-waitlist/lib/promote';
+import { attendeeWithPerson, toAttendeeDto } from '../../lib/helpers';
+
+type MoveAttendeeDeps = {
+ db?: Pick;
+ unitOfWork?: UnitOfWork;
+ now?: () => Date;
+};
+
+type MoveAttendeeCommand = {
+ groupId: string;
+ attendeeId: string;
+ userId: string;
+ targetGroupId: string;
+};
+
+/* Moves a member to another group of the same teacher. It is the same attendee
+ with another `groupId`: past attendance, fees (they stay owed to the old
+ group) and the student app access go with them. Only what was booked for
+ the old group's future classes is undone: absence notices, the EXCUSED rows
+ they left and the released slots. */
+export class MoveAttendee {
+ constructor(private readonly deps: MoveAttendeeDeps = {}) {}
+
+ async execute(command: MoveAttendeeCommand): Promise> {
+ const { groupId, attendeeId, userId, targetGroupId } = command;
+ const db = this.deps.db ?? prisma;
+ const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
+ const now = this.deps.now?.() ?? new Date();
+
+ const sourceResult = await findGroupOwnedByUser(db, groupId, userId);
+ if (!sourceResult.ok) return sourceResult;
+
+ const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId } });
+ if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
+
+ if (targetGroupId === groupId) {
+ return err(
+ conflictProblem({
+ detail: 'El miembro ya pertenece a este grupo.',
+ code: 'attendee_same_group',
+ }),
+ );
+ }
+
+ const targetResult = await findGroupOwnedByUser(db, targetGroupId, userId);
+ if (!targetResult.ok) return targetResult;
+
+ return unitOfWork.executeResult(
+ async (tx: Prisma.TransactionClient): Promise> => {
+ const canJoin = await checkCanJoinGroup(tx, targetResult.value, attendee.personId);
+ if (!canJoin.ok) return canJoin;
+
+ const futureOldClasses = { classSession: { groupId, startsAt: { gt: now } } };
+ await tx.absenceNotice.updateMany({
+ where: { attendeeId, cancelledAt: null, ...futureOldClasses },
+ data: { cancelledAt: now },
+ });
+ await tx.attendance.deleteMany({ where: { attendeeId, ...futureOldClasses } });
+ await tx.slotRelease.deleteMany({ where: { attendeeId, isClaimed: false, ...futureOldClasses } });
+
+ const moved = await tx.attendee.update({
+ where: { id: attendeeId },
+ data: { groupId: targetGroupId },
+ include: attendeeWithPerson,
+ });
+ return ok(toAttendeeDto(moved));
+ },
+ );
+ }
+}
diff --git a/apps/backend/src/modules/attendees/features/remove/route.ts b/apps/backend/src/modules/attendees/features/remove/route.ts
new file mode 100644
index 0000000..6596ffc
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/remove/route.ts
@@ -0,0 +1,24 @@
+import { type RemoveAttendeeQuery, RemoveAttendeeQuerySchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { RemoveAttendee } from './use-case';
+
+const route = new Hono();
+
+route.delete('/:groupId/attendees/:attendeeId', validate.query(RemoveAttendeeQuerySchema), async (c) => {
+ const user = c.get('user');
+ if (!user) {
+ return problemJson(c, unauthorizedProblem(c.req.path));
+ }
+ const groupId = c.req.param('groupId');
+ const attendeeId = c.req.param('attendeeId');
+ const query = c.req.valid('query') as RemoveAttendeeQuery;
+ const useCase = new RemoveAttendee();
+ const result = await useCase.execute(groupId, attendeeId, user.id, {
+ promoteFromWaitlist: query.promoteFromWaitlist,
+ });
+ return resultJson(c, result);
+});
+
+export default route;
\ No newline at end of file
diff --git a/apps/backend/src/modules/attendees/features/remove/use-case.ts b/apps/backend/src/modules/attendees/features/remove/use-case.ts
new file mode 100644
index 0000000..9201822
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/remove/use-case.ts
@@ -0,0 +1,80 @@
+import type { Prisma, PrismaClient } from '@generated/prisma/client';
+import type { ProblemDetails, RemoveAttendeeResult, Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { attendeeHasPaymentsProblem, notFoundResourceProblem } from '@/http/problem-builders';
+import { default as prisma, UnitOfWork } from '@/lib/prisma';
+import {
+ findGroupOwnedByUser,
+ toGroupWaitlistEntryDto,
+} from '@/modules/group-waitlist/lib/helpers';
+import { promoteFirstPendingWaitlistEntry } from '@/modules/group-waitlist/lib/promote';
+
+type RemoveAttendeeDeps = {
+ db?: Pick;
+ unitOfWork?: UnitOfWork;
+};
+
+type RemoveAttendeeOptions = {
+ promoteFromWaitlist?: boolean;
+};
+
+export class RemoveAttendee {
+ constructor(private readonly deps: RemoveAttendeeDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ attendeeId: string,
+ userId: string,
+ options: RemoveAttendeeOptions = {},
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+ const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
+
+ const groupResult = await findGroupOwnedByUser(db, groupId, userId);
+ if (!groupResult.ok) {
+ return groupResult;
+ }
+ const group = groupResult.value;
+
+ const attendee = await db.attendee.findFirst({
+ where: { id: attendeeId, groupId },
+ select: { personId: true },
+ });
+ if (!attendee) {
+ return err(notFoundResourceProblem('Attendee', attendeeId));
+ }
+
+ const paymentsCount = await db.payment.count({ where: { attendeeId } });
+ if (paymentsCount > 0) {
+ return err(attendeeHasPaymentsProblem());
+ }
+
+ return unitOfWork.executeResult(
+ async (tx: Prisma.TransactionClient): Promise> => {
+ await tx.attendee.delete({ where: { id: attendeeId } });
+ // Their last group: the person goes too (with their student app link).
+ await tx.person.deleteMany({
+ where: { id: attendee.personId, attendees: { none: {} } },
+ });
+
+ if (!options.promoteFromWaitlist) {
+ return ok({ removedAttendeeId: attendeeId, promoted: null });
+ }
+
+ const promoteResult = await promoteFirstPendingWaitlistEntry(tx, group);
+ if (!promoteResult.ok) {
+ return err(promoteResult.error);
+ }
+ if (!promoteResult.value) {
+ return ok({ removedAttendeeId: attendeeId, promoted: null });
+ }
+
+ await tx.groupWaitlistEntry.delete({ where: { id: promoteResult.value.entry.id } });
+ return ok({
+ removedAttendeeId: attendeeId,
+ promoted: toGroupWaitlistEntryDto(promoteResult.value.entry),
+ });
+ },
+ );
+ }
+}
\ No newline at end of file
diff --git a/apps/backend/src/modules/attendees/features/update/route.ts b/apps/backend/src/modules/attendees/features/update/route.ts
new file mode 100644
index 0000000..507b5ac
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/update/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/attendees/features/update/use-case.ts b/apps/backend/src/modules/attendees/features/update/use-case.ts
new file mode 100644
index 0000000..1af86d7
--- /dev/null
+++ b/apps/backend/src/modules/attendees/features/update/use-case.ts
@@ -0,0 +1,64 @@
+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 { isUniqueViolation, personPhoneTakenProblem } from '@/modules/people/lib/people';
+import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
+
+type UpdateAttendeeDeps = {
+ db?: Pick;
+};
+
+type UpdateAttendeeCommand = {
+ groupId: string;
+ attendeeId: string;
+ userId: string;
+ input: UpdateAttendee;
+};
+
+export class UpdateAttendeeDetails {
+ constructor(private readonly deps: UpdateAttendeeDeps = {}) {}
+
+ async execute(command: UpdateAttendeeCommand): Promise> {
+ 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 },
+ select: { personId: true },
+ });
+ if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
+
+ // Contact data is the person's: the change shows in every group they are in.
+ try {
+ await db.person.update({
+ where: { id: attendee.personId },
+ data: normalizeEditableFields(input),
+ });
+ } catch (error) {
+ if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
+ throw error;
+ }
+
+ const updated = await db.attendee.findUniqueOrThrow({
+ where: { id: attendeeId },
+ include: attendeeWithPerson,
+ });
+ return ok(toAttendeeDto(updated));
+ }
+}
+
+function normalizeEditableFields(input: UpdateAttendee): UpdateAttendee {
+ return Object.fromEntries(
+ Object.entries(input).map(([key, value]) => {
+ if (value === '') return [key, null];
+ // Same normalization as the add form, so the phone keeps matching.
+ if (key === 'phone' && typeof value === 'string') return [key, normalizePhone(value)];
+ return [key, value];
+ }),
+ );
+}
diff --git a/apps/backend/src/modules/attendees/index.ts b/apps/backend/src/modules/attendees/index.ts
new file mode 100644
index 0000000..ef72296
--- /dev/null
+++ b/apps/backend/src/modules/attendees/index.ts
@@ -0,0 +1 @@
+export { default as attendeesRoutes } from './routes';
\ No newline at end of file
diff --git a/apps/backend/src/modules/attendees/lib/helpers.ts b/apps/backend/src/modules/attendees/lib/helpers.ts
new file mode 100644
index 0000000..066bd00
--- /dev/null
+++ b/apps/backend/src/modules/attendees/lib/helpers.ts
@@ -0,0 +1,126 @@
+import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
+
+/* Contact data of the person behind an attendee (shared by all their groups). */
+export const personContactSelect = {
+ id: true,
+ fullName: true,
+ email: true,
+ phone: true,
+ guardianName: true,
+ guardianPhone: true,
+ notes: true,
+} as const;
+
+/* `include` for any attendee query that ends up in `toAttendeeDto`. */
+export const attendeeWithPerson = { person: { select: personContactSelect } } as const;
+
+export type PersonContactRecord = {
+ id: string;
+ fullName: string;
+ email: string | null;
+ phone: string | null;
+ guardianName: string | null;
+ guardianPhone: string | null;
+ notes: string | null;
+};
+
+export type AttendeeRecord = {
+ id: string;
+ groupId: string;
+ personId: string;
+ notifyToken?: string | null;
+ createdAt: Date;
+ updatedAt: Date;
+ person: PersonContactRecord;
+};
+
+/** Listing item with the attendance and payment summary already resolved. */
+export type AttendeeListItemRecord = AttendeeRecord & {
+ attendances: { status: AttendeeListItem['recentAttendance'][number] }[];
+ payments: {
+ status: NonNullable['status'];
+ dueDate: Date;
+ }[];
+};
+
+export type AttendeeDetailRecord = AttendeeRecord & {
+ payments: AttendeeListItemRecord['payments'];
+ otherGroups: AttendeeDetailDto['otherGroups'];
+};
+
+export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
+ return {
+ id: record.id,
+ groupId: record.groupId,
+ personId: record.personId,
+ fullName: record.person.fullName,
+ email: record.person.email,
+ phone: record.person.phone,
+ guardianName: record.person.guardianName,
+ guardianPhone: record.person.guardianPhone,
+ notes: record.person.notes,
+ notifyToken: record.notifyToken ?? null,
+ createdAt: record.createdAt.toISOString(),
+ updatedAt: record.updatedAt.toISOString(),
+ };
+}
+
+/* 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 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());
+ const outstanding = byDueDate.find((payment) => payment.status !== 'PAID');
+ const relevant = outstanding ?? byDueDate[byDueDate.length - 1];
+
+ if (!relevant) {
+ return null;
+ }
+ return { status: relevant.status, dueDate: relevant.dueDate.toISOString() };
+}
+
+export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetailDto {
+ return {
+ ...toAttendeeDto(record),
+ payment: pickRelevantPayment(record.payments),
+ otherGroups: record.otherGroups,
+ };
+}
+
+/* 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),
+ recentAttendance: [...record.attendances].reverse().map((attendance) => attendance.status),
+ payment: pickRelevantPayment(record.payments),
+ };
+}
+
+/**
+ * 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();
+ const hasPlus = trimmed.startsWith('+');
+ const digitsOnly = trimmed.replace(/\D/g, '');
+ return hasPlus ? `+${digitsOnly}` : digitsOnly;
+}
+
+/* For queries that select a few person fields next to the attendee's: turns
+ `{ id, person: { fullName } }` into `{ id, fullName }`, so the code reading
+ flat rows stays as it was. */
+export function flattenPerson(
+ row: TRow,
+): Omit & TRow['person'] {
+ const { person, ...rest } = row;
+ return { ...rest, ...person };
+}
diff --git a/apps/backend/src/modules/students/routes.ts b/apps/backend/src/modules/attendees/routes.ts
similarity index 100%
rename from apps/backend/src/modules/students/routes.ts
rename to apps/backend/src/modules/attendees/routes.ts
diff --git a/apps/backend/src/modules/attention/features/get-overview/route.ts b/apps/backend/src/modules/attention/features/get-overview/route.ts
new file mode 100644
index 0000000..1d981ce
--- /dev/null
+++ b/apps/backend/src/modules/attention/features/get-overview/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/attention/features/get-overview/use-case.ts b/apps/backend/src/modules/attention/features/get-overview/use-case.ts
new file mode 100644
index 0000000..aeec72e
--- /dev/null
+++ b/apps/backend/src/modules/attention/features/get-overview/use-case.ts
@@ -0,0 +1,188 @@
+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 { flattenPerson } from '@/modules/attendees/lib/helpers';
+import { buildGroupWhereForUser } from '@/modules/groups/lib';
+import { contactPhone } from '@/modules/people/lib/people';
+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> {
+ 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,
+ createdAt: true,
+ person: { select: { fullName: true, phone: true, guardianPhone: true } },
+ },
+ orderBy: { createdAt: 'asc' },
+ }).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
+ // 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,
+ db.attendance.findMany({
+ where: { attendee: { groupId: { in: groupIds }, status: 'ACTIVE' } },
+ select: {
+ attendeeId: true,
+ classSessionId: true,
+ status: true,
+ classSession: { select: { startsAt: true } },
+ },
+ }) as Promise,
+ 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,
+ db.attendeeAlertResolution.findMany({
+ where: { attendee: { groupId: { in: groupIds } } },
+ select: { attendeeId: true, kind: true, signature: true },
+ }) as Promise,
+ ]);
+
+ 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 = contactPhone(attendee);
+ 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(rows: T[], key: (row: T) => string): Map {
+ const map = new Map();
+ for (const row of rows) {
+ const list = map.get(key(row)) ?? [];
+ list.push(row);
+ map.set(key(row), list);
+ }
+ return map;
+}
diff --git a/apps/backend/src/modules/attention/features/resolve/route.ts b/apps/backend/src/modules/attention/features/resolve/route.ts
new file mode 100644
index 0000000..62ed14e
--- /dev/null
+++ b/apps/backend/src/modules/attention/features/resolve/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/attention/features/resolve/use-case.ts b/apps/backend/src/modules/attention/features/resolve/use-case.ts
new file mode 100644
index 0000000..fce1418
--- /dev/null
+++ b/apps/backend/src/modules/attention/features/resolve/use-case.ts
@@ -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> {
+ 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 });
+ }
+}
diff --git a/apps/backend/src/modules/attention/index.ts b/apps/backend/src/modules/attention/index.ts
new file mode 100644
index 0000000..b7196c4
--- /dev/null
+++ b/apps/backend/src/modules/attention/index.ts
@@ -0,0 +1 @@
+export { default as attentionRoutes } from './routes';
diff --git a/apps/backend/src/modules/attention/lib/alert-kind.ts b/apps/backend/src/modules/attention/lib/alert-kind.ts
new file mode 100644
index 0000000..777e155
--- /dev/null
+++ b/apps/backend/src/modules/attention/lib/alert-kind.ts
@@ -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 = {
+ ATTENDANCE: 'asistencia',
+ PAYMENT: 'pago',
+};
+
+export const ALERT_TYPE_TO_KIND: Record = {
+ asistencia: 'ATTENDANCE',
+ pago: 'PAYMENT',
+};
diff --git a/apps/backend/src/modules/attention/routes.ts b/apps/backend/src/modules/attention/routes.ts
new file mode 100644
index 0000000..ba1c069
--- /dev/null
+++ b/apps/backend/src/modules/attention/routes.ts
@@ -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;
diff --git a/apps/backend/src/modules/auth/auth.ts b/apps/backend/src/modules/auth/auth.ts
index cb1d572..8f9458e 100644
--- a/apps/backend/src/modules/auth/auth.ts
+++ b/apps/backend/src/modules/auth/auth.ts
@@ -1,4 +1,5 @@
import { passkey } from '@better-auth/passkey';
+import { appLocaleSchema } from '@gruperly/shared';
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { organization } from 'better-auth/plugins/organization';
@@ -11,9 +12,22 @@ export const auth = betterAuth({
database: prismaAdapter(getPrismaClient(), {
provider: 'postgresql',
}),
+ user: {
+ additionalFields: {
+ // UI language chosen in Ajustes; null means "follow the device". The web
+ // saves it with updateUser and reads it back from the session.
+ locale: {
+ type: 'string',
+ required: false,
+ input: true,
+ validator: { input: appLocaleSchema.nullable() },
+ },
+ },
+ },
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
+ revokeSessionsOnPasswordReset: true,
sendResetPassword: async ({ user, url }) => {
await emailProvider.sendPasswordResetEmail({
email: user.email,
diff --git a/apps/backend/src/modules/billing/features/cancel/route.ts b/apps/backend/src/modules/billing/features/cancel/route.ts
new file mode 100644
index 0000000..ec19a5f
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/cancel/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/billing/features/cancel/use-case.ts b/apps/backend/src/modules/billing/features/cancel/use-case.ts
new file mode 100644
index 0000000..9821dd1
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/cancel/use-case.ts
@@ -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;
+ 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> {
+ 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' });
+ }
+}
diff --git a/apps/backend/src/modules/billing/features/charges/route.ts b/apps/backend/src/modules/billing/features/charges/route.ts
new file mode 100644
index 0000000..5cc6c0f
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/charges/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/billing/features/charges/use-case.ts b/apps/backend/src/modules/billing/features/charges/use-case.ts
new file mode 100644
index 0000000..8873b6e
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/charges/use-case.ts
@@ -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 };
+
+/** The professor's own Pro charges, newest first. */
+export class ListBillingCharges {
+ constructor(private readonly deps: ListBillingChargesDeps = {}) {}
+
+ async execute(
+ query: BillingChargesQuery,
+ userId: string,
+ ): Promise> {
+ 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),
+ });
+ }
+}
diff --git a/apps/backend/src/modules/billing/features/status/route.ts b/apps/backend/src/modules/billing/features/status/route.ts
new file mode 100644
index 0000000..b79fe1c
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/status/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/billing/features/status/use-case.ts b/apps/backend/src/modules/billing/features/status/use-case.ts
new file mode 100644
index 0000000..42130ef
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/status/use-case.ts
@@ -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;
+ guard?: PlanGuard;
+ sync?: Pick;
+ providers?: BillingProviderResolver;
+ now?: () => Date;
+};
+
+export class GetBillingStatus {
+ constructor(private readonly deps: GetBillingStatusDeps = {}) {}
+
+ async execute(userId: string): Promise> {
+ 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,
+ });
+ }
+}
diff --git a/apps/backend/src/modules/billing/features/subscribe/route.ts b/apps/backend/src/modules/billing/features/subscribe/route.ts
new file mode 100644
index 0000000..4013de7
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/subscribe/route.ts
@@ -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;
diff --git a/apps/backend/src/modules/billing/features/subscribe/use-case.ts b/apps/backend/src/modules/billing/features/subscribe/use-case.ts
new file mode 100644
index 0000000..52ecbe0
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/subscribe/use-case.ts
@@ -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;
+ 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> {
+ 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>;
+ 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 });
+ }
+}
diff --git a/apps/backend/src/modules/billing/features/webhook/route.ts b/apps/backend/src/modules/billing/features/webhook/route.ts
new file mode 100644
index 0000000..e055182
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/webhook/route.ts
@@ -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 = {
+ 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;
diff --git a/apps/backend/src/modules/billing/features/webhook/use-case.ts b/apps/backend/src/modules/billing/features/webhook/use-case.ts
new file mode 100644
index 0000000..d4a700c
--- /dev/null
+++ b/apps/backend/src/modules/billing/features/webhook/use-case.ts
@@ -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;
+ providers?: BillingProviderResolver;
+ sync?: Pick;
+};
+
+/** 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> {
+ 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');
+ }
+ }
+}
diff --git a/apps/backend/src/modules/billing/index.ts b/apps/backend/src/modules/billing/index.ts
new file mode 100644
index 0000000..c664a9e
--- /dev/null
+++ b/apps/backend/src/modules/billing/index.ts
@@ -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';
diff --git a/apps/backend/src/modules/billing/jobs/index.ts b/apps/backend/src/modules/billing/jobs/index.ts
new file mode 100644
index 0000000..01574f3
--- /dev/null
+++ b/apps/backend/src/modules/billing/jobs/index.ts
@@ -0,0 +1,2 @@
+export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
+export { startBillingJobs } from './schedule';
diff --git a/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts b/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts
new file mode 100644
index 0000000..0c3e15d
--- /dev/null
+++ b/apps/backend/src/modules/billing/jobs/reconcile-subscriptions.ts
@@ -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;
+ sync?: Pick;
+ 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 {
+ 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;
+ }
+}
diff --git a/apps/backend/src/modules/billing/jobs/schedule.ts b/apps/backend/src/modules/billing/jobs/schedule.ts
new file mode 100644
index 0000000..5e9b60f
--- /dev/null
+++ b/apps/backend/src/modules/billing/jobs/schedule.ts
@@ -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();
+}
diff --git a/apps/backend/src/modules/billing/lib/config.ts b/apps/backend/src/modules/billing/lib/config.ts
new file mode 100644
index 0000000..4dbb7bd
--- /dev/null
+++ b/apps/backend/src/modules/billing/lib/config.ts
@@ -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 = 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 = process.env): number {
+ const value = Number(env.BILLING_GRACE_DAYS);
+ return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
+}
diff --git a/apps/backend/src/modules/billing/lib/entitlements.ts b/apps/backend/src/modules/billing/lib/entitlements.ts
new file mode 100644
index 0000000..ab8746d
--- /dev/null
+++ b/apps/backend/src/modules/billing/lib/entitlements.ts
@@ -0,0 +1,176 @@
+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;
+ 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 {
+ 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 } }),
+ // People, not memberships: someone in three groups is one student.
+ db.person.count({
+ where: { createdById: ownerId, attendees: { some: { status: 'ACTIVE' } } },
+ }),
+ ]);
+
+ const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
+ const 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> {
+ if (!this.enforced) return ok(undefined);
+ const entitlements = await this.getEntitlements(ownerId);
+ return entitlements.readOnly ? err(planReadOnlyProblem()) : ok(undefined);
+ }
+
+ async canCreateGroup(ownerId: string): Promise> {
+ 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> {
+ 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> {
+ return (await this.hasFeature(ownerId, feature))
+ ? ok(undefined)
+ : err(planFeatureRequiredProblem(feature));
+ }
+
+ async hasFeature(ownerId: string, feature: PlanFeature): Promise {
+ if (!this.enforced) return true;
+ const { limits } = await this.getEntitlements(ownerId);
+ return limits[feature];
+ }
+}
diff --git a/apps/backend/src/modules/billing/lib/helpers.ts b/apps/backend/src/modules/billing/lib/helpers.ts
new file mode 100644
index 0000000..e9baf89
--- /dev/null
+++ b/apps/backend/src/modules/billing/lib/helpers.ts
@@ -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;
diff --git a/apps/backend/src/modules/billing/lib/index.ts b/apps/backend/src/modules/billing/lib/index.ts
new file mode 100644
index 0000000..59f697a
--- /dev/null
+++ b/apps/backend/src/modules/billing/lib/index.ts
@@ -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';
diff --git a/apps/backend/src/modules/billing/lib/read-only-middleware.ts b/apps/backend/src/modules/billing/lib/read-only-middleware.ts
new file mode 100644
index 0000000..ddb84c0
--- /dev/null
+++ b/apps/backend/src/modules/billing/lib/read-only-middleware.ts
@@ -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 {
+ 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();
+ };
+}
diff --git a/apps/backend/src/modules/billing/lib/sync.ts b/apps/backend/src/modules/billing/lib/sync.ts
new file mode 100644
index 0000000..c4242c3
--- /dev/null
+++ b/apps/backend/src/modules/billing/lib/sync.ts
@@ -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;
+ providers?: BillingProviderResolver;
+ now?: () => Date;
+};
+
+export type SyncOutcome = { synced: boolean; status: SubscriptionStatus | null };
+
+export function subscriptionRefOf(
+ row: Pick,
+): 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> {
+ 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> {
+ 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 });
+ }
+}
diff --git a/apps/backend/src/modules/billing/providers/billing-provider.ts b/apps/backend/src/modules/billing/providers/billing-provider.ts
new file mode 100644
index 0000000..3b4eb39
--- /dev/null
+++ b/apps/backend/src/modules/billing/providers/billing-provider.ts
@@ -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//`. 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:` 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;
+ /** `null` while the professor has not completed the checkout. */
+ fetch(ref: SubscriptionRef): Promise;
+ listCharges(ref: SubscriptionRef & { externalId: string }): Promise;
+ /** Stops the monthly charge, or voids a checkout never completed. */
+ cancel(ref: SubscriptionRef): Promise
Gruperly
' + return ` -Gruperly
-${title}
-${body}
+${title}
+${body}
${button(url, 'Confirmar mail')}`, + ), + ) + } + + async sendStudentRecoveryLinks({ email, links }: StudentRecoveryEmailData) { + // A guardian may have one account per child with the same email: one button each. + const buttons = links + .map((link) => + links.length > 1 + ? `
${escapeHtml(link.name)}
${button(link.url, 'Ingresar')}` + : button(link.url, 'Ingresar'), + ) + .join('') + 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.
${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 ? `
Motivo: ${escapeHtml(reason)}` : ''}
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), + ) + } } -// Futuro: proveedores transaccionales (Resend, SendGrid, Postmark). -// Añadir implementaciones y alternar con EMAIL_PROVIDER. +// Future: transactional providers (Resend, SendGrid, Postmark). +// Add implementations and switch between them with EMAIL_PROVIDER. export function createEmailProvider(): EmailProvider { return new SMTPEmailProvider() } diff --git a/apps/backend/src/lib/file-type.ts b/apps/backend/src/lib/file-type.ts new file mode 100644 index 0000000..23bc7fa --- /dev/null +++ b/apps/backend/src/lib/file-type.ts @@ -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