diff --git a/.env.example b/.env.example
index 9ad1ad6..b97266e 100644
--- a/.env.example
+++ b/.env.example
@@ -46,6 +46,25 @@ BETTER_AUTH_SECRET=""
# MP_CLIENT_ID=""
# MP_CLIENT_SECRET=""
+# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
+# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
+# whatsapp_not_configured y el paso del onboarding es salteable.
+# WHATSAPP_PROVIDER="openwa" # openwa (MVP) | kapso
+# WHATSAPP_SEND_INTERVAL_MS="5000" # pausa entre envios del mismo profesor
+#
+# OpenWA (servicio `openwa` del compose).
+# OPENWA_IMAGE_TAG="0.25.0"
+# OPENWA_API_URL="http://openwa:2785/api"
+# OPENWA_API_KEY="" # key OPERATOR, sin allowedSessions
+# OPENWA_WEBHOOK_URL="http://api:4000/api/v1/whatsapp/webhooks/openwa"
+# OPENWA_WEBHOOK_SECRET="" # 16+ caracteres: openssl rand -hex 24
+#
+# Kapso (API oficial de WhatsApp Cloud).
+# KAPSO_API_KEY=""
+# KAPSO_CALLBACK_URL="https://app.gruperly.com/api/v1/whatsapp/callback"
+# KAPSO_WEBHOOK_URL="https://app.gruperly.com/api/v1/whatsapp/webhooks/kapso"
+# KAPSO_WEBHOOK_SECRET="" # el mismo del project webhook de Kapso
+
# Only if you want the API on another domain: it is baked into the Vite bundle
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
# origin (recommended).
diff --git a/AGENTS.md b/AGENTS.md
index 5889e28..cf5f925 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
- `src/logger.ts` — pino + pino-pretty.
- - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`.
+ - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`).
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
@@ -42,6 +42,18 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
+- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
+ 1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers//`.
+ 2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
+ 3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
+ 4. La idempotencia de los envíos es el `@@unique([kind, attendeeId, periodKey])` de `outbound_messages` (semana ISO): la fila se crea **antes** de llamar al proveedor y su id es el `Idempotency-Key`.
+ 5. Los teléfonos se guardan en formato nacional: el envío pasa por `toWhatsappE164` (shared) con el país del profesor.
+ 6. Sin SDK de Kapso (trae su propio zod): `fetch` plano.
+ 7. El sandbox de Kapso no soporta templates.
+ 8. La imagen de OpenWA va pineada (`OPENWA_IMAGE_TAG`). Su guard SSRF rechaza webhooks a hosts internos que no estén en `SSRF_ALLOWED_HOSTS`.
+ 9. Al cambiar `WHATSAPP_PROVIDER`, las cuentas del proveedor anterior quedan `requires_reconnect`.
+ 10. Nunca loguear API keys, secretos ni cuerpos de pedidos, que llevan teléfonos.
+ 11. En los tests, los proveedores se inyectan por constructor y `fetch` va en `deps`, sin `mock.module`.
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
diff --git a/README.md b/README.md
index 052e653..a383eaf 100644
--- a/README.md
+++ b/README.md
@@ -146,6 +146,34 @@ La moneda sale del país del profesor (`user.country`, elegido en el onboarding;
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 escanea un QR y 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).
@@ -168,6 +196,8 @@ El compose las interpola desde el entorno. En Dokploy van en la pestaña **Envir
| `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)). El compose levanta el servicio `openwa` en la red interna, con sus sesiones en el volumen `openwa-data` |
+| `OPENWA_IMAGE_TAG` | no | Versión pineada de OpenWA (default `0.25.0`) |
| `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 |
diff --git a/apps/backend/.env.example b/apps/backend/.env.example
index 4f23b9f..6666655 100644
--- a/apps/backend/.env.example
+++ b/apps/backend/.env.example
@@ -30,4 +30,28 @@ MP_CLIENT_SECRET=""
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=""
\ No newline at end of file
+TOKEN_ENCRYPTION_KEY=""
+
+# 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. En local: docker compose up openwa (o 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"
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/models/auth.prisma b/apps/backend/prisma/models/auth.prisma
index e139ab7..b038c60 100644
--- a/apps/backend/prisma/models/auth.prisma
+++ b/apps/backend/prisma/models/auth.prisma
@@ -20,6 +20,7 @@ model User {
orgInvitations Invitation[] @relation("InvitedBy")
waitlist WaitlistEntry[]
mpAccount MpAccount?
+ whatsappAccount WhatsappAccount?
@@map("users")
}
diff --git a/apps/backend/prisma/models/domain.prisma b/apps/backend/prisma/models/domain.prisma
index fc81ab9..beafc79 100644
--- a/apps/backend/prisma/models/domain.prisma
+++ b/apps/backend/prisma/models/domain.prisma
@@ -1,19 +1,22 @@
// Domain models
model Group {
- 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")
- 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")
+ 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, map: "groups_createdById_fkey")
members GroupMember[]
@@ -22,6 +25,7 @@ model Group {
waitlist GroupWaitlistEntry[]
preRegistrations GroupPreRegistration[]
classSessions ClassSession[]
+ outboundMessages OutboundMessage[]
@@map("groups")
}
@@ -81,33 +85,35 @@ model Attendee {
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")
- payments Payment[]
- attendances Attendance[]
- slotReleases SlotRelease[]
+ group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
+ payments Payment[]
+ attendances Attendance[]
+ slotReleases SlotRelease[]
+ outboundMessages OutboundMessage[]
@@index([groupId], map: "attendees_groupId_idx")
@@map("attendees")
}
model Payment {
- id String @id @default(cuid())
- groupId String @map("group_id")
- attendeeId String @map("attendee_id")
- amount Decimal @db.Decimal(10, 2)
- currency String @default("ARS")
- status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
- dueDate DateTime @map("due_date")
- description String? @map("description")
- checkoutUrl String? @map("checkout_url")
- mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
- mpPaymentId String? @map("mp_payment_id")
- paidAt DateTime? @map("paid_at")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @updatedAt @map("updated_at")
+ id String @id @default(cuid())
+ groupId String @map("group_id")
+ attendeeId String @map("attendee_id")
+ amount Decimal @db.Decimal(10, 2)
+ currency String @default("ARS")
+ status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
+ dueDate DateTime @map("due_date")
+ description String? @map("description")
+ checkoutUrl String? @map("checkout_url")
+ mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
+ mpPaymentId String? @map("mp_payment_id")
+ paidAt DateTime? @map("paid_at")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
- group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_fkey")
- attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
+ 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[]
@@index([groupId], map: "payments_groupId_idx")
@@index([attendeeId], map: "payments_attendeeId_idx")
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/src/app.ts b/apps/backend/src/app.ts
index 2d6bc7e..f39043f 100644
--- a/apps/backend/src/app.ts
+++ b/apps/backend/src/app.ts
@@ -25,6 +25,7 @@ import { mpRoutes } from './modules/mp';
import { onboardingRoutes } from './modules/onboarding';
import { paymentsRoutes } from './modules/payments';
import { waitlistRoutes } from './modules/waitlist';
+import { whatsappRoutes } from './modules/whatsapp';
const app = new Hono();
@@ -46,6 +47,7 @@ api.route('/groups', groupsRoutes);
api.route('/home', homeRoutes);
api.route('/onboarding', onboardingRoutes);
api.route('/mp', mpRoutes);
+api.route('/whatsapp', whatsappRoutes);
api.route('/attendees', attendeesRoutes);
api.route('/payments', paymentsRoutes);
api.route('/waitlist', waitlistRoutes);
diff --git a/apps/backend/src/http/problem-builders.ts b/apps/backend/src/http/problem-builders.ts
index 1c371e5..d70fba2 100644
--- a/apps/backend/src/http/problem-builders.ts
+++ b/apps/backend/src/http/problem-builders.ts
@@ -114,6 +114,42 @@ export function mpProviderErrorProblem(): ProblemDetails {
};
}
+/** 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',
+ });
+}
+
+/** 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.',
diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts
index f6549b7..5ea490e 100644
--- a/apps/backend/src/http/session-auth.ts
+++ b/apps/backend/src/http/session-auth.ts
@@ -34,6 +34,14 @@ export function isPublicApiRequest(method: string, path: string): boolean {
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;
+ }
return (
normalizedPath === '/api/v1/health'
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
index 29edc96..d964ba4 100644
--- 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
@@ -18,7 +18,7 @@ import {
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
type GetStudentsAtRiskDeps = {
- db?: AnalyticsAccessDb & Pick;
+ db?: AnalyticsAccessDb & StudentsAtRiskDb;
now?: Date;
};
@@ -37,72 +37,13 @@ export class GetStudentsAtRisk {
): 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 [windowSessions, attendees, attendances] = await Promise.all([
- db.classSession.findMany({
- where: { groupId, startsAt: { gte: since } },
- select: { id: true },
- }),
- db.attendee.findMany({
- where: { groupId, status: 'ACTIVE' },
- select: { id: true, fullName: true, phone: true },
- }),
- db.attendance.findMany({
- where: { attendee: { groupId } },
- select: {
- attendeeId: true,
- status: true,
- classSession: { select: { startsAt: true } },
- },
- orderBy: { classSession: { startsAt: 'desc' } },
- }),
- ]);
-
- const totalWindowSessions = windowSessions.length;
- const streamByAttendee = groupAttendanceByAttendee(attendances);
-
- const atRisk: StudentAtRisk[] = [];
- for (const attendee of attendees) {
- const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
- status: row.status,
- occurredAt: row.classSession.startsAt,
- }));
- const consecutiveAbsences = trailingAbsentStreak(stream);
- const attendedAt = lastAttendedAt(stream);
- const monthlyRate = monthlyAttendanceRate(
- stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
- totalWindowSessions,
- );
- const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
- if (!riskLevel) {
- continue;
- }
- atRisk.push({
- attendeeId: attendee.id,
- fullName: attendee.fullName,
- phone: attendee.phone,
- riskLevel,
- consecutiveAbsences,
- lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
- monthlyAttendanceRate: monthlyRate,
- });
- }
-
- atRisk.sort((a, b) => {
- if (a.riskLevel !== b.riskLevel) {
- return a.riskLevel === 'HIGH' ? -1 : 1;
- }
- if (a.consecutiveAbsences !== b.consecutiveAbsences) {
- return b.consecutiveAbsences - a.consecutiveAbsences;
- }
- return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
- });
+ const atRisk = await findStudentsAtRisk(db, groupId, now);
return ok({
groupName: access.value.name,
@@ -111,6 +52,83 @@ export class GetStudentsAtRisk {
}
}
+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, so both
+ * agree 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 },
+ }),
+ db.attendee.findMany({
+ where: { groupId, status: 'ACTIVE' },
+ select: { id: true, fullName: true, phone: true },
+ }),
+ db.attendance.findMany({
+ where: { attendee: { groupId } },
+ select: {
+ attendeeId: true,
+ status: true,
+ classSession: { select: { startsAt: true } },
+ },
+ orderBy: { classSession: { startsAt: 'desc' } },
+ }),
+ ]);
+
+ const totalWindowSessions = windowSessions.length;
+ const streamByAttendee = groupAttendanceByAttendee(attendances);
+
+ const atRisk: StudentAtRisk[] = [];
+ for (const attendee of attendees) {
+ const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
+ status: row.status,
+ occurredAt: row.classSession.startsAt,
+ }));
+ const consecutiveAbsences = trailingAbsentStreak(stream);
+ const attendedAt = lastAttendedAt(stream);
+ const monthlyRate = monthlyAttendanceRate(
+ stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
+ totalWindowSessions,
+ );
+ const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
+ if (!riskLevel) {
+ continue;
+ }
+ atRisk.push({
+ attendeeId: attendee.id,
+ fullName: attendee.fullName,
+ phone: attendee.phone,
+ riskLevel,
+ consecutiveAbsences,
+ lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
+ monthlyAttendanceRate: monthlyRate,
+ });
+ }
+
+ atRisk.sort((a, b) => {
+ if (a.riskLevel !== b.riskLevel) {
+ return a.riskLevel === 'HIGH' ? -1 : 1;
+ }
+ if (a.consecutiveAbsences !== b.consecutiveAbsences) {
+ return b.consecutiveAbsences - a.consecutiveAbsences;
+ }
+ return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
+ });
+
+ return atRisk;
+}
+
function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map {
const byAttendee = new Map();
for (const row of rows) {
diff --git a/apps/backend/src/modules/groups/lib/helpers.ts b/apps/backend/src/modules/groups/lib/helpers.ts
index f2efc8f..71532f6 100644
--- a/apps/backend/src/modules/groups/lib/helpers.ts
+++ b/apps/backend/src/modules/groups/lib/helpers.ts
@@ -19,6 +19,8 @@ export type GroupRecord = {
billingType: BillingType | null;
dueDay: number | null;
inviteToken?: string | null;
+ autoPaymentReminders?: boolean;
+ autoReengagement?: boolean;
};
/* The listing adds the occupancy counters to each group so the card can show
@@ -44,6 +46,8 @@ export function toGroupDto(record: GroupRecord): GroupDto {
billingType: record.billingType,
dueDay: record.dueDay,
inviteToken: record.inviteToken ?? null,
+ autoPaymentReminders: record.autoPaymentReminders ?? false,
+ autoReengagement: record.autoReengagement ?? false,
};
}
diff --git a/apps/backend/src/modules/groups/routes.ts b/apps/backend/src/modules/groups/routes.ts
index b3418dd..13f4801 100644
--- a/apps/backend/src/modules/groups/routes.ts
+++ b/apps/backend/src/modules/groups/routes.ts
@@ -10,6 +10,7 @@ import updateAttendeeRoute from '../attendees/features/update/route';
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
import groupWaitlistRoutes from '../group-waitlist/routes';
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
+import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route';
import createGroupRoute from './features/create/route';
import getAllRoute from './features/get-all/route';
import getByIdRoute from './features/get-by-id/route';
@@ -26,6 +27,7 @@ routes.route('/', createAttendeeRoute);
routes.route('/', bulkCreateAttendeesRoute);
routes.route('/', getByIdRoute);
routes.route('/', createPaymentsBatchRoute);
+routes.route('/', updateGroupAutomationsRoute);
routes.route('/', addToGroupWaitlistRoute);
routes.route('/', groupWaitlistRoutes);
routes.route('/', groupPreRegistrationRoutes);
diff --git a/apps/backend/src/modules/onboarding/features/status/use-case.ts b/apps/backend/src/modules/onboarding/features/status/use-case.ts
index 492a653..5e92e91 100644
--- a/apps/backend/src/modules/onboarding/features/status/use-case.ts
+++ b/apps/backend/src/modules/onboarding/features/status/use-case.ts
@@ -3,8 +3,11 @@ import type { OnboardingStatusDto, ProblemDetails, Result } from '@gruperly/shar
import { err, ok } from '@gruperly/shared';
import { problemDetails } from '@/http/problem-details';
import prisma from '@/lib/prisma';
+import { isWhatsappAccountUsable } from '@/modules/whatsapp/lib/account';
-type GetOnboardingStatusDeps = { db?: Pick };
+type GetOnboardingStatusDeps = {
+ db?: Pick;
+};
export class GetOnboardingStatus {
constructor(private readonly deps: GetOnboardingStatusDeps = {}) {}
@@ -24,8 +27,11 @@ export class GetOnboardingStatus {
);
}
+ const whatsappAccount = await db.whatsappAccount.findUnique({ where: { ownerId: userId } });
+ const whatsappConnected = isWhatsappAccountUsable(whatsappAccount);
+
if (user.onboardingCompleted) {
- return ok({ step: 'COMPLETED', paymentConnected: true, completed: true });
+ return ok({ step: 'COMPLETED', paymentConnected: true, whatsappConnected, completed: true });
}
// Linking Mercado Pago is optional, so `paymentConnected` here only resumes
@@ -33,9 +39,14 @@ export class GetOnboardingStatus {
// need to see the "Cobros" step again. A `revoked` row is not usable.
const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } });
if (mpAccount && mpAccount.status === 'ACTIVE') {
- return ok({ step: 'PAYMENT_CONNECTED', paymentConnected: true, completed: false });
+ return ok({
+ step: 'PAYMENT_CONNECTED',
+ paymentConnected: true,
+ whatsappConnected,
+ completed: false,
+ });
}
- return ok({ step: 'NOT_STARTED', paymentConnected: false, completed: false });
+ return ok({ step: 'NOT_STARTED', paymentConnected: false, whatsappConnected, completed: false });
}
}
\ No newline at end of file
diff --git a/apps/backend/src/modules/onboarding/lib/helpers.ts b/apps/backend/src/modules/onboarding/lib/helpers.ts
index e12b447..72a2ffb 100644
--- a/apps/backend/src/modules/onboarding/lib/helpers.ts
+++ b/apps/backend/src/modules/onboarding/lib/helpers.ts
@@ -15,6 +15,8 @@ export type OnboardingGroupRecord = {
price: PriceLike | number | null;
billingType: BillingType | null;
dueDay: number | null;
+ autoPaymentReminders?: boolean;
+ autoReengagement?: boolean;
};
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
@@ -31,5 +33,7 @@ export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingG
price: record.price == null ? null : Number(record.price.toString()),
billingType: record.billingType,
dueDay: record.dueDay,
+ autoPaymentReminders: record.autoPaymentReminders ?? false,
+ autoReengagement: record.autoReengagement ?? false,
};
}
\ No newline at end of file
diff --git a/apps/backend/src/modules/whatsapp/features/callback/route.ts b/apps/backend/src/modules/whatsapp/features/callback/route.ts
new file mode 100644
index 0000000..419d9d4
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/callback/route.ts
@@ -0,0 +1,33 @@
+import type { WhatsappCallbackQuery } from '@gruperly/shared';
+import { WhatsappCallbackQuerySchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { validate } from '@/http/validate';
+import { logger } from '@/logger';
+import { getWebOrigin } from '@/modules/mp/lib';
+import { buildWhatsappReturnUrl, CompleteWhatsappSetup } from './use-case';
+
+/**
+ * The browser arrives here from the provider's hosted linking (Kapso), so this
+ * route always redirects back to the app and never returns a problem body.
+ */
+const route = new Hono();
+
+route.get('/', validate.query(WhatsappCallbackQuerySchema), async (c) => {
+ const query = c.req.valid('query') as WhatsappCallbackQuery;
+
+ const user = c.get('user');
+ if (!user) {
+ // Without a session there is nobody to credit the number to.
+ logger.warn('WhatsApp setup callback arrived without a session');
+ return c.redirect(new URL('/login', getWebOrigin()).toString());
+ }
+
+ const outcome = await new CompleteWhatsappSetup().execute(user.id, query);
+ if (outcome.kind === 'error') {
+ logger.warn({ reason: outcome.reason }, 'WhatsApp setup callback failed');
+ }
+
+ return c.redirect(buildWhatsappReturnUrl(getWebOrigin(), query.returnTo, outcome));
+});
+
+export default route;
diff --git a/apps/backend/src/modules/whatsapp/features/callback/use-case.ts b/apps/backend/src/modules/whatsapp/features/callback/use-case.ts
new file mode 100644
index 0000000..6573fb6
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/callback/use-case.ts
@@ -0,0 +1,70 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { WhatsappCallbackReason, WhatsappReturnTo } from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { activateWhatsappAccount } from '../../lib/activate-account';
+import { getMessagingProvider } from '../../providers';
+import type { MessagingProvider } from '../../providers/messaging-provider';
+
+type CompleteWhatsappSetupDeps = {
+ db?: Pick;
+ provider?: MessagingProvider;
+ now?: () => Date;
+};
+
+export type WhatsappCallbackOutcome =
+ | { kind: 'success' }
+ | { kind: 'error'; reason: WhatsappCallbackReason };
+
+/**
+ * Finishes a redirect-based linking (Kapso's setup link). Never fails as a
+ * `Result`: whatever happens, the browser is sent back to the app with an
+ * outcome it can show.
+ */
+export class CompleteWhatsappSetup {
+ constructor(private readonly deps: CompleteWhatsappSetupDeps = {}) {}
+
+ async execute(
+ ownerId: string,
+ query: Record,
+ ): Promise {
+ const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
+ if (!providerResult.ok) return failure('provider_error');
+ const provider = providerResult.value;
+ if (!provider.completeRedirect) return failure('invalid_setup');
+
+ const db = this.deps.db ?? prisma;
+ const account = await db.whatsappAccount.findUnique({ where: { ownerId } });
+ if (!account || account.provider !== provider.id) return failure('invalid_setup');
+
+ const completed = await provider.completeRedirect(account, query);
+ if (!completed.ok) return failure(completed.error);
+
+ const activated = await activateWhatsappAccount(
+ db,
+ provider,
+ account,
+ completed.value,
+ this.deps.now?.() ?? new Date(),
+ );
+ return activated.ok ? { kind: 'success' } : failure('number_in_use');
+ }
+}
+
+function failure(reason: WhatsappCallbackReason): WhatsappCallbackOutcome {
+ return { kind: 'error', reason };
+}
+
+/**
+ * Where the callback sends the teacher back to. `returnTo` comes from the
+ * validated enum, so this cannot become an open redirect.
+ */
+export function buildWhatsappReturnUrl(
+ webUrl: string,
+ returnTo: WhatsappReturnTo,
+ outcome: WhatsappCallbackOutcome,
+): string {
+ const url = new URL(`/${returnTo}`, webUrl);
+ url.searchParams.set('wa', outcome.kind);
+ if (outcome.kind === 'error') url.searchParams.set('reason', outcome.reason);
+ return url.toString();
+}
diff --git a/apps/backend/src/modules/whatsapp/features/connect/route.ts b/apps/backend/src/modules/whatsapp/features/connect/route.ts
new file mode 100644
index 0000000..d83693c
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/connect/route.ts
@@ -0,0 +1,21 @@
+import type { WhatsappConnect } from '@gruperly/shared';
+import { WhatsappConnectSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { StartWhatsappConnection } from './use-case';
+
+const route = new Hono();
+
+route.post('/', validate.json(WhatsappConnectSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
+
+ const { returnTo } = c.req.valid('json') as WhatsappConnect;
+
+ const useCase = new StartWhatsappConnection();
+ const result = await useCase.execute({ id: user.id, name: user.name }, returnTo);
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/whatsapp/features/connect/use-case.ts b/apps/backend/src/modules/whatsapp/features/connect/use-case.ts
new file mode 100644
index 0000000..fddece2
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/connect/use-case.ts
@@ -0,0 +1,63 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ ProblemDetails,
+ Result,
+ WhatsappConnectResultDto,
+ WhatsappReturnTo,
+} from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { getMessagingProvider } from '../../providers';
+import type { MessagingProvider } from '../../providers/messaging-provider';
+
+type StartWhatsappConnectionDeps = {
+ db?: Pick;
+ provider?: MessagingProvider;
+};
+
+/**
+ * Starts linking the teacher's WhatsApp with the active provider. The answer
+ * tells the browser how to continue: show a QR code or navigate away.
+ *
+ * Linking again (another number, another provider) reuses the same row: the
+ * account goes back to PENDING until the provider confirms the new link.
+ */
+export class StartWhatsappConnection {
+ constructor(private readonly deps: StartWhatsappConnectionDeps = {}) {}
+
+ async execute(
+ owner: { id: string; name: string },
+ returnTo: WhatsappReturnTo,
+ ): Promise> {
+ const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider();
+ if (!providerResult.ok) return providerResult;
+ const provider = providerResult.value;
+
+ const db = this.deps.db ?? prisma;
+ const account = await db.whatsappAccount.findUnique({ where: { ownerId: owner.id } });
+
+ const started = await provider.startConnection({
+ ownerId: owner.id,
+ ownerName: owner.name,
+ returnTo,
+ account,
+ });
+ if (!started.ok) return err(started.error);
+
+ const data = {
+ provider: provider.id,
+ status: 'PENDING' as const,
+ externalId: started.value.externalId,
+ displayPhoneNumber: null,
+ providerData: started.value.providerData ?? undefined,
+ connectedAt: null,
+ };
+ await db.whatsappAccount.upsert({
+ where: { ownerId: owner.id },
+ create: { ownerId: owner.id, ...data },
+ update: data,
+ });
+
+ return ok({ start: started.value.start });
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/features/disconnect/route.ts b/apps/backend/src/modules/whatsapp/features/disconnect/route.ts
new file mode 100644
index 0000000..760565a
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/disconnect/route.ts
@@ -0,0 +1,16 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { DisconnectWhatsapp } from './use-case';
+
+const route = new Hono();
+
+route.delete('/', async (c) => {
+ const user = c.get('user');
+ if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
+
+ const useCase = new DisconnectWhatsapp();
+ const result = await useCase.execute(user.id);
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/whatsapp/features/disconnect/use-case.ts b/apps/backend/src/modules/whatsapp/features/disconnect/use-case.ts
new file mode 100644
index 0000000..b161de4
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/disconnect/use-case.ts
@@ -0,0 +1,53 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { ProblemDetails, Result, WhatsappDisconnectResultDto } from '@gruperly/shared';
+import { ok } from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { logger } from '@/logger';
+import { getMessagingProvider } from '../../providers';
+import type { MessagingProvider } from '../../providers/messaging-provider';
+
+type DisconnectWhatsappDeps = {
+ db?: Pick;
+ /** The provider the account was linked with; defaults to building it from the env. */
+ provider?: MessagingProvider;
+};
+
+/**
+ * Unlinks the teacher's WhatsApp. The provider side is best effort (OpenWA logs
+ * the device out of the phone; Kapso keeps the number at Meta); locally the row
+ * is kept as DISCONNECTED with no number, so it frees the number for a relink
+ * while keeping provider references (the Kapso customer) for next time.
+ */
+export class DisconnectWhatsapp {
+ constructor(private readonly deps: DisconnectWhatsappDeps = {}) {}
+
+ async execute(ownerId: string): Promise> {
+ const db = this.deps.db ?? prisma;
+
+ const account = await db.whatsappAccount.findUnique({ where: { ownerId } });
+ if (!account || account.status === 'DISCONNECTED') {
+ return ok({ disconnected: false });
+ }
+
+ const provider = this.deps.provider ?? resolveProvider(account.provider);
+ if (provider) {
+ const result = await provider.disconnect(account);
+ if (!result.ok) {
+ logger.warn({ code: result.error.code }, 'WhatsApp provider-side disconnect failed');
+ }
+ }
+
+ await db.whatsappAccount.update({
+ where: { id: account.id },
+ data: { status: 'DISCONNECTED', externalId: null, displayPhoneNumber: null, connectedAt: null },
+ });
+
+ return ok({ disconnected: true });
+ }
+}
+
+/** The adapter the row was linked with, if this deployment can still build it. */
+function resolveProvider(id: 'OPENWA' | 'KAPSO'): MessagingProvider | null {
+ const result = getMessagingProvider(id);
+ return result.ok ? result.value : null;
+}
diff --git a/apps/backend/src/modules/whatsapp/features/status/route.ts b/apps/backend/src/modules/whatsapp/features/status/route.ts
new file mode 100644
index 0000000..f090857
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/status/route.ts
@@ -0,0 +1,16 @@
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { GetWhatsappStatus } 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 GetWhatsappStatus();
+ const result = await useCase.execute(user.id);
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/whatsapp/features/status/use-case.ts b/apps/backend/src/modules/whatsapp/features/status/use-case.ts
new file mode 100644
index 0000000..7d392e2
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/status/use-case.ts
@@ -0,0 +1,105 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ ProblemDetails,
+ Result,
+ WhatsappReadiness,
+ WhatsappStatusDto,
+} from '@gruperly/shared';
+import { ok } from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { toVisibleWhatsappStatus } from '../../lib/account';
+import { activateWhatsappAccount } from '../../lib/activate-account';
+import { getMessagingProvider } from '../../providers';
+import type { MessagingProvider, WhatsappAccountRecord } from '../../providers/messaging-provider';
+
+type GetWhatsappStatusDeps = {
+ db?: Pick;
+ provider?: MessagingProvider;
+ now?: () => Date;
+};
+
+const BLOCKED: WhatsappStatusDto['readiness'] = {
+ PAYMENT_REMINDER: 'blocked',
+ REENGAGEMENT: 'blocked',
+};
+
+/**
+ * The teacher's WhatsApp, for Settings, the onboarding step and the group
+ * automations card.
+ *
+ * While a linking is PENDING this also asks the provider how it is going, so a
+ * QR linking completes (and the QR refreshes) by polling this endpoint alone,
+ * even where the provider's webhook cannot reach us (local development).
+ */
+export class GetWhatsappStatus {
+ constructor(private readonly deps: GetWhatsappStatusDeps = {}) {}
+
+ async execute(ownerId: string): Promise> {
+ const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider();
+ if (!providerResult.ok) return providerResult;
+ const provider = providerResult.value;
+
+ const db = this.deps.db ?? prisma;
+ let account: WhatsappAccountRecord | null = await db.whatsappAccount.findUnique({
+ where: { ownerId },
+ });
+
+ if (!account) {
+ return ok(dto(provider, null, null, BLOCKED));
+ }
+
+ let qrCode: string | null = null;
+ if (account.provider === provider.id && account.status === 'PENDING') {
+ const snapshot = await provider.refreshConnection(account);
+ if (snapshot.ok) {
+ const live = snapshot.value;
+ if (live.state === 'pending') {
+ qrCode = live.qrCode;
+ } else if (live.state === 'active') {
+ const activated = await activateWhatsappAccount(
+ db,
+ provider,
+ account,
+ { displayPhoneNumber: live.displayPhoneNumber },
+ this.deps.now?.() ?? new Date(),
+ );
+ if (activated.ok) account = activated.account;
+ } else {
+ account = await db.whatsappAccount.update({
+ where: { id: account.id },
+ data: { status: 'DISCONNECTED' },
+ });
+ }
+ }
+ // A failed lookup is not an answer: report what we have and let the next
+ // poll try again.
+ }
+
+ const readiness =
+ toVisibleWhatsappStatus(account, provider.id) === 'active'
+ ? {
+ PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'),
+ REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'),
+ }
+ : BLOCKED;
+
+ return ok(dto(provider, account, qrCode, readiness));
+ }
+}
+
+function dto(
+ provider: MessagingProvider,
+ account: WhatsappAccountRecord & { connectedAt?: Date | null } | null,
+ qrCode: string | null,
+ readiness: Record<'PAYMENT_REMINDER' | 'REENGAGEMENT', WhatsappReadiness>,
+): WhatsappStatusDto {
+ const status = toVisibleWhatsappStatus(account, provider.id);
+ return {
+ status,
+ provider: provider.id,
+ displayPhoneNumber: status === 'active' ? (account?.displayPhoneNumber ?? null) : null,
+ connectedAt: status === 'active' ? (account?.connectedAt?.toISOString() ?? null) : null,
+ qrCode,
+ readiness,
+ };
+}
diff --git a/apps/backend/src/modules/whatsapp/features/update-automations/route.ts b/apps/backend/src/modules/whatsapp/features/update-automations/route.ts
new file mode 100644
index 0000000..e93c375
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/update-automations/route.ts
@@ -0,0 +1,21 @@
+import type { UpdateGroupAutomations } from '@gruperly/shared';
+import { UpdateGroupAutomationsSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { UpdateGroupAutomationsUseCase } from './use-case';
+
+/** Mounted from `modules/groups/routes.ts`: `PATCH /groups/:groupId/automations`. */
+const route = new Hono();
+
+route.patch('/:groupId/automations', validate.json(UpdateGroupAutomationsSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
+
+ const input = c.req.valid('json') as UpdateGroupAutomations;
+ const useCase = new UpdateGroupAutomationsUseCase();
+ const result = await useCase.execute(c.req.param('groupId'), user.id, input);
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts b/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts
new file mode 100644
index 0000000..cd5a18a
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/update-automations/use-case.ts
@@ -0,0 +1,58 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ GroupAutomationsDto,
+ ProblemDetails,
+ Result,
+ UpdateGroupAutomations,
+} from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders';
+import prisma from '@/lib/prisma';
+
+type UpdateGroupAutomationsDeps = { db?: Pick };
+
+/**
+ * Turns the group's weekly WhatsApp automations on or off. Only the owner can:
+ * the messages go out from their own WhatsApp.
+ *
+ * Turning one on does not require a linked WhatsApp. The weekly job skips
+ * groups whose owner has nothing usable, and the UI explains why.
+ */
+export class UpdateGroupAutomationsUseCase {
+ constructor(private readonly deps: UpdateGroupAutomationsDeps = {}) {}
+
+ async execute(
+ groupId: string,
+ userId: string,
+ input: UpdateGroupAutomations,
+ ): Promise> {
+ const db = this.deps.db ?? prisma;
+
+ const group = await db.group.findUnique({
+ where: { id: groupId },
+ select: { id: true, createdById: true },
+ });
+ if (!group) return err(notFoundResourceProblem('Group', groupId));
+ if (group.createdById !== userId) {
+ return err(
+ forbiddenProblem({
+ detail: 'Solo quien creó el grupo puede cambiar sus automatizaciones.',
+ code: 'group_owner_required',
+ }),
+ );
+ }
+
+ const updated = await db.group.update({
+ where: { id: groupId },
+ data: {
+ ...(input.autoPaymentReminders !== undefined
+ ? { autoPaymentReminders: input.autoPaymentReminders }
+ : {}),
+ ...(input.autoReengagement !== undefined ? { autoReengagement: input.autoReengagement } : {}),
+ },
+ select: { autoPaymentReminders: true, autoReengagement: true },
+ });
+
+ return ok(updated);
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/features/webhook/route.ts b/apps/backend/src/modules/whatsapp/features/webhook/route.ts
new file mode 100644
index 0000000..de15643
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/webhook/route.ts
@@ -0,0 +1,32 @@
+import { Hono } from 'hono';
+import { logger } from '@/logger';
+import type { MessagingProviderId } from '../../providers/messaging-provider';
+import { HandleWhatsappWebhook } from './use-case';
+
+const PROVIDERS: Record = { openwa: 'OPENWA', kapso: 'KAPSO' };
+
+/**
+ * Public endpoint (see `isPublicApiRequest`): the provider calls it, not the
+ * browser, so there is no session. Authenticity comes from the HMAC signature,
+ * checked over the raw body before anything is parsed. Answers fast: Kapso
+ * retries a delivery that is not acknowledged within 10 seconds.
+ */
+const route = new Hono();
+
+route.post('/:provider', async (c) => {
+ const providerId = PROVIDERS[c.req.param('provider')];
+ if (!providerId) return c.body(null, 404);
+
+ const rawBody = await c.req.text();
+ const result = await new HandleWhatsappWebhook().execute(providerId, rawBody, c.req.raw.headers);
+
+ if (!result.ok) {
+ logger.warn({ provider: providerId, reason: result.error }, 'WhatsApp webhook rejected');
+ const status = result.error === 'invalid_signature' ? 401 : result.error === 'not_configured' ? 503 : 400;
+ return c.body(null, status);
+ }
+
+ return c.json({ received: true, duplicate: result.value.duplicate });
+});
+
+export default route;
diff --git a/apps/backend/src/modules/whatsapp/features/webhook/use-case.ts b/apps/backend/src/modules/whatsapp/features/webhook/use-case.ts
new file mode 100644
index 0000000..b173a11
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/webhook/use-case.ts
@@ -0,0 +1,138 @@
+import type { OutboundMessageStatus, PrismaClient } from '@generated/prisma/client';
+import type { Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import prisma from '@/lib/prisma';
+import { logger } from '@/logger';
+import { activateWhatsappAccount } from '../../lib/activate-account';
+import { getMessagingProvider } from '../../providers';
+import type {
+ MessageDeliveryStatus,
+ MessagingProvider,
+ MessagingProviderId,
+ NormalizedEvent,
+} from '../../providers/messaging-provider';
+
+type HandleWhatsappWebhookDeps = {
+ db?: Pick;
+ provider?: MessagingProvider;
+ now?: () => Date;
+};
+
+export type WebhookFailure = 'not_configured' | 'invalid_signature' | 'invalid_payload';
+
+/** Prisma's unique-constraint violation: this delivery was already processed. */
+const UNIQUE_VIOLATION = 'P2002';
+
+/**
+ * States a message may move to from each state. Receipts can arrive out of
+ * order (a `read` before its `delivered`), so a late one never moves it back.
+ */
+const ADVANCES_FROM: Record = {
+ SENT: ['QUEUED'],
+ DELIVERED: ['QUEUED', 'SENT'],
+ READ: ['QUEUED', 'SENT', 'DELIVERED'],
+ FAILED: ['QUEUED', 'SENT', 'DELIVERED'],
+};
+
+/**
+ * Applies one provider webhook delivery: verify, dedupe, then reduce to the two
+ * things we track (the account's link and each message's delivery status).
+ */
+export class HandleWhatsappWebhook {
+ constructor(private readonly deps: HandleWhatsappWebhookDeps = {}) {}
+
+ async execute(
+ providerId: MessagingProviderId,
+ rawBody: string,
+ headers: Headers,
+ ): Promise> {
+ const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider(providerId);
+ if (!providerResult.ok) return err('not_configured');
+ const provider = providerResult.value;
+
+ const parsed = provider.parseWebhook(rawBody, headers);
+ if (!parsed.ok) return err(parsed.error);
+
+ const db = this.deps.db ?? prisma;
+ const dedupe = { provider: provider.id, dedupeKey: parsed.value.dedupeKey };
+
+ try {
+ await db.whatsappWebhookEvent.create({ data: dedupe });
+ } catch (error) {
+ if ((error as { code?: string }).code === UNIQUE_VIOLATION) {
+ return ok({ duplicate: true, applied: 0 });
+ }
+ throw error;
+ }
+
+ try {
+ let applied = 0;
+ for (const event of parsed.value.events) {
+ applied += (await this.apply(db, provider, event)) ? 1 : 0;
+ }
+ return ok({ duplicate: false, applied });
+ } catch (error) {
+ // Un-burn the key so the provider's retry gets another chance.
+ await db.whatsappWebhookEvent
+ .delete({ where: { provider_dedupeKey: dedupe } })
+ .catch(() => undefined);
+ throw error;
+ }
+ }
+
+ private async apply(
+ db: NonNullable,
+ provider: MessagingProvider,
+ event: NormalizedEvent,
+ ): Promise {
+ if (event.type === 'message_status') {
+ const result = await db.outboundMessage.updateMany({
+ where: {
+ provider: provider.id,
+ providerMessageId: event.providerMessageId,
+ status: { in: ADVANCES_FROM[event.status] },
+ },
+ data: {
+ status: event.status,
+ ...(event.status === 'FAILED'
+ ? { errorCode: event.errorCode ?? 'delivery_failed', errorMessage: event.errorMessage ?? null }
+ : {}),
+ },
+ });
+ return result.count > 0;
+ }
+
+ const account =
+ (await db.whatsappAccount.findFirst({
+ where: { provider: provider.id, externalId: event.externalId },
+ })) ??
+ (event.ownerId
+ ? await db.whatsappAccount.findFirst({
+ where: { provider: provider.id, ownerId: event.ownerId, status: { not: 'DISCONNECTED' } },
+ })
+ : null);
+ if (!account) return false;
+
+ if (event.status === 'disconnected') {
+ if (account.status === 'DISCONNECTED') return false;
+ await db.whatsappAccount.update({ where: { id: account.id }, data: { status: 'DISCONNECTED' } });
+ return true;
+ }
+
+ const activated = await activateWhatsappAccount(
+ db,
+ provider,
+ account,
+ {
+ externalId: event.externalId,
+ displayPhoneNumber: event.displayPhoneNumber,
+ providerData: event.providerData,
+ },
+ this.deps.now?.() ?? new Date(),
+ );
+ if (!activated.ok) {
+ logger.warn({ provider: provider.id }, 'WhatsApp number already linked to another teacher');
+ }
+ return activated.ok;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/index.ts b/apps/backend/src/modules/whatsapp/index.ts
new file mode 100644
index 0000000..9218ac9
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/index.ts
@@ -0,0 +1,2 @@
+export { startWhatsappJobs } from './jobs';
+export { default as whatsappRoutes } from './routes';
diff --git a/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts b/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts
new file mode 100644
index 0000000..acf7634
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts
@@ -0,0 +1,59 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared';
+import { countryCodeSchema } from '@gruperly/shared';
+import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider';
+
+export type EligibleGroup = { id: string; name: string };
+
+export type EligibleAccount = {
+ account: WhatsappAccountRecord;
+ country: CountryCode | null;
+ groups: EligibleGroup[];
+};
+
+type AutomationFlag = 'autoPaymentReminders' | 'autoReengagement';
+
+/**
+ * Groups with the automation on, bundled by owner, keeping only owners whose
+ * WhatsApp is linked with the active provider and ready to send this kind of
+ * message (for Kapso: the template is approved).
+ */
+export async function findEligibleAccounts(
+ db: Pick,
+ provider: MessagingProvider,
+ flag: AutomationFlag,
+ kind: WhatsappMessageKind,
+): Promise {
+ const groups = await db.group.findMany({
+ where: {
+ [flag]: true,
+ owner: { whatsappAccount: { is: { provider: provider.id, status: 'ACTIVE' } } },
+ },
+ select: {
+ id: true,
+ name: true,
+ createdById: true,
+ owner: { select: { country: true, whatsappAccount: true } },
+ },
+ orderBy: { createdAt: 'asc' },
+ });
+
+ const byOwner = new Map();
+ for (const group of groups) {
+ const account = group.owner.whatsappAccount;
+ if (!account) continue;
+ let entry = byOwner.get(group.createdById);
+ if (!entry) {
+ const country = countryCodeSchema.safeParse(group.owner.country);
+ entry = { account, country: country.success ? country.data : null, groups: [] };
+ byOwner.set(group.createdById, entry);
+ }
+ entry.groups.push({ id: group.id, name: group.name });
+ }
+
+ const eligible: EligibleAccount[] = [];
+ for (const entry of byOwner.values()) {
+ if ((await provider.readiness(entry.account, kind)) === 'ready') eligible.push(entry);
+ }
+ return eligible;
+}
diff --git a/apps/backend/src/modules/whatsapp/jobs/index.ts b/apps/backend/src/modules/whatsapp/jobs/index.ts
new file mode 100644
index 0000000..a85cdef
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/jobs/index.ts
@@ -0,0 +1,4 @@
+export { startWhatsappJobs } from './schedule';
+export { SendPaymentReminders } from './send-payment-reminders';
+export { SendReengagementMessages } from './send-reengagement-messages';
+export { SyncKapsoTemplates } from './sync-kapso-templates';
diff --git a/apps/backend/src/modules/whatsapp/jobs/schedule.ts b/apps/backend/src/modules/whatsapp/jobs/schedule.ts
new file mode 100644
index 0000000..d96f387
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/jobs/schedule.ts
@@ -0,0 +1,63 @@
+import { logger } from '@/logger';
+import { getActiveProviderId } from '../providers';
+import { SendPaymentReminders } from './send-payment-reminders';
+import { SendReengagementMessages } from './send-reengagement-messages';
+import { SyncKapsoTemplates } from './sync-kapso-templates';
+
+/** Mondays 13:00 UTC = 10:00 in Argentina (UTC-3, no DST). */
+export const WEEKLY_MESSAGES_CRON = '0 13 * * 1';
+const TEMPLATE_SYNC_CRON = '*/30 * * * *';
+
+/**
+ * Registers the WhatsApp jobs. Called once from `server.ts`, with the same
+ * guards as `startMpJobs`: Bun's cron turns a rejected promise into an
+ * unhandledRejection (which exits the process), and `unref` keeps the jobs from
+ * holding the process alive.
+ *
+ * Reminders run before re-engagement: if the gateway rate limits the account
+ * halfway, the message about money is the one that already went out.
+ */
+export function startWhatsappJobs(): void {
+ Bun.cron(
+ WEEKLY_MESSAGES_CRON,
+ async () => {
+ try {
+ const reminders = await new SendPaymentReminders().execute();
+ logger.info(reminders, 'WhatsApp payment reminders finished');
+ } catch (error) {
+ logger.error({ err: error }, 'WhatsApp payment reminders failed');
+ }
+ try {
+ const reengagement = await new SendReengagementMessages().execute();
+ logger.info(reengagement, 'WhatsApp re-engagement messages finished');
+ } catch (error) {
+ logger.error({ err: error }, 'WhatsApp re-engagement messages failed');
+ }
+ },
+ { tz: 'UTC' },
+ ).unref();
+
+ if (activeProviderIs('KAPSO')) {
+ Bun.cron(
+ TEMPLATE_SYNC_CRON,
+ async () => {
+ try {
+ const totals = await new SyncKapsoTemplates().execute();
+ if (totals.checked > 0) logger.info(totals, 'Kapso template sync finished');
+ } catch (error) {
+ logger.error({ err: error }, 'Kapso template sync failed');
+ }
+ },
+ { tz: 'UTC' },
+ ).unref();
+ }
+}
+
+function activeProviderIs(id: 'OPENWA' | 'KAPSO'): boolean {
+ try {
+ return getActiveProviderId() === id;
+ } catch (error) {
+ logger.error({ err: error }, 'Invalid WHATSAPP_PROVIDER');
+ return false;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts
new file mode 100644
index 0000000..2e01bce
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts
@@ -0,0 +1,113 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import prisma from '@/lib/prisma';
+import { logger } from '@/logger';
+import {
+ addTotals,
+ type DispatchItem,
+ type DispatchTotals,
+ dispatchForAccount,
+ emptyTotals,
+ sendIntervalFromEnv,
+ sleep,
+} from '../lib/dispatch';
+import { formatAmount, formatDueDate } from '../lib/format';
+import { getMessagingProvider } from '../providers';
+import type { MessagingProvider } from '../providers/messaging-provider';
+import { findEligibleAccounts } from './eligible-accounts';
+
+/** Only charges that are due within the coming week (or already overdue). */
+const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000;
+
+type SendPaymentRemindersDeps = {
+ db?: Pick;
+ provider?: MessagingProvider;
+ now?: Date;
+ intervalMs?: number;
+ sleep?: (ms: number) => Promise;
+};
+
+/**
+ * Weekly reminder to members with a PENDING or OVERDUE charge that already has
+ * a Checkout Pro link, in groups whose owner turned the automation on.
+ *
+ * One reminder per member per week even with several open charges: the oldest
+ * one goes in the message (the rest are in the same Cobros screen anyway).
+ */
+export class SendPaymentReminders {
+ constructor(private readonly deps: SendPaymentRemindersDeps = {}) {}
+
+ async execute(): Promise {
+ const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
+ if (!providerResult.ok) {
+ logger.warn('WhatsApp is not configured; payment reminders skipped');
+ return emptyTotals();
+ }
+ const provider = providerResult.value;
+ const db = this.deps.db ?? prisma;
+ const now = this.deps.now ?? new Date();
+ const totals = emptyTotals();
+
+ const accounts = await findEligibleAccounts(db, provider, 'autoPaymentReminders', 'PAYMENT_REMINDER');
+
+ for (const { account, country, groups } of accounts) {
+ const items: DispatchItem[] = [];
+
+ for (const group of groups) {
+ const payments = await db.payment.findMany({
+ where: {
+ groupId: group.id,
+ status: { in: ['PENDING', 'OVERDUE'] },
+ checkoutUrl: { not: null },
+ dueDate: { lte: new Date(now.getTime() + DUE_HORIZON_MS) },
+ attendee: { status: 'ACTIVE' },
+ },
+ select: {
+ id: true,
+ amount: true,
+ currency: true,
+ dueDate: true,
+ checkoutUrl: true,
+ attendee: { select: { id: true, fullName: true, phone: true, guardianPhone: true } },
+ },
+ orderBy: { dueDate: 'asc' },
+ });
+
+ const seen = new Set();
+ for (const payment of payments) {
+ if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue;
+ seen.add(payment.attendee.id);
+ items.push({
+ groupId: group.id,
+ attendeeId: payment.attendee.id,
+ paymentId: payment.id,
+ rawPhone: payment.attendee.phone ?? payment.attendee.guardianPhone,
+ message: {
+ kind: 'PAYMENT_REMINDER',
+ studentName: payment.attendee.fullName,
+ groupName: group.name,
+ amount: formatAmount(Number(payment.amount.toString()), payment.currency, country),
+ dueDate: formatDueDate(payment.dueDate, country),
+ paymentLink: payment.checkoutUrl,
+ },
+ });
+ }
+ }
+
+ const result = await dispatchForAccount(
+ {
+ db,
+ provider,
+ now,
+ intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(),
+ sleep: this.deps.sleep ?? sleep,
+ },
+ account,
+ country,
+ items,
+ );
+ addTotals(totals, result);
+ }
+
+ return totals;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts
new file mode 100644
index 0000000..0e452d2
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/jobs/send-reengagement-messages.ts
@@ -0,0 +1,106 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import prisma from '@/lib/prisma';
+import { logger } from '@/logger';
+import {
+ findStudentsAtRisk,
+ type StudentsAtRiskDb,
+} from '@/modules/analytics/features/get-students-at-risk/use-case';
+import {
+ addTotals,
+ type DispatchItem,
+ type DispatchTotals,
+ dispatchForAccount,
+ emptyTotals,
+ sendIntervalFromEnv,
+ sleep,
+} from '../lib/dispatch';
+import { getMessagingProvider } from '../providers';
+import type { MessagingProvider } from '../providers/messaging-provider';
+import { findEligibleAccounts } from './eligible-accounts';
+
+/** A member who got a re-engagement message is left alone for two weeks. */
+export const REENGAGEMENT_COOLDOWN_MS = 14 * 24 * 60 * 60 * 1000;
+
+type SendReengagementMessagesDeps = {
+ db?: Pick & StudentsAtRiskDb;
+ provider?: MessagingProvider;
+ now?: Date;
+ intervalMs?: number;
+ sleep?: (ms: number) => Promise;
+};
+
+/**
+ * Weekly re-engagement message to the members the teacher sees in "Alumnos en
+ * riesgo" (same rule, `findStudentsAtRisk`), in groups with the automation on.
+ */
+export class SendReengagementMessages {
+ constructor(private readonly deps: SendReengagementMessagesDeps = {}) {}
+
+ async execute(): Promise {
+ const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
+ if (!providerResult.ok) {
+ logger.warn('WhatsApp is not configured; re-engagement messages skipped');
+ return emptyTotals();
+ }
+ const provider = providerResult.value;
+ const db = this.deps.db ?? prisma;
+ const now = this.deps.now ?? new Date();
+ const totals = emptyTotals();
+
+ const accounts = await findEligibleAccounts(db, provider, 'autoReengagement', 'REENGAGEMENT');
+
+ for (const { account, country, groups } of accounts) {
+ const items: DispatchItem[] = [];
+
+ for (const group of groups) {
+ const atRisk = await findStudentsAtRisk(db, group.id, now);
+ if (atRisk.length === 0) continue;
+ const ids = atRisk.map((student) => student.attendeeId);
+
+ const [recent, contacts] = await Promise.all([
+ db.outboundMessage.findMany({
+ where: {
+ kind: 'REENGAGEMENT',
+ attendeeId: { in: ids },
+ status: { in: ['SENT', 'DELIVERED', 'READ'] },
+ createdAt: { gte: new Date(now.getTime() - REENGAGEMENT_COOLDOWN_MS) },
+ },
+ select: { attendeeId: true },
+ }),
+ db.attendee.findMany({
+ where: { id: { in: ids } },
+ select: { id: true, phone: true, guardianPhone: true },
+ }),
+ ]);
+ const coolingDown = new Set(recent.map((row) => row.attendeeId));
+ const phones = new Map(contacts.map((row) => [row.id, row.phone ?? row.guardianPhone]));
+
+ for (const student of atRisk) {
+ if (coolingDown.has(student.attendeeId)) continue;
+ items.push({
+ groupId: group.id,
+ attendeeId: student.attendeeId,
+ rawPhone: phones.get(student.attendeeId) ?? null,
+ message: { kind: 'REENGAGEMENT', studentName: student.fullName, groupName: group.name },
+ });
+ }
+ }
+
+ const result = await dispatchForAccount(
+ {
+ db,
+ provider,
+ now,
+ intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(),
+ sleep: this.deps.sleep ?? sleep,
+ },
+ account,
+ country,
+ items,
+ );
+ addTotals(totals, result);
+ }
+
+ return totals;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts b/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts
new file mode 100644
index 0000000..a11d1f7
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/jobs/sync-kapso-templates.ts
@@ -0,0 +1,52 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import prisma from '@/lib/prisma';
+import { logger } from '@/logger';
+import { KapsoProvider } from '../providers';
+import { getKapsoConfig } from '../providers/kapso/config';
+
+type SyncKapsoTemplatesDeps = {
+ db?: Pick;
+ provider?: KapsoProvider;
+};
+
+export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number };
+
+/** How many templates each account should have (one per message kind). */
+const EXPECTED_TEMPLATES = 2;
+
+/**
+ * Meta reviews templates on its own schedule (up to ~24h) and Kapso documents
+ * no webhook for the verdict, so this polls the accounts that are still waiting.
+ * Accounts missing a template (a submission that failed) get it resubmitted.
+ */
+export class SyncKapsoTemplates {
+ constructor(private readonly deps: SyncKapsoTemplatesDeps = {}) {}
+
+ async execute(): Promise {
+ const db = this.deps.db ?? prisma;
+ const provider = this.deps.provider ?? new KapsoProvider(getKapsoConfig(), { db });
+ const totals: SyncKapsoTemplatesResult = { checked: 0, updated: 0, failed: 0 };
+
+ const accounts = await db.whatsappAccount.findMany({
+ where: { provider: 'KAPSO', status: 'ACTIVE' },
+ include: { templates: { select: { status: true } } },
+ });
+
+ for (const account of accounts) {
+ const missing = account.templates.length < EXPECTED_TEMPLATES;
+ const pending = account.templates.some((template) => template.status === 'PENDING');
+ if (!missing && !pending) continue;
+
+ totals.checked += 1;
+ try {
+ if (missing) await provider.onConnected(account);
+ totals.updated += await provider.syncTemplates(account);
+ } catch (error) {
+ totals.failed += 1;
+ logger.warn({ err: error }, 'Kapso template sync failed for an account');
+ }
+ }
+
+ return totals;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/lib/account.ts b/apps/backend/src/modules/whatsapp/lib/account.ts
new file mode 100644
index 0000000..ddc3ae0
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/lib/account.ts
@@ -0,0 +1,43 @@
+import type { WhatsappAccountStatus } from '@gruperly/shared';
+import { getActiveProviderId } from '../providers/active';
+import type { MessagingProviderId } from '../providers/messaging-provider';
+
+type AccountLike = { provider: MessagingProviderId; status: 'PENDING' | 'ACTIVE' | 'DISCONNECTED' };
+
+/**
+ * A row linked through another gateway is useless after `WHATSAPP_PROVIDER`
+ * changes: the session or phone number id means nothing to the new one. It is
+ * kept (so nothing is lost if the switch is rolled back) and shown as
+ * "requires reconnect".
+ */
+export function toVisibleWhatsappStatus(
+ account: AccountLike | null,
+ activeProvider: MessagingProviderId = getActiveProviderId(),
+): WhatsappAccountStatus {
+ if (!account) return 'none';
+ if (account.provider !== activeProvider) {
+ return account.status === 'DISCONNECTED' ? 'none' : 'requires_reconnect';
+ }
+ switch (account.status) {
+ case 'PENDING':
+ return 'pending';
+ case 'ACTIVE':
+ return 'active';
+ case 'DISCONNECTED':
+ return 'disconnected';
+ }
+}
+
+/** Whether automated messages can go out from this account at all. */
+export function isWhatsappAccountUsable(
+ account: AccountLike | null,
+ activeProvider?: MessagingProviderId,
+): boolean {
+ if (!account) return false;
+ try {
+ return toVisibleWhatsappStatus(account, activeProvider) === 'active';
+ } catch {
+ // A bad WHATSAPP_PROVIDER must not break the screens that only ask "linked?".
+ return false;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/lib/activate-account.ts b/apps/backend/src/modules/whatsapp/lib/activate-account.ts
new file mode 100644
index 0000000..ec79222
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/lib/activate-account.ts
@@ -0,0 +1,74 @@
+import type { Prisma, PrismaClient } from '@generated/prisma/client';
+import { logger } from '@/logger';
+import type { MessagingProvider, WhatsappAccountRecord } from '../providers/messaging-provider';
+
+export type WhatsappAccountDb = Pick;
+
+/** Prisma's unique-constraint violation (here: the number is someone else's). */
+const UNIQUE_VIOLATION = 'P2002';
+
+export type ActivationInput = {
+ externalId?: string | null;
+ displayPhoneNumber?: string | null;
+ providerData?: Record | null;
+};
+
+/**
+ * Marks the teacher's account ACTIVE and runs the provider's `onConnected`.
+ *
+ * The same activation arrives through three doors (the status poll, the Kapso
+ * callback and the webhooks) and possibly more than once; an account that is
+ * already ACTIVE is left alone so `onConnected` does not run on every poll.
+ */
+export async function activateWhatsappAccount(
+ db: WhatsappAccountDb,
+ provider: MessagingProvider,
+ account: WhatsappAccountRecord,
+ input: ActivationInput,
+ now: Date,
+): Promise<{ ok: true; account: WhatsappAccountRecord } | { ok: false; reason: 'number_in_use' }> {
+ if (account.status === 'ACTIVE' && account.provider === provider.id) {
+ return { ok: true, account };
+ }
+
+ let updated: WhatsappAccountRecord;
+ try {
+ updated = await db.whatsappAccount.update({
+ where: { id: account.id },
+ data: {
+ status: 'ACTIVE',
+ connectedAt: now,
+ ...(input.externalId ? { externalId: input.externalId } : {}),
+ ...(input.displayPhoneNumber !== undefined ? { displayPhoneNumber: input.displayPhoneNumber } : {}),
+ ...(input.providerData
+ ? { providerData: mergeProviderData(account.providerData, input.providerData) }
+ : {}),
+ },
+ });
+ } catch (error) {
+ if ((error as { code?: string }).code === UNIQUE_VIOLATION) {
+ return { ok: false, reason: 'number_in_use' };
+ }
+ throw error;
+ }
+
+ if (provider.onConnected) {
+ try {
+ await provider.onConnected(updated);
+ } catch (error) {
+ // The account is linked either way; templates and webhooks are retried
+ // the next time the teacher links, and the sync job reports their state.
+ logger.error({ err: error, provider: provider.id }, 'WhatsApp post-connection setup failed');
+ }
+ }
+
+ return { ok: true, account: updated };
+}
+
+export function mergeProviderData(
+ current: unknown,
+ next: Record | null | undefined,
+): Prisma.InputJsonObject {
+ const base = current && typeof current === 'object' && !Array.isArray(current) ? current : {};
+ return { ...(base as Record), ...(next ?? {}) };
+}
diff --git a/apps/backend/src/modules/whatsapp/lib/dispatch.ts b/apps/backend/src/modules/whatsapp/lib/dispatch.ts
new file mode 100644
index 0000000..541003e
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/lib/dispatch.ts
@@ -0,0 +1,171 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { CountryCode, WhatsappMessageKind } from '@gruperly/shared';
+import { toWhatsappE164 } from '@gruperly/shared';
+import { logger } from '@/logger';
+import type {
+ MessagingProvider,
+ WhatsappAccountRecord,
+ WhatsappMessage,
+} from '../providers/messaging-provider';
+import { isoWeekKey } from './period';
+
+export type DispatchDb = Pick;
+
+/** One message the weekly job wants to send to one member. */
+export type DispatchItem = {
+ groupId: string;
+ attendeeId: string;
+ paymentId?: string | null;
+ /** The member's phone, or their guardian's, as stored. */
+ rawPhone: string | null;
+ message: WhatsappMessage;
+};
+
+export type DispatchTotals = { sent: number; skipped: number; failed: number };
+
+export type DispatcherDeps = {
+ db: DispatchDb;
+ provider: MessagingProvider;
+ now: Date;
+ /** Pause between two sends from the same account. */
+ intervalMs: number;
+ sleep: (ms: number) => Promise;
+};
+
+/** Prisma's unique-constraint violation: already handled this week. */
+const UNIQUE_VIOLATION = 'P2002';
+
+export const DEFAULT_SEND_INTERVAL_MS = 5_000;
+
+export function sendIntervalFromEnv(): number {
+ const value = Number(process.env.WHATSAPP_SEND_INTERVAL_MS);
+ return Number.isFinite(value) && value >= 0 ? value : DEFAULT_SEND_INTERVAL_MS;
+}
+
+export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+export function emptyTotals(): DispatchTotals {
+ return { sent: 0, skipped: 0, failed: 0 };
+}
+
+export function addTotals(into: DispatchTotals, from: DispatchTotals): DispatchTotals {
+ into.sent += from.sent;
+ into.skipped += from.skipped;
+ into.failed += from.failed;
+ return into;
+}
+
+/**
+ * Sends one account's messages, one after the other.
+ *
+ * Every message is first written to `outbound_messages` (QUEUED) and only then
+ * handed to the provider: the unique (kind, attendee, week) makes a second run
+ * of the job skip it, and the row id doubles as the provider's idempotency key,
+ * so a retried HTTP call cannot deliver twice either.
+ *
+ * Sends are paced (`intervalMs`) and stop for the whole account when the
+ * provider says it is rate limited: hammering an unofficial gateway is how a
+ * number gets banned. What was not sent stays for next week.
+ */
+export async function dispatchForAccount(
+ deps: DispatcherDeps,
+ account: WhatsappAccountRecord,
+ country: CountryCode | null,
+ items: DispatchItem[],
+): Promise {
+ const totals = emptyTotals();
+ const periodKey = isoWeekKey(deps.now);
+ let sentBefore = false;
+
+ for (const item of items) {
+ const base = {
+ ownerId: account.ownerId,
+ groupId: item.groupId,
+ attendeeId: item.attendeeId,
+ paymentId: item.paymentId ?? null,
+ kind: item.message.kind as WhatsappMessageKind,
+ provider: deps.provider.id,
+ periodKey,
+ };
+
+ const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null;
+ if (!e164) {
+ await record(deps.db, { ...base, toPhone: item.rawPhone ?? '', status: 'SKIPPED', errorCode: 'invalid_phone' });
+ totals.skipped += 1;
+ continue;
+ }
+
+ const recipient = await deps.provider.resolveRecipient(account, e164);
+ if (!recipient.ok) {
+ if (recipient.code === 'no_whatsapp') {
+ await record(deps.db, { ...base, toPhone: e164, status: 'SKIPPED', errorCode: 'no_whatsapp' });
+ totals.skipped += 1;
+ } else {
+ // No row: the gateway could not tell, so next week tries again.
+ totals.failed += 1;
+ }
+ continue;
+ }
+
+ const row = await record(deps.db, { ...base, toPhone: e164, status: 'QUEUED' });
+ if (!row) {
+ totals.skipped += 1;
+ continue;
+ }
+
+ if (sentBefore && deps.intervalMs > 0) await deps.sleep(deps.intervalMs);
+ sentBefore = true;
+
+ const outcome = await deps.provider.send(account, recipient.to, item.message, row.id);
+ if (outcome.ok) {
+ await deps.db.outboundMessage.update({
+ where: { id: row.id },
+ data: { status: 'SENT', providerMessageId: outcome.providerMessageId, sentAt: new Date() },
+ });
+ totals.sent += 1;
+ continue;
+ }
+
+ if (outcome.rateLimitedForMs !== undefined) {
+ // Never sent: drop the row so this member is not marked as handled.
+ await deps.db.outboundMessage.delete({ where: { id: row.id } });
+ totals.skipped += 1;
+ logger.warn(
+ { provider: deps.provider.id, retryInMs: outcome.rateLimitedForMs },
+ 'WhatsApp account rate limited; stopping its sends for this run',
+ );
+ break;
+ }
+
+ await deps.db.outboundMessage.update({
+ where: { id: row.id },
+ data: { status: 'FAILED', errorCode: outcome.code, errorMessage: outcome.message.slice(0, 500) },
+ });
+ totals.failed += 1;
+ }
+
+ return totals;
+}
+
+type RecordInput = {
+ ownerId: string;
+ groupId: string;
+ attendeeId: string;
+ paymentId: string | null;
+ kind: WhatsappMessageKind;
+ provider: MessagingProvider['id'];
+ periodKey: string;
+ toPhone: string;
+ status: 'QUEUED' | 'SKIPPED';
+ errorCode?: string;
+};
+
+/** Creates the log row, or returns null when this member was already handled this week. */
+async function record(db: DispatchDb, data: RecordInput): Promise<{ id: string } | null> {
+ try {
+ return await db.outboundMessage.create({ data, select: { id: true } });
+ } catch (error) {
+ if ((error as { code?: string }).code === UNIQUE_VIOLATION) return null;
+ throw error;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/lib/format.ts b/apps/backend/src/modules/whatsapp/lib/format.ts
new file mode 100644
index 0000000..f4bb64e
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/lib/format.ts
@@ -0,0 +1,50 @@
+import type { CountryCode } from '@gruperly/shared';
+import { DEFAULT_COUNTRY } from '@gruperly/shared';
+
+/* Amounts and dates go inside a WhatsApp message, so they are formatted the way
+ people in the teacher's country write them (the student is there too). */
+
+const LOCALES: Record = {
+ AR: 'es-AR',
+ BR: 'pt-BR',
+ CL: 'es-CL',
+ CO: 'es-CO',
+ MX: 'es-MX',
+ PE: 'es-PE',
+ UY: 'es-UY',
+};
+
+const TIME_ZONES: Record = {
+ AR: 'America/Argentina/Buenos_Aires',
+ BR: 'America/Sao_Paulo',
+ CL: 'America/Santiago',
+ CO: 'America/Bogota',
+ MX: 'America/Mexico_City',
+ PE: 'America/Lima',
+ UY: 'America/Montevideo',
+};
+
+/** `25000` ARS → `$ 25.000`; cents only when there are any. */
+export function formatAmount(
+ amount: number,
+ currency: string,
+ country: CountryCode | null | undefined,
+): string {
+ const hasCents = !Number.isInteger(amount);
+ return new Intl.NumberFormat(LOCALES[country ?? DEFAULT_COUNTRY], {
+ style: 'currency',
+ currency,
+ minimumFractionDigits: hasCents ? 2 : 0,
+ maximumFractionDigits: 2,
+ }).format(amount);
+}
+
+/** Due date as day/month in the teacher's country, e.g. `10/11`. */
+export function formatDueDate(date: Date, country: CountryCode | null | undefined): string {
+ const resolved = country ?? DEFAULT_COUNTRY;
+ return new Intl.DateTimeFormat(LOCALES[resolved], {
+ day: '2-digit',
+ month: '2-digit',
+ timeZone: TIME_ZONES[resolved],
+ }).format(date);
+}
diff --git a/apps/backend/src/modules/whatsapp/lib/hmac.ts b/apps/backend/src/modules/whatsapp/lib/hmac.ts
new file mode 100644
index 0000000..38d0e9a
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/lib/hmac.ts
@@ -0,0 +1,24 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+/**
+ * Constant-time check of an HMAC-SHA256 hex signature computed over the raw
+ * request body. It has to be the raw text: re-serializing the parsed JSON can
+ * reorder keys or change whitespace and the signature would never match.
+ *
+ * `prefix` covers providers that send `sha256=` (OpenWA) instead of the
+ * bare hex (Kapso).
+ */
+export function verifyHmacSha256(
+ rawBody: string,
+ signature: string | null | undefined,
+ secret: string,
+ prefix = '',
+): boolean {
+ if (typeof signature !== 'string' || !signature) return false;
+
+ const expected = prefix + createHmac('sha256', secret).update(rawBody).digest('hex');
+ const received = Buffer.from(signature.trim());
+ const wanted = Buffer.from(expected);
+ // `timingSafeEqual` throws on a length mismatch, so a forged short header fails first.
+ return received.length === wanted.length && timingSafeEqual(received, wanted);
+}
diff --git a/apps/backend/src/modules/whatsapp/lib/period.ts b/apps/backend/src/modules/whatsapp/lib/period.ts
new file mode 100644
index 0000000..0c14d74
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/lib/period.ts
@@ -0,0 +1,16 @@
+/**
+ * ISO-8601 week of a date in UTC, e.g. `2026-W43`.
+ *
+ * It is the `periodKey` of an automated message: one message of each kind per
+ * member per week, enforced by a unique index, so a job that runs twice (two
+ * API instances, a manual re-run) cannot write to the same person twice.
+ */
+export function isoWeekKey(date: Date): string {
+ const day = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
+ // Thursday of the same week decides the ISO year.
+ const weekday = day.getUTCDay() || 7;
+ day.setUTCDate(day.getUTCDate() + 4 - weekday);
+ const yearStart = new Date(Date.UTC(day.getUTCFullYear(), 0, 1));
+ const week = Math.ceil(((day.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7);
+ return `${day.getUTCFullYear()}-W${String(week).padStart(2, '0')}`;
+}
diff --git a/apps/backend/src/modules/whatsapp/lib/render-message.ts b/apps/backend/src/modules/whatsapp/lib/render-message.ts
new file mode 100644
index 0000000..7494565
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/lib/render-message.ts
@@ -0,0 +1,33 @@
+import type { WhatsappMessage } from '../providers/messaging-provider';
+
+/**
+ * The Spanish copy of the automated messages, as free text.
+ *
+ * OpenWA sends exactly this. Kapso cannot (Meta only allows approved templates
+ * outside the 24h window), but its template bodies in `providers/kapso/templates.ts`
+ * are written from these same sentences: if one changes, change the other and
+ * submit a new template version.
+ */
+export function renderMessage(message: WhatsappMessage): string {
+ const firstName = firstNameOf(message.studentName);
+
+ switch (message.kind) {
+ case 'PAYMENT_REMINDER':
+ return (
+ `¡Hola ${firstName}! Te recordamos el pago de ${message.groupName} ` +
+ `por ${message.amount}, con vencimiento el ${message.dueDate}. ` +
+ `Podés pagarlo desde este link: ${message.paymentLink}`
+ );
+ case 'REENGAGEMENT':
+ // Same copy the teacher sends by hand from "Alumnos en riesgo".
+ return (
+ `¡Hola ${firstName}! 👋 Te extrañamos en ${message.groupName}. ` +
+ 'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' +
+ 'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.'
+ );
+ }
+}
+
+export function firstNameOf(fullName: string): string {
+ return fullName.trim().split(/\s+/)[0] ?? fullName;
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/active.ts b/apps/backend/src/modules/whatsapp/providers/active.ts
new file mode 100644
index 0000000..9f5d6f3
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/active.ts
@@ -0,0 +1,19 @@
+import type { MessagingProviderId } from './messaging-provider';
+
+const PROVIDERS: Record = {
+ openwa: 'OPENWA',
+ kapso: 'KAPSO',
+};
+
+/**
+ * The gateway this deployment sends through (`WHATSAPP_PROVIDER`, default
+ * `openwa`). An unknown value is a deployment mistake and fails loudly.
+ */
+export function getActiveProviderId(): MessagingProviderId {
+ const raw = process.env.WHATSAPP_PROVIDER?.trim().toLowerCase() || 'openwa';
+ const id = PROVIDERS[raw];
+ if (!id) {
+ throw new Error(`Unknown WHATSAPP_PROVIDER "${raw}". Use one of: ${Object.keys(PROVIDERS).join(', ')}.`);
+ }
+ return id;
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/index.ts b/apps/backend/src/modules/whatsapp/providers/index.ts
new file mode 100644
index 0000000..b71da22
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/index.ts
@@ -0,0 +1,40 @@
+import type { ProblemDetails, Result } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { whatsappNotConfiguredProblem } from '@/http/problem-builders';
+import { logger } from '@/logger';
+import { getActiveProviderId } from './active';
+import { KapsoProvider } from './kapso';
+import { getKapsoConfig } from './kapso/config';
+import type { MessagingProvider, MessagingProviderId } from './messaging-provider';
+import { OpenWaProvider } from './openwa';
+import { getOpenWaConfig } from './openwa/config';
+
+export { getActiveProviderId } from './active';
+export { KapsoProvider } from './kapso';
+export type * from './messaging-provider';
+export { OpenWaProvider } from './openwa';
+
+/**
+ * The one place that maps a provider id to its adapter. Swapping gateways means
+ * changing `WHATSAPP_PROVIDER`; adding one means a new `providers//` that
+ * implements `MessagingProvider` plus a case here.
+ *
+ * A missing variable is answered as `whatsapp_not_configured` (503) instead of
+ * crashing, so the rest of the app (and the skippable onboarding step) keeps
+ * working on a deployment without WhatsApp.
+ */
+export function getMessagingProvider(
+ id?: MessagingProviderId,
+): Result {
+ try {
+ switch (id ?? getActiveProviderId()) {
+ case 'OPENWA':
+ return ok(new OpenWaProvider(getOpenWaConfig()));
+ case 'KAPSO':
+ return ok(new KapsoProvider(getKapsoConfig()));
+ }
+ } catch (error) {
+ logger.error({ err: error }, 'WhatsApp messaging is not configured');
+ return err(whatsappNotConfiguredProblem());
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/config.ts b/apps/backend/src/modules/whatsapp/providers/kapso/config.ts
new file mode 100644
index 0000000..cee671a
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/kapso/config.ts
@@ -0,0 +1,47 @@
+export type KapsoConfig = {
+ /** `https://api.kapso.ai` unless overridden. */
+ apiUrl: string;
+ /** Project API key, sent as `X-API-Key`. */
+ apiKey: string;
+ /** Public URL of `/api/v1/whatsapp/callback` (setup link redirects). */
+ callbackUrl: string;
+ /** Public URL of `/api/v1/whatsapp/webhooks/kapso`. */
+ webhookUrl: string;
+ /** HMAC secret for the project webhook and every per-number webhook. */
+ webhookSecret: string;
+};
+
+const DEFAULT_API_URL = 'https://api.kapso.ai';
+
+/**
+ * Reads the Kapso settings. Throws on a deployment mistake, naming the missing
+ * variables (never their values), like `getMpOAuthConfig()`.
+ */
+export function getKapsoConfig(): KapsoConfig {
+ const missing: string[] = [];
+ const read = (name: string): string => {
+ const value = process.env[name]?.trim();
+ if (!value) {
+ missing.push(name);
+ return '';
+ }
+ return value;
+ };
+
+ const apiKey = read('KAPSO_API_KEY');
+ const callbackUrl = read('KAPSO_CALLBACK_URL');
+ const webhookUrl = read('KAPSO_WEBHOOK_URL');
+ const webhookSecret = read('KAPSO_WEBHOOK_SECRET');
+
+ if (missing.length > 0) {
+ throw new Error(`Missing Kapso environment variables: ${missing.join(', ')}. See .env.example.`);
+ }
+
+ return {
+ apiUrl: (process.env.KAPSO_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, ''),
+ apiKey,
+ callbackUrl,
+ webhookUrl,
+ webhookSecret,
+ };
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/http.ts b/apps/backend/src/modules/whatsapp/providers/kapso/http.ts
new file mode 100644
index 0000000..87bb430
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/kapso/http.ts
@@ -0,0 +1,210 @@
+import type { KapsoConfig } from './config';
+
+/**
+ * Thin client for Kapso: the Platform API (customers, setup links, phone
+ * numbers, webhooks) and the Meta proxy (templates, messages). Plain `fetch`
+ * on purpose: `@kapso/whatsapp-cloud-api` brings its own Zod, and this repo
+ * pins zod 3.24 (see AGENTS.md).
+ */
+
+export const META_GRAPH_VERSION = 'v24.0';
+
+export class KapsoApiError extends Error {
+ constructor(
+ readonly status: number,
+ /** Meta error code (e.g. `131047`) or Kapso's error string when there is one. */
+ readonly code: string | null,
+ ) {
+ super(`Kapso request failed with ${status}${code ? ` (${code})` : ''}`);
+ this.name = 'KapsoApiError';
+ }
+}
+
+export type KapsoFetch = (input: string, init?: RequestInit) => Promise;
+
+export type KapsoPhoneNumber = {
+ phone_number_id: string;
+ business_account_id: string | null;
+ display_phone_number: string | null;
+ customer_id: string | null;
+ status?: string | null;
+};
+
+export type MetaTemplate = {
+ id: string;
+ name: string;
+ language?: string;
+ status: string;
+ category?: string;
+ rejected_reason?: string | null;
+};
+
+export type MetaTemplateComponent = {
+ type: 'BODY';
+ text: string;
+ example?: { body_text_named_params: { param_name: string; example: string }[] };
+};
+
+export type MetaTemplateDefinition = {
+ name: string;
+ language: string;
+ category: 'UTILITY' | 'MARKETING';
+ parameter_format: 'NAMED';
+ components: MetaTemplateComponent[];
+};
+
+const REQUEST_TIMEOUT_MS = 30_000;
+
+export class KapsoClient {
+ constructor(
+ private readonly config: KapsoConfig,
+ private readonly fetchFn: KapsoFetch = (input, init) => fetch(input, init),
+ ) {}
+
+ async createCustomer(input: { name: string; externalId: string }): Promise<{ id: string }> {
+ const response = await this.request<{ data: { id: string } }>('POST', '/platform/v1/customers', {
+ customer: { name: input.name, external_customer_id: input.externalId },
+ });
+ return response.data;
+ }
+
+ async createSetupLink(
+ customerId: string,
+ input: { successRedirectUrl: string; failureRedirectUrl: string },
+ ): Promise<{ id: string; url: string }> {
+ const response = await this.request<{ data: { id: string; url: string } }>(
+ 'POST',
+ `/platform/v1/customers/${encodeURIComponent(customerId)}/setup_links`,
+ {
+ setup_link: {
+ success_redirect_url: input.successRedirectUrl,
+ failure_redirect_url: input.failureRedirectUrl,
+ allowed_connection_types: ['coexistence', 'dedicated'],
+ // The teacher pays Meta from their own Business account. Fixed at
+ // creation: Kapso cannot change it on an existing link.
+ meta_billing_mode: 'customer_managed',
+ language: 'es',
+ },
+ },
+ );
+ return response.data;
+ }
+
+ async getPhoneNumber(phoneNumberId: string): Promise {
+ const response = await this.request<{ data: KapsoPhoneNumber }>(
+ 'GET',
+ `/platform/v1/whatsapp/phone_numbers/${encodeURIComponent(phoneNumberId)}`,
+ );
+ return response.data;
+ }
+
+ async createPhoneWebhook(
+ phoneNumberId: string,
+ input: { url: string; secret: string; events: string[] },
+ ): Promise<{ id: string }> {
+ const response = await this.request<{ data: { id: string } }>(
+ 'POST',
+ `/platform/v1/whatsapp/phone_numbers/${encodeURIComponent(phoneNumberId)}/webhooks`,
+ {
+ whatsapp_webhook: {
+ url: input.url,
+ secret_key: input.secret,
+ events: input.events,
+ kind: 'kapso',
+ active: true,
+ },
+ },
+ );
+ return response.data;
+ }
+
+ createTemplate(
+ businessAccountId: string,
+ template: MetaTemplateDefinition,
+ ): Promise<{ id: string; status: string; category?: string }> {
+ return this.request(
+ 'POST',
+ `/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(businessAccountId)}/message_templates`,
+ template,
+ );
+ }
+
+ async listTemplates(businessAccountId: string, name?: string): Promise {
+ const query = name ? `?name=${encodeURIComponent(name)}` : '';
+ const response = await this.request<{ data?: MetaTemplate[] }>(
+ 'GET',
+ `/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(businessAccountId)}/message_templates${query}`,
+ );
+ return response.data ?? [];
+ }
+
+ async sendTemplate(
+ phoneNumberId: string,
+ input: {
+ to: string;
+ name: string;
+ language: string;
+ parameters: { name: string; text: string }[];
+ },
+ ): Promise<{ messageId: string }> {
+ const response = await this.request<{ messages?: { id: string }[] }>(
+ 'POST',
+ `/meta/whatsapp/${META_GRAPH_VERSION}/${encodeURIComponent(phoneNumberId)}/messages`,
+ {
+ messaging_product: 'whatsapp',
+ to: input.to,
+ type: 'template',
+ template: {
+ name: input.name,
+ language: { code: input.language },
+ components: [
+ {
+ type: 'body',
+ parameters: input.parameters.map((parameter) => ({
+ type: 'text',
+ parameter_name: parameter.name,
+ text: parameter.text,
+ })),
+ },
+ ],
+ },
+ },
+ );
+ const messageId = response.messages?.[0]?.id;
+ if (!messageId) throw new KapsoApiError(502, 'missing_message_id');
+ return { messageId };
+ }
+
+ private async request(method: string, path: string, body?: unknown): Promise {
+ const response = await this.fetchFn(`${this.config.apiUrl}${path}`, {
+ method,
+ headers: {
+ 'X-API-Key': this.config.apiKey,
+ Accept: 'application/json',
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+
+ if (!response.ok) {
+ const payload = (await response.json().catch(() => null)) as {
+ error?: { code?: unknown; error_subcode?: unknown } | string;
+ code?: unknown;
+ } | null;
+ throw new KapsoApiError(response.status, errorCode(payload));
+ }
+
+ if (response.status === 204) return undefined as T;
+ return (await response.json()) as T;
+ }
+}
+
+function errorCode(
+ payload: { error?: { code?: unknown } | string; code?: unknown } | null,
+): string | null {
+ if (!payload) return null;
+ if (typeof payload.error === 'string') return payload.error;
+ const code = payload.error?.code ?? payload.code;
+ return code === undefined || code === null ? null : String(code);
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/index.ts b/apps/backend/src/modules/whatsapp/providers/kapso/index.ts
new file mode 100644
index 0000000..6f408ad
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/kapso/index.ts
@@ -0,0 +1,436 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type {
+ ProblemDetails,
+ Result,
+ WhatsappCallbackReason,
+ WhatsappMessageKind,
+ WhatsappReadiness,
+} from '@gruperly/shared';
+import { err, ok, whatsappMessageKindSchema } from '@gruperly/shared';
+import { whatsappProviderErrorProblem } from '@/http/problem-builders';
+import prisma from '@/lib/prisma';
+import { logger } from '@/logger';
+import { verifyHmacSha256 } from '../../lib/hmac';
+import type {
+ CompletedConnection,
+ ConnectionSnapshot,
+ MessageDeliveryStatus,
+ MessagingProvider,
+ NormalizedEvent,
+ ParsedWebhook,
+ RecipientResolution,
+ SendOutcome,
+ StartConnectionContext,
+ StartConnectionResult,
+ WebhookParseError,
+ WhatsappAccountRecord,
+ WhatsappMessage,
+} from '../messaging-provider';
+import type { KapsoConfig } from './config';
+import { KapsoApiError, KapsoClient, type KapsoFetch } from './http';
+import { KAPSO_TEMPLATES, TEMPLATE_LANGUAGE, toTemplateStatus } from './templates';
+
+/** Message events each connected number reports to our webhook. */
+export const KAPSO_MESSAGE_EVENTS = [
+ 'whatsapp.message.sent',
+ 'whatsapp.message.delivered',
+ 'whatsapp.message.read',
+ 'whatsapp.message.failed',
+];
+
+/**
+ * Errors where repeating the same send cannot help: 402 out of credits (only
+ * with partner billing), 131047 outside the 24h window (templates avoid it),
+ * the student opting out of marketing, or a number/account mismatch.
+ */
+const PERMANENT_SEND_ERRORS = new Set([
+ '131047',
+ '131050',
+ 'marketing_preference_stopped',
+ 'messaging_account_mismatch',
+ 'insufficient_credits',
+]);
+
+export type KapsoProviderData = {
+ customerId?: string;
+ setupLinkId?: string;
+ businessAccountId?: string;
+ webhookId?: string;
+};
+
+type KapsoProviderDeps = {
+ db?: Pick;
+ fetch?: KapsoFetch;
+};
+
+/**
+ * Kapso, on top of Meta's official WhatsApp Cloud API.
+ *
+ * Linking is a hosted flow: we create a Kapso customer for the teacher, send
+ * them to a setup link (Facebook login + number verification at Meta) and
+ * Kapso redirects back to our callback. Messages outside a conversation must
+ * be approved templates, which Meta reviews per WhatsApp Business Account, so
+ * a freshly linked account sends nothing until its templates are APPROVED.
+ */
+export class KapsoProvider implements MessagingProvider {
+ readonly id = 'KAPSO' as const;
+ private readonly client: KapsoClient;
+
+ constructor(
+ private readonly config: KapsoConfig,
+ private readonly deps: KapsoProviderDeps = {},
+ ) {
+ this.client = new KapsoClient(config, deps.fetch);
+ }
+
+ private get db() {
+ return this.deps.db ?? prisma;
+ }
+
+ async startConnection(
+ context: StartConnectionContext,
+ ): Promise> {
+ const previous = context.account?.provider === 'KAPSO' ? readData(context.account.providerData) : {};
+
+ try {
+ // One Kapso customer per teacher, reused when they link again.
+ const customerId =
+ previous.customerId ??
+ (await this.client.createCustomer({ name: context.ownerName, externalId: context.ownerId })).id;
+
+ const returnUrl = `${this.config.callbackUrl}?returnTo=${context.returnTo}`;
+ const link = await this.client.createSetupLink(customerId, {
+ successRedirectUrl: returnUrl,
+ failureRedirectUrl: returnUrl,
+ });
+
+ return ok({
+ start: { type: 'redirect', url: link.url },
+ externalId: null,
+ providerData: { customerId, setupLinkId: link.id },
+ });
+ } catch (error) {
+ logger.error({ err: describe(error) }, 'Kapso could not create a setup link');
+ return err(whatsappProviderErrorProblem());
+ }
+ }
+
+ async refreshConnection(
+ account: WhatsappAccountRecord,
+ ): Promise> {
+ // A Kapso linking happens at Meta; there is no QR to refresh. Until the
+ // callback (or the `phone_number.created` webhook) lands it is just pending.
+ if (account.status === 'ACTIVE') {
+ return ok({ state: 'active', displayPhoneNumber: account.displayPhoneNumber });
+ }
+ return ok({ state: 'pending', qrCode: null });
+ }
+
+ async completeRedirect(
+ account: WhatsappAccountRecord,
+ query: Record,
+ ): Promise> {
+ const data = readData(account.providerData);
+
+ // Nothing in this query is trusted: anyone can type a URL. The setup link
+ // has to be the one we created for this teacher, and Kapso itself has to
+ // confirm that the number belongs to this teacher's customer.
+ if (!query.setup_link_id || query.setup_link_id !== data.setupLinkId || !data.customerId) {
+ return err('invalid_setup');
+ }
+ if (query.error_code || (query.status && query.status !== 'completed')) {
+ return err('setup_failed');
+ }
+ if (!query.phone_number_id) return err('invalid_setup');
+
+ try {
+ const phone = await this.client.getPhoneNumber(query.phone_number_id);
+ if (phone.customer_id !== data.customerId) return err('invalid_setup');
+
+ return ok({
+ externalId: phone.phone_number_id,
+ displayPhoneNumber: formatPhone(phone.display_phone_number),
+ providerData: {
+ ...compact(data),
+ ...(phone.business_account_id ? { businessAccountId: phone.business_account_id } : {}),
+ },
+ });
+ } catch (error) {
+ logger.error({ err: describe(error) }, 'Kapso phone number lookup failed');
+ return err('provider_error');
+ }
+ }
+
+ async disconnect(): Promise> {
+ // The number stays connected to the teacher's WhatsApp Business Account at
+ // Meta (they manage it there); unlinking here only stops Gruperly from
+ // sending through it. The Kapso customer is kept for a later relink.
+ return ok(undefined);
+ }
+
+ /**
+ * Subscribes our webhook to the number and submits the templates. Safe to run
+ * again: what already exists is skipped.
+ */
+ async onConnected(account: WhatsappAccountRecord): Promise {
+ if (!account.externalId) return;
+ const data = readData(account.providerData);
+
+ if (!data.businessAccountId) {
+ const phone = await this.client.getPhoneNumber(account.externalId);
+ if (phone.business_account_id) data.businessAccountId = phone.business_account_id;
+ }
+
+ if (!data.webhookId) {
+ try {
+ const webhook = await this.client.createPhoneWebhook(account.externalId, {
+ url: this.config.webhookUrl,
+ secret: this.config.webhookSecret,
+ events: KAPSO_MESSAGE_EVENTS,
+ });
+ data.webhookId = webhook.id;
+ } catch (error) {
+ // Only delivery receipts depend on it; sending still works.
+ logger.warn({ err: describe(error) }, 'Kapso per-number webhook registration failed');
+ }
+ }
+
+ await this.db.whatsappAccount.update({
+ where: { id: account.id },
+ data: { providerData: compact(data) },
+ });
+
+ if (data.businessAccountId) {
+ await this.submitTemplates(account.id, data.businessAccountId);
+ }
+ }
+
+ async readiness(
+ account: WhatsappAccountRecord,
+ kind: WhatsappMessageKind,
+ ): Promise {
+ if (account.status !== 'ACTIVE') return 'blocked';
+ const template = await this.db.whatsappTemplate.findUnique({
+ where: { accountId_kind: { accountId: account.id, kind } },
+ });
+ if (!template || template.status === 'PENDING') return 'pending';
+ return template.status === 'APPROVED' ? 'ready' : 'blocked';
+ }
+
+ async resolveRecipient(_account: WhatsappAccountRecord, e164: string): Promise {
+ // The Cloud API takes the E.164 digits; it reports unknown numbers on send.
+ return { ok: true, to: e164.replace(/\D/g, '') };
+ }
+
+ async send(
+ account: WhatsappAccountRecord,
+ to: string,
+ message: WhatsappMessage,
+ ): Promise {
+ if (!account.externalId) {
+ return { ok: false, retryable: false, code: 'no_phone_number', message: 'Account has no number' };
+ }
+ const spec = KAPSO_TEMPLATES[message.kind];
+
+ try {
+ const response = await this.client.sendTemplate(account.externalId, {
+ to,
+ name: spec.definition.name,
+ language: TEMPLATE_LANGUAGE,
+ parameters: spec.parameters(message),
+ });
+ return { ok: true, providerMessageId: response.messageId };
+ } catch (error) {
+ if (error instanceof KapsoApiError) {
+ const permanent =
+ error.status === 402 ||
+ (error.code !== null && PERMANENT_SEND_ERRORS.has(error.code)) ||
+ (error.status >= 400 && error.status < 500 && error.status !== 409 && error.status !== 429);
+ return {
+ ok: false,
+ retryable: !permanent,
+ ...(error.status === 429 ? { rateLimitedForMs: 60_000 } : {}),
+ code: error.code ?? `http_${error.status}`,
+ message: error.message,
+ };
+ }
+ return { ok: false, retryable: true, code: 'network_error', message: describe(error).message };
+ }
+ }
+
+ parseWebhook(rawBody: string, headers: Headers): Result {
+ if (!verifyHmacSha256(rawBody, headers.get('X-Webhook-Signature'), this.config.webhookSecret)) {
+ return err('invalid_signature');
+ }
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(rawBody);
+ } catch {
+ return err('invalid_payload');
+ }
+
+ const dedupeKey = headers.get('X-Idempotency-Key');
+ if (!dedupeKey) return err('invalid_payload');
+
+ // Batched deliveries (`X-Webhook-Batch`) carry the events in `data[]`.
+ const headerEvent = headers.get('X-Webhook-Event');
+ const items = isRecord(payload) && Array.isArray(payload.data) ? payload.data : [payload];
+ const events = items.flatMap((item) => (isRecord(item) ? toEvents(item, headerEvent) : []));
+
+ return ok({ dedupeKey, events });
+ }
+
+ /** Pulls Meta's verdict for the account's pending templates. */
+ async syncTemplates(account: WhatsappAccountRecord): Promise {
+ const data = readData(account.providerData);
+ if (!data.businessAccountId) return 0;
+
+ const pending = await this.db.whatsappTemplate.findMany({
+ where: { accountId: account.id, status: 'PENDING' },
+ });
+ let updated = 0;
+ for (const template of pending) {
+ const [remote] = await this.client.listTemplates(data.businessAccountId, template.name);
+ if (!remote) continue;
+ const status = toTemplateStatus(remote.status);
+ if (status === template.status) continue;
+ await this.db.whatsappTemplate.update({
+ where: { id: template.id },
+ data: { status, metaTemplateId: remote.id, rejectedReason: remote.rejected_reason ?? null },
+ });
+ updated += 1;
+ }
+ return updated;
+ }
+
+ private async submitTemplates(accountId: string, businessAccountId: string): Promise {
+ for (const kind of whatsappMessageKindSchema.options) {
+ const existing = await this.db.whatsappTemplate.findUnique({
+ where: { accountId_kind: { accountId, kind } },
+ });
+ if (existing) continue;
+
+ const { definition } = KAPSO_TEMPLATES[kind];
+ let remote: { id: string; status: string } | null = null;
+ try {
+ remote = await this.client.createTemplate(businessAccountId, definition);
+ } catch (error) {
+ // Relinking the same Business Account: the template is already there.
+ const [found] = await this.client.listTemplates(businessAccountId, definition.name).catch(() => []);
+ if (!found) {
+ logger.error({ err: describe(error), kind }, 'Kapso template submission failed');
+ continue;
+ }
+ remote = found;
+ }
+
+ await this.db.whatsappTemplate.create({
+ data: {
+ accountId,
+ kind,
+ name: definition.name,
+ language: definition.language,
+ metaTemplateId: remote.id,
+ status: toTemplateStatus(remote.status),
+ },
+ });
+ }
+ }
+}
+
+const MESSAGE_STATUSES: Record = {
+ 'whatsapp.message.sent': 'SENT',
+ 'whatsapp.message.delivered': 'DELIVERED',
+ 'whatsapp.message.read': 'READ',
+ 'whatsapp.message.failed': 'FAILED',
+};
+
+function toEvents(item: Record, headerEvent: string | null): NormalizedEvent[] {
+ const event = headerEvent ?? (typeof item.event === 'string' ? item.event : null);
+ if (!event) return [];
+
+ const phoneNumberId = stringAt(item, 'phone_number_id') ?? stringAt(item, 'phone_number', 'phone_number_id');
+
+ if (event === 'whatsapp.phone_number.created') {
+ if (!phoneNumberId) return [];
+ const businessAccountId = stringAt(item, 'business_account_id');
+ return [
+ {
+ type: 'connection',
+ externalId: phoneNumberId,
+ ownerId: stringAt(item, 'customer', 'external_id') ?? undefined,
+ status: 'active',
+ displayPhoneNumber: formatPhone(stringAt(item, 'display_phone_number')),
+ providerData: businessAccountId ? { businessAccountId } : null,
+ },
+ ];
+ }
+
+ if (
+ event === 'whatsapp.phone_number.deleted' ||
+ event === 'whatsapp.phone_number.disconnected' ||
+ event === 'whatsapp.phone_number.offboarded'
+ ) {
+ return phoneNumberId ? [{ type: 'connection', externalId: phoneNumberId, status: 'disconnected' }] : [];
+ }
+
+ const status = MESSAGE_STATUSES[event];
+ const messageId = stringAt(item, 'message', 'id');
+ if (!status || !messageId) return [];
+
+ const errors = (isRecord(item.message) && isRecord(item.message.kapso) && Array.isArray(item.message.kapso.statuses)
+ ? item.message.kapso.statuses
+ : []
+ ).flatMap((entry) => (isRecord(entry) && Array.isArray(entry.errors) ? entry.errors : []));
+ const firstError = errors.find(isRecord);
+
+ return [
+ {
+ type: 'message_status',
+ providerMessageId: messageId,
+ status,
+ errorCode: status === 'FAILED' ? (firstError?.code != null ? String(firstError.code) : 'delivery_failed') : null,
+ errorMessage:
+ status === 'FAILED' && typeof firstError?.title === 'string' ? firstError.title : null,
+ },
+ ];
+}
+
+function isRecord(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function stringAt(value: Record, ...path: string[]): string | null {
+ let current: unknown = value;
+ for (const key of path) {
+ if (!isRecord(current)) return null;
+ current = current[key];
+ }
+ return typeof current === 'string' && current ? current : null;
+}
+
+function readData(value: unknown): KapsoProviderData {
+ return isRecord(value) ? { ...(value as KapsoProviderData) } : {};
+}
+
+function compact(data: KapsoProviderData): Record {
+ return Object.fromEntries(
+ Object.entries(data).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
+ );
+}
+
+function formatPhone(phone: string | null | undefined): string | null {
+ if (!phone) return null;
+ const digits = phone.replace(/\D/g, '');
+ return digits ? `+${digits}` : null;
+}
+
+function describe(error: unknown): { name: string; message: string; status?: number } {
+ if (error instanceof KapsoApiError) {
+ return { name: error.name, message: error.message, status: error.status };
+ }
+ return error instanceof Error
+ ? { name: error.name, message: error.message }
+ : { name: 'Unknown', message: String(error) };
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts b/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts
new file mode 100644
index 0000000..30e1b15
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/kapso/templates.ts
@@ -0,0 +1,104 @@
+import type { WhatsappMessageKind } from '@gruperly/shared';
+import { firstNameOf } from '../../lib/render-message';
+import type { WhatsappMessage } from '../messaging-provider';
+import type { MetaTemplateDefinition } from './http';
+
+/**
+ * The message templates submitted to Meta for each teacher's WhatsApp Business
+ * Account. Their bodies follow `lib/render-message.ts` (the OpenWA copy).
+ *
+ * Rules Meta enforces and that are easy to break:
+ * - A submitted template cannot be edited. Changing the copy means a new name
+ * (`gruperly_payment_reminder_v2`) and a new approval round.
+ * - The payment reminder stays UTILITY only while it has no promotional
+ * content; anything that sells turns it into MARKETING (and Meta may
+ * re-categorize it on its own).
+ * - The body cannot start or end with a variable.
+ */
+export const TEMPLATE_LANGUAGE = 'es_AR';
+
+type TemplateSpec = {
+ definition: MetaTemplateDefinition;
+ parameters: (message: WhatsappMessage) => { name: string; text: string }[];
+};
+
+export const KAPSO_TEMPLATES: Record = {
+ PAYMENT_REMINDER: {
+ definition: {
+ name: 'gruperly_payment_reminder',
+ language: TEMPLATE_LANGUAGE,
+ category: 'UTILITY',
+ parameter_format: 'NAMED',
+ components: [
+ {
+ type: 'BODY',
+ text:
+ '¡Hola {{student_name}}! Te recordamos el pago de {{group_name}} por {{amount}}, ' +
+ 'con vencimiento el {{due_date}}. Podés pagarlo desde este link: {{payment_link}} ¡Gracias!',
+ example: {
+ body_text_named_params: [
+ { param_name: 'student_name', example: 'Ana' },
+ { param_name: 'group_name', example: 'Yoga Martes y Jueves' },
+ { param_name: 'amount', example: '$ 25.000' },
+ { param_name: 'due_date', example: '10/11' },
+ { param_name: 'payment_link', example: 'https://mpago.la/2xYz123' },
+ ],
+ },
+ },
+ ],
+ },
+ parameters: (message) =>
+ message.kind === 'PAYMENT_REMINDER'
+ ? [
+ { name: 'student_name', text: firstNameOf(message.studentName) },
+ { name: 'group_name', text: message.groupName },
+ { name: 'amount', text: message.amount },
+ { name: 'due_date', text: message.dueDate },
+ { name: 'payment_link', text: message.paymentLink },
+ ]
+ : [],
+ },
+ REENGAGEMENT: {
+ definition: {
+ name: 'gruperly_reengagement',
+ language: TEMPLATE_LANGUAGE,
+ category: 'MARKETING',
+ parameter_format: 'NAMED',
+ components: [
+ {
+ type: 'BODY',
+ text:
+ '¡Hola {{student_name}}! 👋 Te extrañamos en {{group_name}}. ' +
+ 'Notamos que no asististe a las últimas clases y queremos que vuelvas. ' +
+ 'Si tenés algún problema con tus horarios o tu membresía, escribinos y lo resolvemos juntos.',
+ example: {
+ body_text_named_params: [
+ { param_name: 'student_name', example: 'Ana' },
+ { param_name: 'group_name', example: 'Yoga Martes y Jueves' },
+ ],
+ },
+ },
+ ],
+ },
+ parameters: (message) => [
+ { name: 'student_name', text: firstNameOf(message.studentName) },
+ { name: 'group_name', text: message.groupName },
+ ],
+ },
+};
+
+/** Meta's template status, mapped to ours. Unknown values stay PENDING. */
+export function toTemplateStatus(status: string): 'PENDING' | 'APPROVED' | 'REJECTED' | 'DISABLED' {
+ switch (status.toUpperCase()) {
+ case 'APPROVED':
+ return 'APPROVED';
+ case 'REJECTED':
+ return 'REJECTED';
+ case 'DISABLED':
+ case 'PAUSED':
+ case 'ARCHIVED':
+ return 'DISABLED';
+ default:
+ return 'PENDING';
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts
new file mode 100644
index 0000000..680d610
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts
@@ -0,0 +1,165 @@
+import type { WhatsappAccount } from '@generated/prisma/client';
+import type {
+ ProblemDetails,
+ Result,
+ WhatsappCallbackReason,
+ WhatsappConnectionStart,
+ WhatsappMessageKind,
+ WhatsappReadiness,
+ WhatsappReturnTo,
+} from '@gruperly/shared';
+
+/**
+ * The port every WhatsApp gateway implements. The domain (linking, the weekly
+ * jobs, the webhook) only talks to this interface; everything that knows about
+ * OpenWA or Kapso lives in `providers//`. Switching gateways is a matter of
+ * `WHATSAPP_PROVIDER` plus an adapter, never of touching the jobs or the UI.
+ */
+
+export type MessagingProviderId = 'OPENWA' | 'KAPSO';
+
+export type WhatsappAccountRecord = Pick<
+ WhatsappAccount,
+ 'id' | 'ownerId' | 'provider' | 'status' | 'externalId' | 'displayPhoneNumber' | 'providerData'
+>;
+
+/**
+ * What the teacher receives, in domain terms. Each provider turns it into its
+ * own wire format: free text (OpenWA) or a template with parameters (Kapso).
+ */
+export type WhatsappMessage =
+ | {
+ kind: 'PAYMENT_REMINDER';
+ studentName: string;
+ groupName: string;
+ amount: string;
+ dueDate: string;
+ paymentLink: string;
+ }
+ | {
+ kind: 'REENGAGEMENT';
+ studentName: string;
+ groupName: string;
+ };
+
+export type StartConnectionContext = {
+ ownerId: string;
+ ownerName: string;
+ returnTo: WhatsappReturnTo;
+ /** The teacher's existing row, if any, to reuse provider-side resources. */
+ account: WhatsappAccountRecord | null;
+};
+
+export type StartConnectionResult = {
+ start: WhatsappConnectionStart;
+ /** OpenWA: the session id. Kapso: null until the setup finishes. */
+ externalId: string | null;
+ providerData?: Record | null;
+};
+
+/** The live state of a linking, as the provider reports it. */
+export type ConnectionSnapshot =
+ | { state: 'pending'; qrCode: string | null }
+ | { state: 'active'; displayPhoneNumber: string | null }
+ | { state: 'disconnected'; reason: string | null };
+
+/** The provider-side result of finishing a redirect-based linking (Kapso). */
+export type CompletedConnection = {
+ externalId: string;
+ displayPhoneNumber: string | null;
+ providerData?: Record | null;
+};
+
+export type RecipientResolution =
+ | { ok: true; to: string }
+ | { ok: false; code: 'no_whatsapp' | 'provider_error' };
+
+export type SendOutcome =
+ | { ok: true; providerMessageId: string }
+ | {
+ ok: false;
+ /** Worth trying again on the next run (5xx, network). */
+ retryable: boolean;
+ /** The gateway asked us to stop sending from this account for a while. */
+ rateLimitedForMs?: number;
+ code: string;
+ message: string;
+ };
+
+export type MessageDeliveryStatus = 'SENT' | 'DELIVERED' | 'READ' | 'FAILED';
+
+/** Webhook payloads reduced to the two things the domain cares about. */
+export type NormalizedEvent =
+ | {
+ type: 'connection';
+ /** Session id (OpenWA) or phone_number_id (Kapso). */
+ externalId: string;
+ /** When the provider carries our own reference (Kapso's external customer id). */
+ ownerId?: string;
+ status: 'active' | 'disconnected';
+ displayPhoneNumber?: string | null;
+ providerData?: Record | null;
+ }
+ | {
+ type: 'message_status';
+ providerMessageId: string;
+ status: MessageDeliveryStatus;
+ errorCode?: string | null;
+ errorMessage?: string | null;
+ };
+
+export type ParsedWebhook = {
+ /** The delivery's idempotency key; burned before the events are applied. */
+ dedupeKey: string;
+ events: NormalizedEvent[];
+};
+
+export type WebhookParseError = 'invalid_signature' | 'invalid_payload';
+
+export interface MessagingProvider {
+ readonly id: MessagingProviderId;
+
+ /** Starts (or restarts) linking the teacher's number. */
+ startConnection(
+ context: StartConnectionContext,
+ ): Promise>;
+
+ /** Asks the provider how the linking is going (fresh QR, linked, failed). */
+ refreshConnection(
+ account: WhatsappAccountRecord,
+ ): Promise>;
+
+ /**
+ * Finishes a redirect-based linking from the callback query. Only providers
+ * whose `startConnection` answers `redirect` implement it.
+ */
+ completeRedirect?(
+ account: WhatsappAccountRecord,
+ query: Record,
+ ): Promise>;
+
+ /** Unlinks the number on the provider side. Best effort. */
+ disconnect(account: WhatsappAccountRecord): Promise>;
+
+ /** Runs once the account becomes ACTIVE (Kapso: templates and webhooks). */
+ onConnected?(account: WhatsappAccountRecord): Promise;
+
+ /** Whether a message of this kind can be sent from the account right now. */
+ readiness(account: WhatsappAccountRecord, kind: WhatsappMessageKind): Promise;
+
+ /** Turns an E.164 number into the provider's recipient id, or says it has no WhatsApp. */
+ resolveRecipient(account: WhatsappAccountRecord, e164: string): Promise;
+
+ send(
+ account: WhatsappAccountRecord,
+ to: string,
+ message: WhatsappMessage,
+ idempotencyKey: string,
+ ): Promise;
+
+ /** Verifies the signature over the raw body and normalizes the payload. */
+ parseWebhook(
+ rawBody: string,
+ headers: Headers,
+ ): Result;
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/config.ts b/apps/backend/src/modules/whatsapp/providers/openwa/config.ts
new file mode 100644
index 0000000..c93dc42
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/openwa/config.ts
@@ -0,0 +1,51 @@
+export type OpenWaConfig = {
+ /** Base URL including `/api`, e.g. `http://openwa:2785/api`. */
+ apiUrl: string;
+ /** An OPERATOR key that is not scoped to specific sessions (it creates them). */
+ apiKey: string;
+ /**
+ * Public URL of `/api/v1/whatsapp/webhooks/openwa`. Optional: without it the
+ * linking still works (the status endpoint polls OpenWA) but delivery and
+ * read receipts never reach `outbound_messages`.
+ */
+ webhookUrl: string | null;
+ /** HMAC secret registered with each session webhook (16+ characters). */
+ webhookSecret: string | null;
+};
+
+const MIN_SECRET_LENGTH = 16;
+
+/**
+ * Reads the OpenWA settings. Throws on a deployment mistake, naming the
+ * variables (never their values), like `getMpOAuthConfig()`.
+ */
+export function getOpenWaConfig(): OpenWaConfig {
+ const missing: string[] = [];
+ const read = (name: string, required: boolean): string | null => {
+ const value = process.env[name]?.trim();
+ if (!value) {
+ if (required) missing.push(name);
+ return null;
+ }
+ return value;
+ };
+
+ const apiUrl = read('OPENWA_API_URL', true);
+ const apiKey = read('OPENWA_API_KEY', true);
+ const webhookUrl = read('OPENWA_WEBHOOK_URL', false);
+ const webhookSecret = read('OPENWA_WEBHOOK_SECRET', webhookUrl !== null);
+
+ if (missing.length > 0) {
+ throw new Error(`Missing OpenWA environment variables: ${missing.join(', ')}. See .env.example.`);
+ }
+ if (webhookSecret !== null && webhookSecret.length < MIN_SECRET_LENGTH) {
+ throw new Error(`OPENWA_WEBHOOK_SECRET must be at least ${MIN_SECRET_LENGTH} characters long.`);
+ }
+
+ return {
+ apiUrl: (apiUrl as string).replace(/\/+$/, ''),
+ apiKey: apiKey as string,
+ webhookUrl,
+ webhookSecret,
+ };
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/http.ts b/apps/backend/src/modules/whatsapp/providers/openwa/http.ts
new file mode 100644
index 0000000..ba2f25a
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/openwa/http.ts
@@ -0,0 +1,156 @@
+import type { OpenWaConfig } from './config';
+
+/**
+ * Thin client for the OpenWA REST gateway (rmyndharis/OpenWA). Plain `fetch`:
+ * responses are the raw resource (no `{ data }` envelope) and errors use the
+ * NestJS shape `{ statusCode, message, error, code? }`.
+ */
+
+export class OpenWaApiError extends Error {
+ constructor(
+ readonly status: number,
+ /** OpenWA's stable machine code when it sends one (e.g. `SEND_PACING_LIMITED`). */
+ readonly code: string | null,
+ readonly retryAfterSeconds: number | null = null,
+ ) {
+ super(`OpenWA request failed with ${status}${code ? ` (${code})` : ''}`);
+ this.name = 'OpenWaApiError';
+ }
+}
+
+export type OpenWaSessionStatus =
+ | 'created'
+ | 'initializing'
+ | 'qr_ready'
+ | 'authenticating'
+ | 'ready'
+ | 'disconnected'
+ | 'action_required'
+ | 'failed';
+
+export type OpenWaSession = {
+ id: string;
+ name: string;
+ status: OpenWaSessionStatus;
+ phone: string | null;
+ lastError: string | null;
+ engineLoaded: boolean;
+};
+
+export type OpenWaFetch = (input: string, init?: RequestInit) => Promise;
+
+const REQUEST_TIMEOUT_MS = 30_000;
+
+export class OpenWaClient {
+ constructor(
+ private readonly config: OpenWaConfig,
+ private readonly fetchFn: OpenWaFetch = (input, init) => fetch(input, init),
+ ) {}
+
+ getSession(sessionId: string): Promise {
+ return this.request('GET', `/sessions/${encodeURIComponent(sessionId)}`);
+ }
+
+ async findSessionByName(name: string): Promise {
+ const sessions = await this.request(
+ 'GET',
+ `/sessions?name=${encodeURIComponent(name)}`,
+ );
+ return sessions[0] ?? null;
+ }
+
+ createSession(name: string): Promise {
+ return this.request('POST', '/sessions', { name });
+ }
+
+ startSession(sessionId: string): Promise {
+ return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/start`);
+ }
+
+ logoutSession(sessionId: string): Promise {
+ return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/logout`);
+ }
+
+ async deleteSession(sessionId: string): Promise {
+ await this.request('DELETE', `/sessions/${encodeURIComponent(sessionId)}`);
+ }
+
+ async getQrCode(sessionId: string): Promise {
+ const response = await this.request<{ qrCode?: string | null }>(
+ 'GET',
+ `/sessions/${encodeURIComponent(sessionId)}/qr`,
+ );
+ return response.qrCode ?? null;
+ }
+
+ createWebhook(
+ sessionId: string,
+ body: { url: string; events: string[]; secret: string; retryCount: number },
+ ): Promise<{ id: string }> {
+ return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/webhooks`, body);
+ }
+
+ checkContact(
+ sessionId: string,
+ digits: string,
+ ): Promise<{ exists: boolean; whatsappId: string | null }> {
+ return this.request(
+ 'GET',
+ `/sessions/${encodeURIComponent(sessionId)}/contacts/check/${encodeURIComponent(digits)}`,
+ );
+ }
+
+ sendText(
+ sessionId: string,
+ body: { chatId: string; text: string },
+ idempotencyKey: string,
+ ): Promise<{ messageId: string; timestamp?: number }> {
+ return this.request(
+ 'POST',
+ `/sessions/${encodeURIComponent(sessionId)}/messages/send-text`,
+ body,
+ { 'Idempotency-Key': idempotencyKey },
+ );
+ }
+
+ private async request(
+ method: string,
+ path: string,
+ body?: unknown,
+ extraHeaders: Record = {},
+ ): Promise {
+ const response = await this.fetchFn(`${this.config.apiUrl}${path}`, {
+ method,
+ headers: {
+ 'X-API-Key': this.config.apiKey,
+ Accept: 'application/json',
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
+ ...extraHeaders,
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+
+ if (!response.ok) {
+ const payload = (await response.json().catch(() => null)) as {
+ code?: unknown;
+ retryAfterSeconds?: unknown;
+ } | null;
+ const retryAfterHeader = Number(response.headers.get('Retry-After'));
+ const retryAfterSeconds =
+ typeof payload?.retryAfterSeconds === 'number'
+ ? payload.retryAfterSeconds
+ : Number.isFinite(retryAfterHeader) && retryAfterHeader > 0
+ ? retryAfterHeader
+ : null;
+ throw new OpenWaApiError(
+ response.status,
+ typeof payload?.code === 'string' ? payload.code : null,
+ retryAfterSeconds,
+ );
+ }
+
+ if (response.status === 204) return undefined as T;
+ return (await response.json()) as T;
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/index.ts b/apps/backend/src/modules/whatsapp/providers/openwa/index.ts
new file mode 100644
index 0000000..0638de5
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/providers/openwa/index.ts
@@ -0,0 +1,374 @@
+import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared';
+import { err, ok } from '@gruperly/shared';
+import { whatsappProviderErrorProblem } from '@/http/problem-builders';
+import { logger } from '@/logger';
+import { verifyHmacSha256 } from '../../lib/hmac';
+import { renderMessage } from '../../lib/render-message';
+import type {
+ ConnectionSnapshot,
+ MessageDeliveryStatus,
+ MessagingProvider,
+ NormalizedEvent,
+ ParsedWebhook,
+ RecipientResolution,
+ SendOutcome,
+ StartConnectionContext,
+ StartConnectionResult,
+ WebhookParseError,
+ WhatsappAccountRecord,
+ WhatsappMessage,
+} from '../messaging-provider';
+import type { OpenWaConfig } from './config';
+import { OpenWaApiError, OpenWaClient, type OpenWaFetch, type OpenWaSession } from './http';
+
+/** Events each session webhook subscribes to. */
+export const OPENWA_WEBHOOK_EVENTS = [
+ 'session.status',
+ 'session.authenticated',
+ 'session.disconnected',
+ 'message.ack',
+ 'message.failed',
+];
+
+const WEBHOOK_RETRY_COUNT = 3;
+/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */
+const DEFAULT_RATE_LIMIT_MS = 60_000;
+
+const PENDING_STATUSES = new Set(['created', 'initializing', 'qr_ready', 'authenticating']);
+
+/** One OpenWA session per teacher. Names allow letters, digits and hyphens (3-50). */
+export function openWaSessionName(ownerId: string): string {
+ return `gruperly-${ownerId.replace(/[^a-zA-Z0-9-]/g, '')}`.slice(0, 50);
+}
+
+type OpenWaProviderDeps = { fetch?: OpenWaFetch };
+
+/**
+ * OpenWA (self-hosted, unofficial WhatsApp Web gateway) for the MVP.
+ *
+ * The teacher links their own WhatsApp as a "linked device" by scanning a QR
+ * code shown inside Gruperly; messages are free text sent from that session.
+ * It is not Meta's official API: see `docs/whatsapp.md` for the ban risk and
+ * why sends are paced.
+ */
+export class OpenWaProvider implements MessagingProvider {
+ readonly id = 'OPENWA' as const;
+ private readonly client: OpenWaClient;
+
+ constructor(
+ private readonly config: OpenWaConfig,
+ deps: OpenWaProviderDeps = {},
+ ) {
+ this.client = new OpenWaClient(config, deps.fetch);
+ }
+
+ async startConnection(
+ context: StartConnectionContext,
+ ): Promise> {
+ const previous =
+ context.account?.provider === 'OPENWA' ? context.account : null;
+ const previousData = readData(previous?.providerData);
+
+ try {
+ let session = previous?.externalId ? await this.findSession(previous.externalId) : null;
+ let webhookId = session ? previousData.webhookId ?? null : null;
+
+ if (!session) {
+ session = await this.createOrAdoptSession(openWaSessionName(context.ownerId));
+ webhookId = null;
+ }
+
+ if (!webhookId) {
+ webhookId = await this.registerWebhook(session.id);
+ }
+
+ // Linking again from an already linked session (e.g. to change number):
+ // unlink first so WhatsApp hands out a fresh QR code.
+ if (session.status === 'ready' && session.engineLoaded) {
+ session = await this.client.logoutSession(session.id).catch(() => session as OpenWaSession);
+ }
+
+ if (!session.engineLoaded || session.status === 'disconnected' || session.status === 'failed') {
+ session = await this.client.startSession(session.id).catch((error: unknown) => {
+ // 400 = already started / starting: fine, the QR is on its way.
+ if (error instanceof OpenWaApiError && error.status === 400) return session as OpenWaSession;
+ throw error;
+ });
+ }
+
+ return ok({
+ start: { type: 'qr', qrCode: await this.tryQrCode(session.id) },
+ externalId: session.id,
+ providerData: {
+ sessionName: session.name,
+ ...(webhookId ? { webhookId } : {}),
+ },
+ });
+ } catch (error) {
+ logger.error({ err: describe(error) }, 'OpenWA could not start a session');
+ return err(whatsappProviderErrorProblem());
+ }
+ }
+
+ async refreshConnection(
+ account: WhatsappAccountRecord,
+ ): Promise> {
+ if (!account.externalId) return ok({ state: 'disconnected', reason: 'no_session' });
+
+ try {
+ const session = await this.findSession(account.externalId);
+ if (!session) return ok({ state: 'disconnected', reason: 'session_not_found' });
+
+ if (session.status === 'ready') {
+ return ok({ state: 'active', displayPhoneNumber: formatPhone(session.phone) });
+ }
+ if (PENDING_STATUSES.has(session.status)) {
+ const qrCode = session.status === 'qr_ready' ? await this.tryQrCode(session.id) : null;
+ return ok({ state: 'pending', qrCode });
+ }
+ // A `disconnected` session whose engine is still loaded is backing off
+ // before an automatic reconnect: not a failure yet.
+ if (session.status === 'disconnected' && session.engineLoaded) {
+ return ok({ state: 'pending', qrCode: null });
+ }
+ return ok({ state: 'disconnected', reason: session.lastError ?? session.status });
+ } catch (error) {
+ logger.warn({ err: describe(error) }, 'OpenWA session status lookup failed');
+ return err(whatsappProviderErrorProblem());
+ }
+ }
+
+ async disconnect(account: WhatsappAccountRecord): Promise> {
+ if (!account.externalId) return ok(undefined);
+ const sessionId = account.externalId;
+
+ // `logout` unlinks the device from the teacher's phone; `delete` alone
+ // would leave it listed under "Linked devices". Both are best effort: the
+ // local row is unlinked either way.
+ try {
+ await this.client.logoutSession(sessionId);
+ } catch (error) {
+ logger.warn({ err: describe(error) }, 'OpenWA logout did not complete');
+ }
+ try {
+ await this.client.deleteSession(sessionId);
+ } catch (error) {
+ if (!(error instanceof OpenWaApiError && error.status === 404)) {
+ logger.warn({ err: describe(error) }, 'OpenWA session delete did not complete');
+ }
+ }
+ return ok(undefined);
+ }
+
+ async readiness(account: WhatsappAccountRecord): Promise {
+ return account.status === 'ACTIVE' ? 'ready' : 'blocked';
+ }
+
+ async resolveRecipient(
+ account: WhatsappAccountRecord,
+ e164: string,
+ ): Promise {
+ if (!account.externalId) return { ok: false, code: 'provider_error' };
+ try {
+ // The canonical id WhatsApp knows the number by. It also settles the
+ // Argentine "9" after the country code, which differs per account.
+ const contact = await this.client.checkContact(account.externalId, e164.replace(/\D/g, ''));
+ return contact.exists && contact.whatsappId
+ ? { ok: true, to: contact.whatsappId }
+ : { ok: false, code: 'no_whatsapp' };
+ } catch (error) {
+ logger.warn({ err: describe(error) }, 'OpenWA contact check failed');
+ return { ok: false, code: 'provider_error' };
+ }
+ }
+
+ async send(
+ account: WhatsappAccountRecord,
+ to: string,
+ message: WhatsappMessage,
+ idempotencyKey: string,
+ ): Promise {
+ if (!account.externalId) {
+ return { ok: false, retryable: false, code: 'no_session', message: 'Account has no session' };
+ }
+
+ try {
+ const response = await this.client.sendText(
+ account.externalId,
+ { chatId: to, text: renderMessage(message) },
+ idempotencyKey,
+ );
+ return { ok: true, providerMessageId: response.messageId };
+ } catch (error) {
+ return toSendFailure(error);
+ }
+ }
+
+ parseWebhook(rawBody: string, headers: Headers): Result {
+ const secret = this.config.webhookSecret;
+ if (!secret || !verifyHmacSha256(rawBody, headers.get('X-OpenWA-Signature'), secret, 'sha256=')) {
+ return err('invalid_signature');
+ }
+
+ let payload: OpenWaWebhookPayload;
+ try {
+ payload = JSON.parse(rawBody) as OpenWaWebhookPayload;
+ } catch {
+ return err('invalid_payload');
+ }
+
+ const dedupeKey =
+ headers.get('X-OpenWA-Idempotency-Key') ?? payload.idempotencyKey ?? payload.deliveryId;
+ if (!dedupeKey || typeof payload.event !== 'string') return err('invalid_payload');
+
+ return ok({ dedupeKey, events: toEvents(payload) });
+ }
+
+ private async findSession(sessionId: string): Promise {
+ try {
+ return await this.client.getSession(sessionId);
+ } catch (error) {
+ if (error instanceof OpenWaApiError && error.status === 404) return null;
+ throw error;
+ }
+ }
+
+ /** Creates the teacher's session, or adopts it if one with that name survived. */
+ private async createOrAdoptSession(name: string): Promise {
+ try {
+ return await this.client.createSession(name);
+ } catch (error) {
+ if (error instanceof OpenWaApiError && error.status === 409) {
+ const existing = await this.client.findSessionByName(name);
+ if (existing) return existing;
+ }
+ throw error;
+ }
+ }
+
+ private async registerWebhook(sessionId: string): Promise {
+ if (!this.config.webhookUrl || !this.config.webhookSecret) return null;
+ try {
+ const webhook = await this.client.createWebhook(sessionId, {
+ url: this.config.webhookUrl,
+ events: OPENWA_WEBHOOK_EVENTS,
+ secret: this.config.webhookSecret,
+ retryCount: WEBHOOK_RETRY_COUNT,
+ });
+ return webhook.id;
+ } catch (error) {
+ // Without the webhook the linking still works through polling; only the
+ // delivery receipts are lost. Not worth failing the teacher's click.
+ logger.warn({ err: describe(error) }, 'OpenWA webhook registration failed');
+ return null;
+ }
+ }
+
+ private async tryQrCode(sessionId: string): Promise {
+ try {
+ return await this.client.getQrCode(sessionId);
+ } catch {
+ // 400 while the engine is still starting: the next status poll brings it.
+ return null;
+ }
+ }
+}
+
+type OpenWaWebhookPayload = {
+ event?: unknown;
+ sessionId?: string;
+ idempotencyKey?: string;
+ deliveryId?: string;
+ data?: Record;
+};
+
+const ACK_STATUSES: Record = {
+ sent: 'SENT',
+ delivered: 'DELIVERED',
+ read: 'READ',
+ played: 'READ',
+ failed: 'FAILED',
+};
+
+function toEvents(payload: OpenWaWebhookPayload): NormalizedEvent[] {
+ const data = payload.data ?? {};
+ const sessionId = (typeof data.sessionId === 'string' ? data.sessionId : null) ?? payload.sessionId;
+
+ switch (payload.event) {
+ case 'session.authenticated':
+ return sessionId
+ ? [
+ {
+ type: 'connection',
+ externalId: sessionId,
+ status: 'active',
+ displayPhoneNumber: formatPhone(typeof data.phone === 'string' ? data.phone : null),
+ },
+ ]
+ : [];
+ case 'session.status':
+ if (!sessionId) return [];
+ if (data.status === 'ready') return [{ type: 'connection', externalId: sessionId, status: 'active' }];
+ if (data.status === 'failed') {
+ return [{ type: 'connection', externalId: sessionId, status: 'disconnected' }];
+ }
+ return [];
+ case 'session.disconnected':
+ return sessionId ? [{ type: 'connection', externalId: sessionId, status: 'disconnected' }] : [];
+ case 'message.ack':
+ case 'message.failed': {
+ const status = ACK_STATUSES[String(data.status ?? (payload.event === 'message.failed' ? 'failed' : ''))];
+ const messageId = typeof data.messageId === 'string' ? data.messageId : null;
+ if (!status || !messageId) return [];
+ return [
+ {
+ type: 'message_status',
+ providerMessageId: messageId,
+ status,
+ errorCode: status === 'FAILED' ? 'delivery_failed' : null,
+ },
+ ];
+ }
+ default:
+ return [];
+ }
+}
+
+function toSendFailure(error: unknown): SendOutcome {
+ if (error instanceof OpenWaApiError) {
+ if (error.status === 429) {
+ return {
+ ok: false,
+ retryable: true,
+ rateLimitedForMs: error.retryAfterSeconds ? error.retryAfterSeconds * 1000 : DEFAULT_RATE_LIMIT_MS,
+ code: error.code ?? 'rate_limited',
+ message: error.message,
+ };
+ }
+ // 4xx: the session is not active, the body was refused, the key reused…
+ // none of them gets better by repeating the same request.
+ const retryable = error.status >= 500 || error.status === 409;
+ return { ok: false, retryable, code: error.code ?? `http_${error.status}`, message: error.message };
+ }
+ return { ok: false, retryable: true, code: 'network_error', message: describe(error).message };
+}
+
+function readData(value: unknown): Record {
+ return value && typeof value === 'object' ? (value as Record) : {};
+}
+
+function formatPhone(phone: string | null | undefined): string | null {
+ if (!phone) return null;
+ const digits = phone.replace(/\D/g, '');
+ return digits ? `+${digits}` : null;
+}
+
+/** Errors are logged by name and status only: request bodies may hold phone numbers. */
+function describe(error: unknown): { name: string; message: string; status?: number } {
+ if (error instanceof OpenWaApiError) {
+ return { name: error.name, message: error.message, status: error.status };
+ }
+ return error instanceof Error
+ ? { name: error.name, message: error.message }
+ : { name: 'Unknown', message: String(error) };
+}
diff --git a/apps/backend/src/modules/whatsapp/routes.ts b/apps/backend/src/modules/whatsapp/routes.ts
new file mode 100644
index 0000000..83d3230
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/routes.ts
@@ -0,0 +1,18 @@
+import { Hono } from 'hono';
+import callbackRoute from './features/callback/route';
+import connectRoute from './features/connect/route';
+import disconnectRoute from './features/disconnect/route';
+import statusRoute from './features/status/route';
+import webhookRoute from './features/webhook/route';
+
+const routes = new Hono();
+
+// Same trick as `mp`: `disconnectRoute` only declares `DELETE /`, so mounting
+// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`.
+routes.route('/connect', connectRoute);
+routes.route('/connect', disconnectRoute);
+routes.route('/status', statusRoute);
+routes.route('/callback', callbackRoute);
+routes.route('/webhooks', webhookRoute);
+
+export default routes;
diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts
index ad88a40..8e0a7ae 100644
--- a/apps/backend/src/server.ts
+++ b/apps/backend/src/server.ts
@@ -3,6 +3,7 @@ import { getPrismaClient } from '@/lib/prisma';
import { logger } from '@/logger';
import { startMpJobs } from '@/modules/mp';
import { startPaymentJobs } from '@/modules/payments';
+import { startWhatsappJobs } from '@/modules/whatsapp';
const port = Number(process.env.PORT ?? 4000);
@@ -15,6 +16,7 @@ const server = Bun.serve({
startMpJobs();
startPaymentJobs();
+startWhatsappJobs();
async function shutdown(): Promise {
server.stop(true);
diff --git a/apps/backend/test/groups.test.ts b/apps/backend/test/groups.test.ts
index 6104538..bdca845 100644
--- a/apps/backend/test/groups.test.ts
+++ b/apps/backend/test/groups.test.ts
@@ -40,6 +40,8 @@ const group = {
billingType: null,
dueDay: null,
inviteToken: null,
+ autoPaymentReminders: false,
+ autoReengagement: false,
};
function makeApp(userValue: unknown) {
diff --git a/apps/backend/test/onboarding.test.ts b/apps/backend/test/onboarding.test.ts
index fa9e8e7..a103418 100644
--- a/apps/backend/test/onboarding.test.ts
+++ b/apps/backend/test/onboarding.test.ts
@@ -9,6 +9,9 @@ const db = {
mpAccount: {
findUnique: mock(),
},
+ whatsappAccount: {
+ findUnique: mock(async () => null),
+ },
group: {
create: mock(),
},
@@ -54,6 +57,8 @@ const group = {
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
+ autoPaymentReminders: false,
+ autoReengagement: false,
};
const firstGroupPayload = {
@@ -83,6 +88,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'NOT_STARTED',
paymentConnected: false,
+ whatsappConnected: false,
completed: false,
});
});
@@ -97,6 +103,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'PAYMENT_CONNECTED',
paymentConnected: true,
+ whatsappConnected: false,
completed: false,
});
});
@@ -115,6 +122,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'NOT_STARTED',
paymentConnected: false,
+ whatsappConnected: false,
completed: false,
});
});
@@ -128,6 +136,7 @@ describe('onboarding routes', () => {
expect(await res.json()).toEqual({
step: 'COMPLETED',
paymentConnected: true,
+ whatsappConnected: false,
completed: true,
});
});
@@ -166,6 +175,8 @@ describe('onboarding routes', () => {
price: 150.5,
billingType: 'MONTHLY',
dueDay: 5,
+ autoPaymentReminders: false,
+ autoReengagement: false,
},
onboardingCompleted: true,
});
diff --git a/apps/backend/test/session-auth.test.ts b/apps/backend/test/session-auth.test.ts
index 760e2c9..2faca6f 100644
--- a/apps/backend/test/session-auth.test.ts
+++ b/apps/backend/test/session-auth.test.ts
@@ -50,6 +50,17 @@ describe('session auth', () => {
).toBe(false);
});
+ it('classifies the WhatsApp provider webhooks as public (signature-based)', () => {
+ expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/openwa')).toBe(true);
+ expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/kapso/')).toBe(true);
+ // Everything else under /whatsapp needs the teacher's session.
+ expect(isPublicApiRequest('GET', '/api/v1/whatsapp/webhooks/openwa')).toBe(false);
+ expect(isPublicApiRequest('POST', '/api/v1/whatsapp/webhooks/other')).toBe(false);
+ expect(isPublicApiRequest('GET', '/api/v1/whatsapp/status')).toBe(false);
+ expect(isPublicApiRequest('POST', '/api/v1/whatsapp/connect')).toBe(false);
+ expect(isPublicApiRequest('GET', '/api/v1/whatsapp/callback')).toBe(false);
+ });
+
it('allows public requests without a session', async () => {
const app = new Hono();
app.use('*', sessionAuthMiddleware);
diff --git a/apps/backend/test/whatsapp-core.test.ts b/apps/backend/test/whatsapp-core.test.ts
new file mode 100644
index 0000000..e0f120e
--- /dev/null
+++ b/apps/backend/test/whatsapp-core.test.ts
@@ -0,0 +1,590 @@
+import { beforeEach, describe, expect, it, mock } from 'bun:test';
+import { ok } from '@gruperly/shared';
+import { CompleteWhatsappSetup } from '@/modules/whatsapp/features/callback/use-case';
+import { StartWhatsappConnection } from '@/modules/whatsapp/features/connect/use-case';
+import { DisconnectWhatsapp } from '@/modules/whatsapp/features/disconnect/use-case';
+import { GetWhatsappStatus } from '@/modules/whatsapp/features/status/use-case';
+import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
+import { HandleWhatsappWebhook } from '@/modules/whatsapp/features/webhook/use-case';
+import { toVisibleWhatsappStatus } from '@/modules/whatsapp/lib/account';
+import type {
+ MessagingProvider,
+ NormalizedEvent,
+} from '@/modules/whatsapp/providers/messaging-provider';
+
+/* The domain side of WhatsApp, driven through a fake provider: these tests pin
+ what the use cases do with whatever any provider answers, so they do not
+ change when an adapter does. Dependencies go in through constructors (no
+ `mock.module`), as AGENTS.md asks for provider code. */
+
+const ownerId = 'user-1';
+const now = new Date('2026-10-19T13:00:00.000Z');
+
+function fakeProvider(overrides: Partial = {}): MessagingProvider {
+ return {
+ id: 'OPENWA',
+ startConnection: mock(async () =>
+ ok({
+ start: { type: 'qr' as const, qrCode: 'data:image/png;base64,QR1' },
+ externalId: 'session-1',
+ providerData: { sessionName: 'gruperly-user-1' },
+ }),
+ ),
+ refreshConnection: mock(async () => ok({ state: 'pending' as const, qrCode: 'data:QR2' })),
+ disconnect: mock(async () => ok(undefined)),
+ readiness: mock(async () => 'ready' as const),
+ resolveRecipient: mock(async (_account, e164: string) => ({ ok: true as const, to: e164 })),
+ send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })),
+ parseWebhook: mock(() => ok({ dedupeKey: 'delivery-1', events: [] as NormalizedEvent[] })),
+ ...overrides,
+ } as MessagingProvider;
+}
+
+function account(overrides: Record = {}) {
+ return {
+ id: 'wa-1',
+ ownerId,
+ provider: 'OPENWA',
+ status: 'PENDING',
+ externalId: 'session-1',
+ displayPhoneNumber: null,
+ providerData: { sessionName: 'gruperly-user-1' },
+ connectedAt: null,
+ ...overrides,
+ };
+}
+
+function makeDb() {
+ return {
+ whatsappAccount: {
+ findUnique: mock(),
+ findFirst: mock(),
+ upsert: mock(async () => ({})),
+ update: mock(async ({ data }: { data: Record }) => account({ ...data })),
+ },
+ whatsappWebhookEvent: {
+ create: mock(async () => ({})),
+ delete: mock(async () => ({})),
+ },
+ outboundMessage: {
+ updateMany: mock(async () => ({ count: 1 })),
+ },
+ group: {
+ findUnique: mock(),
+ update: mock(),
+ },
+ };
+}
+
+type Db = ReturnType;
+let db: Db;
+
+beforeEach(() => {
+ db = makeDb();
+});
+
+describe('visible WhatsApp status', () => {
+ it('maps rows of the active provider', () => {
+ expect(toVisibleWhatsappStatus(null, 'OPENWA')).toBe('none');
+ expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'PENDING' }, 'OPENWA')).toBe('pending');
+ expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'OPENWA')).toBe('active');
+ expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'OPENWA')).toBe(
+ 'disconnected',
+ );
+ });
+
+ it('asks to reconnect an account linked with another provider', () => {
+ expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'ACTIVE' }, 'KAPSO')).toBe(
+ 'requires_reconnect',
+ );
+ expect(toVisibleWhatsappStatus({ provider: 'OPENWA', status: 'DISCONNECTED' }, 'KAPSO')).toBe('none');
+ });
+});
+
+describe('start connection', () => {
+ it('stores a PENDING account and hands the QR to the browser', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(null);
+ const provider = fakeProvider();
+
+ const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
+ { id: ownerId, name: 'Ana Profe' },
+ 'onboarding',
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ value: { start: { type: 'qr', qrCode: 'data:image/png;base64,QR1' } },
+ });
+ expect(provider.startConnection).toHaveBeenCalledWith({
+ ownerId,
+ ownerName: 'Ana Profe',
+ returnTo: 'onboarding',
+ account: null,
+ });
+ const upsert = db.whatsappAccount.upsert.mock.calls[0]?.[0] as {
+ create: Record;
+ update: Record;
+ };
+ expect(upsert.create).toMatchObject({
+ ownerId,
+ provider: 'OPENWA',
+ status: 'PENDING',
+ externalId: 'session-1',
+ });
+ expect(upsert.update).toMatchObject({ status: 'PENDING', connectedAt: null });
+ });
+
+ it('passes the redirect through for hosted linkings', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(null);
+ const provider = fakeProvider({
+ id: 'KAPSO',
+ startConnection: mock(async () =>
+ ok({
+ start: { type: 'redirect' as const, url: 'https://app.kapso.ai/whatsapp/setup/abc' },
+ externalId: null,
+ providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
+ }),
+ ),
+ });
+
+ const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
+ { id: ownerId, name: 'Ana' },
+ 'settings',
+ );
+
+ expect(result.ok && result.value.start).toEqual({
+ type: 'redirect',
+ url: 'https://app.kapso.ai/whatsapp/setup/abc',
+ });
+ });
+
+ it('does not touch the account when the provider fails', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(null);
+ const provider = fakeProvider({
+ startConnection: mock(async () => ({
+ ok: false as const,
+ error: { type: 'x', title: 'Bad Gateway', status: 502, code: 'whatsapp_provider_error' },
+ })),
+ });
+
+ const result = await new StartWhatsappConnection({ db: db as never, provider }).execute(
+ { id: ownerId, name: 'Ana' },
+ 'settings',
+ );
+
+ expect(result.ok).toBe(false);
+ expect(db.whatsappAccount.upsert).not.toHaveBeenCalled();
+ });
+});
+
+describe('status', () => {
+ it('reports no account', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(null);
+
+ const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute(
+ ownerId,
+ );
+
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ status: 'none',
+ provider: 'OPENWA',
+ displayPhoneNumber: null,
+ connectedAt: null,
+ qrCode: null,
+ readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' },
+ },
+ });
+ });
+
+ it('returns the fresh QR while the linking is pending', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account());
+
+ const result = await new GetWhatsappStatus({ db: db as never, provider: fakeProvider() }).execute(
+ ownerId,
+ );
+
+ expect(result.ok && result.value).toMatchObject({ status: 'pending', qrCode: 'data:QR2' });
+ expect(db.whatsappAccount.update).not.toHaveBeenCalled();
+ });
+
+ it('activates the account once the provider reports it linked', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account());
+ const onConnected = mock(async () => undefined);
+ const provider = fakeProvider({
+ refreshConnection: mock(async () =>
+ ok({ state: 'active' as const, displayPhoneNumber: '+5491123456789' }),
+ ),
+ onConnected,
+ });
+
+ const result = await new GetWhatsappStatus({ db: db as never, provider, now: () => now }).execute(
+ ownerId,
+ );
+
+ expect(db.whatsappAccount.update).toHaveBeenCalledWith({
+ where: { id: 'wa-1' },
+ data: { status: 'ACTIVE', connectedAt: now, displayPhoneNumber: '+5491123456789' },
+ });
+ expect(onConnected).toHaveBeenCalledTimes(1);
+ expect(result.ok && result.value).toMatchObject({
+ status: 'active',
+ displayPhoneNumber: '+5491123456789',
+ connectedAt: now.toISOString(),
+ readiness: { PAYMENT_REMINDER: 'ready', REENGAGEMENT: 'ready' },
+ });
+ });
+
+ it('marks a failed linking as disconnected', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account());
+ const provider = fakeProvider({
+ refreshConnection: mock(async () => ok({ state: 'disconnected' as const, reason: 'failed' })),
+ });
+
+ const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
+
+ expect(db.whatsappAccount.update).toHaveBeenCalledWith({
+ where: { id: 'wa-1' },
+ data: { status: 'DISCONNECTED' },
+ });
+ expect(result.ok && result.value.status).toBe('disconnected');
+ });
+
+ it('does not poll the provider for an account linked elsewhere', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO', status: 'ACTIVE' }));
+ const provider = fakeProvider();
+
+ const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
+
+ expect(provider.refreshConnection).not.toHaveBeenCalled();
+ expect(result.ok && result.value).toMatchObject({
+ status: 'requires_reconnect',
+ readiness: { PAYMENT_REMINDER: 'blocked', REENGAGEMENT: 'blocked' },
+ });
+ });
+
+ it('reports a template still under review', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
+ const provider = fakeProvider({
+ readiness: mock(async (_account, kind) => (kind === 'REENGAGEMENT' ? 'pending' : 'ready')),
+ });
+
+ const result = await new GetWhatsappStatus({ db: db as never, provider }).execute(ownerId);
+
+ expect(result.ok && result.value.readiness).toEqual({
+ PAYMENT_REMINDER: 'ready',
+ REENGAGEMENT: 'pending',
+ });
+ });
+});
+
+describe('disconnect', () => {
+ it('unlinks on the provider and frees the number locally', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
+ const provider = fakeProvider();
+
+ const result = await new DisconnectWhatsapp({ db: db as never, provider }).execute(ownerId);
+
+ expect(result).toEqual({ ok: true, value: { disconnected: true } });
+ expect(provider.disconnect).toHaveBeenCalledTimes(1);
+ expect(db.whatsappAccount.update).toHaveBeenCalledWith({
+ where: { id: 'wa-1' },
+ data: { status: 'DISCONNECTED', externalId: null, displayPhoneNumber: null, connectedAt: null },
+ });
+ });
+
+ it('is a no-op without a linked account', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(null);
+
+ const result = await new DisconnectWhatsapp({ db: db as never, provider: fakeProvider() }).execute(
+ ownerId,
+ );
+
+ expect(result).toEqual({ ok: true, value: { disconnected: false } });
+ expect(db.whatsappAccount.update).not.toHaveBeenCalled();
+ });
+});
+
+describe('redirect callback', () => {
+ it('activates the account the provider confirmed', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(
+ account({ provider: 'KAPSO', externalId: null, providerData: { customerId: 'cust-1' } }),
+ );
+ const provider = fakeProvider({
+ id: 'KAPSO',
+ completeRedirect: mock(async () =>
+ ok({
+ externalId: 'phone-1',
+ displayPhoneNumber: '+5491100000000',
+ providerData: { businessAccountId: 'waba-1' },
+ }),
+ ),
+ });
+
+ const outcome = await new CompleteWhatsappSetup({ db: db as never, provider, now: () => now }).execute(
+ ownerId,
+ { setup_link_id: 'link-1', phone_number_id: 'phone-1', status: 'completed' },
+ );
+
+ expect(outcome).toEqual({ kind: 'success' });
+ expect(db.whatsappAccount.update).toHaveBeenCalledWith({
+ where: { id: 'wa-1' },
+ data: {
+ status: 'ACTIVE',
+ connectedAt: now,
+ externalId: 'phone-1',
+ displayPhoneNumber: '+5491100000000',
+ providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' },
+ },
+ });
+ });
+
+ it('reports a number already linked to someone else', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account({ provider: 'KAPSO' }));
+ db.whatsappAccount.update.mockRejectedValueOnce(Object.assign(new Error('unique'), { code: 'P2002' }));
+ const provider = fakeProvider({
+ id: 'KAPSO',
+ completeRedirect: mock(async () => ok({ externalId: 'phone-1', displayPhoneNumber: null })),
+ });
+
+ const outcome = await new CompleteWhatsappSetup({ db: db as never, provider }).execute(ownerId, {});
+
+ expect(outcome).toEqual({ kind: 'error', reason: 'number_in_use' });
+ });
+
+ it('refuses a provider without hosted linking', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account());
+
+ const outcome = await new CompleteWhatsappSetup({ db: db as never, provider: fakeProvider() }).execute(
+ ownerId,
+ {},
+ );
+
+ expect(outcome).toEqual({ kind: 'error', reason: 'invalid_setup' });
+ });
+});
+
+describe('webhook', () => {
+ const headers = new Headers();
+
+ it('rejects an invalid signature before touching the database', async () => {
+ const provider = fakeProvider({
+ parseWebhook: mock(() => ({ ok: false as const, error: 'invalid_signature' as const })),
+ });
+
+ const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute(
+ 'OPENWA',
+ '{}',
+ headers,
+ );
+
+ expect(result).toEqual({ ok: false, error: 'invalid_signature' });
+ expect(db.whatsappWebhookEvent.create).not.toHaveBeenCalled();
+ });
+
+ it('ignores a delivery it already processed', async () => {
+ db.whatsappWebhookEvent.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' }));
+ const provider = fakeProvider({
+ parseWebhook: mock(() =>
+ ok({
+ dedupeKey: 'delivery-1',
+ events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }],
+ }),
+ ),
+ });
+
+ const result = await new HandleWhatsappWebhook({ db: db as never, provider }).execute(
+ 'OPENWA',
+ '{}',
+ headers,
+ );
+
+ expect(result).toEqual({ ok: true, value: { duplicate: true, applied: 0 } });
+ expect(db.outboundMessage.updateMany).not.toHaveBeenCalled();
+ });
+
+ it('advances a message status without moving it backwards', async () => {
+ const provider = fakeProvider({
+ parseWebhook: mock(() =>
+ ok({
+ dedupeKey: 'delivery-2',
+ events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'DELIVERED' as const }],
+ }),
+ ),
+ });
+
+ await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
+
+ expect(db.whatsappWebhookEvent.create).toHaveBeenCalledWith({
+ data: { provider: 'OPENWA', dedupeKey: 'delivery-2' },
+ });
+ expect(db.outboundMessage.updateMany).toHaveBeenCalledWith({
+ where: {
+ provider: 'OPENWA',
+ providerMessageId: 'wamid-1',
+ status: { in: ['QUEUED', 'SENT'] },
+ },
+ data: { status: 'DELIVERED' },
+ });
+ });
+
+ it('records why a message failed', async () => {
+ const provider = fakeProvider({
+ parseWebhook: mock(() =>
+ ok({
+ dedupeKey: 'delivery-3',
+ events: [
+ {
+ type: 'message_status' as const,
+ providerMessageId: 'wamid-1',
+ status: 'FAILED' as const,
+ errorCode: '131026',
+ errorMessage: 'Message undeliverable',
+ },
+ ],
+ }),
+ ),
+ });
+
+ await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
+
+ expect(db.outboundMessage.updateMany.mock.calls[0]?.[0]).toMatchObject({
+ data: { status: 'FAILED', errorCode: '131026', errorMessage: 'Message undeliverable' },
+ });
+ });
+
+ it('activates the account a connection event names and runs the setup once', async () => {
+ db.whatsappAccount.findFirst.mockResolvedValueOnce(account());
+ const onConnected = mock(async () => undefined);
+ const provider = fakeProvider({
+ onConnected,
+ parseWebhook: mock(() =>
+ ok({
+ dedupeKey: 'delivery-4',
+ events: [
+ {
+ type: 'connection' as const,
+ externalId: 'session-1',
+ status: 'active' as const,
+ displayPhoneNumber: '+5491123456789',
+ },
+ ],
+ }),
+ ),
+ });
+
+ const result = await new HandleWhatsappWebhook({ db: db as never, provider, now: () => now }).execute(
+ 'OPENWA',
+ '{}',
+ headers,
+ );
+
+ expect(result).toEqual({ ok: true, value: { duplicate: false, applied: 1 } });
+ expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({
+ where: { id: 'wa-1' },
+ data: { status: 'ACTIVE', connectedAt: now, externalId: 'session-1' },
+ });
+ expect(onConnected).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to the owner reference when the number is new to us', async () => {
+ db.whatsappAccount.findFirst.mockResolvedValueOnce(null).mockResolvedValueOnce(account({ provider: 'KAPSO' }));
+ const provider = fakeProvider({
+ id: 'KAPSO',
+ parseWebhook: mock(() =>
+ ok({
+ dedupeKey: 'delivery-5',
+ events: [{ type: 'connection' as const, externalId: 'phone-1', ownerId, status: 'active' as const }],
+ }),
+ ),
+ });
+
+ await new HandleWhatsappWebhook({ db: db as never, provider }).execute('KAPSO', '{}', headers);
+
+ expect(db.whatsappAccount.findFirst.mock.calls[1]?.[0]).toEqual({
+ where: { provider: 'KAPSO', ownerId, status: { not: 'DISCONNECTED' } },
+ });
+ expect(db.whatsappAccount.update.mock.calls[0]?.[0]).toMatchObject({
+ data: { status: 'ACTIVE', externalId: 'phone-1' },
+ });
+ });
+
+ it('marks an unlinked number as disconnected', async () => {
+ db.whatsappAccount.findFirst.mockResolvedValueOnce(account({ status: 'ACTIVE' }));
+ const provider = fakeProvider({
+ parseWebhook: mock(() =>
+ ok({
+ dedupeKey: 'delivery-6',
+ events: [{ type: 'connection' as const, externalId: 'session-1', status: 'disconnected' as const }],
+ }),
+ ),
+ });
+
+ await new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers);
+
+ expect(db.whatsappAccount.update).toHaveBeenCalledWith({
+ where: { id: 'wa-1' },
+ data: { status: 'DISCONNECTED' },
+ });
+ });
+
+ it('un-burns the delivery when applying it fails, so the retry gets through', async () => {
+ db.outboundMessage.updateMany.mockRejectedValueOnce(new Error('db down'));
+ const provider = fakeProvider({
+ parseWebhook: mock(() =>
+ ok({
+ dedupeKey: 'delivery-7',
+ events: [{ type: 'message_status' as const, providerMessageId: 'wamid-1', status: 'READ' as const }],
+ }),
+ ),
+ });
+
+ await expect(
+ new HandleWhatsappWebhook({ db: db as never, provider }).execute('OPENWA', '{}', headers),
+ ).rejects.toThrow('db down');
+ expect(db.whatsappWebhookEvent.delete).toHaveBeenCalledWith({
+ where: { provider_dedupeKey: { provider: 'OPENWA', dedupeKey: 'delivery-7' } },
+ });
+ });
+});
+
+describe('group automations', () => {
+ it('lets the owner turn an automation on', async () => {
+ db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: ownerId });
+ db.group.update.mockResolvedValue({ autoPaymentReminders: true, autoReengagement: false });
+
+ const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, {
+ autoPaymentReminders: true,
+ });
+
+ expect(result).toEqual({ ok: true, value: { autoPaymentReminders: true, autoReengagement: false } });
+ expect(db.group.update).toHaveBeenCalledWith({
+ where: { id: 'group-1' },
+ data: { autoPaymentReminders: true },
+ select: { autoPaymentReminders: true, autoReengagement: true },
+ });
+ });
+
+ it('refuses anyone but the owner', async () => {
+ db.group.findUnique.mockResolvedValue({ id: 'group-1', createdById: 'someone-else' });
+
+ const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('group-1', ownerId, {
+ autoReengagement: true,
+ });
+
+ expect(result.ok).toBe(false);
+ expect(!result.ok && result.error.status).toBe(403);
+ expect(db.group.update).not.toHaveBeenCalled();
+ });
+
+ it('answers 404 for an unknown group', async () => {
+ db.group.findUnique.mockResolvedValue(null);
+
+ const result = await new UpdateGroupAutomationsUseCase({ db: db as never }).execute('nope', ownerId, {
+ autoReengagement: true,
+ });
+
+ expect(!result.ok && result.error.status).toBe(404);
+ });
+});
diff --git a/apps/backend/test/whatsapp-jobs.test.ts b/apps/backend/test/whatsapp-jobs.test.ts
new file mode 100644
index 0000000..840f96b
--- /dev/null
+++ b/apps/backend/test/whatsapp-jobs.test.ts
@@ -0,0 +1,383 @@
+import { beforeEach, describe, expect, it, mock } from 'bun:test';
+import { ok, toWhatsappE164 } from '@gruperly/shared';
+import { SendPaymentReminders, SendReengagementMessages } from '@/modules/whatsapp/jobs';
+import { isoWeekKey } from '@/modules/whatsapp/lib/period';
+import { renderMessage } from '@/modules/whatsapp/lib/render-message';
+import type { MessagingProvider } from '@/modules/whatsapp/providers/messaging-provider';
+
+/* The weekly jobs, with the provider faked through constructor deps. */
+
+const now = new Date('2026-10-19T13:00:00.000Z'); // Monday
+const ownerId = 'user-1';
+
+const activeAccount = {
+ id: 'wa-1',
+ ownerId,
+ provider: 'OPENWA',
+ status: 'ACTIVE',
+ externalId: 'session-1',
+ displayPhoneNumber: '+5491100000000',
+ providerData: null,
+};
+
+function eligibleGroup(overrides: Record = {}) {
+ return {
+ id: 'group-1',
+ name: 'Yoga Martes',
+ createdById: ownerId,
+ owner: { country: 'AR', whatsappAccount: activeAccount },
+ ...overrides,
+ };
+}
+
+function payment(id: string, attendee: Record, overrides: Record = {}) {
+ return {
+ id,
+ amount: { toString: () => '25000' },
+ currency: 'ARS',
+ dueDate: new Date('2026-10-20T15:00:00.000Z'),
+ checkoutUrl: `https://mpago.la/${id}`,
+ attendee: { phone: null, guardianPhone: null, ...attendee },
+ ...overrides,
+ };
+}
+
+function fakeProvider(overrides: Partial = {}): MessagingProvider {
+ return {
+ id: 'OPENWA',
+ startConnection: mock(),
+ refreshConnection: mock(),
+ disconnect: mock(),
+ readiness: mock(async () => 'ready' as const),
+ resolveRecipient: mock(async (_account, e164: string) => ({
+ ok: true as const,
+ to: `${e164.slice(1)}@c.us`,
+ })),
+ send: mock(async () => ({ ok: true as const, providerMessageId: 'wamid-1' })),
+ parseWebhook: mock(() => ok({ dedupeKey: 'k', events: [] })),
+ ...overrides,
+ } as MessagingProvider;
+}
+
+function makeDb() {
+ let counter = 0;
+ return {
+ group: { findMany: mock(async () => [eligibleGroup()]) },
+ payment: { findMany: mock(async () => [] as unknown[]) },
+ attendee: { findMany: mock(async () => [] as unknown[]) },
+ classSession: { findMany: mock(async () => [] as unknown[]) },
+ attendance: { findMany: mock(async () => [] as unknown[]) },
+ outboundMessage: {
+ create: mock(async () => ({ id: `msg-${++counter}` })),
+ update: mock(async () => ({})),
+ delete: mock(async () => ({})),
+ findMany: mock(async () => [] as unknown[]),
+ },
+ };
+}
+
+let db: ReturnType;
+const sleep = mock(async () => undefined);
+
+beforeEach(() => {
+ db = makeDb();
+ sleep.mockClear();
+});
+
+function reminders(provider: MessagingProvider) {
+ return new SendPaymentReminders({ db: db as never, provider, now, intervalMs: 5000, sleep });
+}
+
+function reengagement(provider: MessagingProvider) {
+ return new SendReengagementMessages({ db: db as never, provider, now, intervalMs: 5000, sleep });
+}
+
+describe('payment reminders', () => {
+ it('only looks at groups with the automation on and an active account of this provider', async () => {
+ await reminders(fakeProvider()).execute();
+
+ expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({
+ where: {
+ autoPaymentReminders: true,
+ owner: { whatsappAccount: { is: { provider: 'OPENWA', status: 'ACTIVE' } } },
+ },
+ });
+ });
+
+ it('asks for open charges with a link due within a week', async () => {
+ await reminders(fakeProvider()).execute();
+
+ expect(db.payment.findMany.mock.calls[0]?.[0]).toMatchObject({
+ where: {
+ groupId: 'group-1',
+ status: { in: ['PENDING', 'OVERDUE'] },
+ checkoutUrl: { not: null },
+ dueDate: { lte: new Date('2026-10-26T13:00:00.000Z') },
+ attendee: { status: 'ACTIVE' },
+ },
+ orderBy: { dueDate: 'asc' },
+ });
+ });
+
+ it('sends one reminder per member, logged before the send and keyed by the row id', async () => {
+ db.payment.findMany.mockResolvedValue([
+ payment('pay-1', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }),
+ payment('pay-2', { id: 'att-1', fullName: 'Ana López', phone: '11 2345-6789' }),
+ ]);
+ const provider = fakeProvider();
+
+ const totals = await reminders(provider).execute();
+
+ expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
+ expect(db.outboundMessage.create).toHaveBeenCalledWith({
+ data: {
+ ownerId,
+ groupId: 'group-1',
+ attendeeId: 'att-1',
+ paymentId: 'pay-1',
+ kind: 'PAYMENT_REMINDER',
+ provider: 'OPENWA',
+ periodKey: '2026-W43',
+ toPhone: '+5491123456789',
+ status: 'QUEUED',
+ },
+ select: { id: true },
+ });
+ const [, to, message, key] = (provider.send as ReturnType).mock.calls[0] ?? [];
+ expect(to).toBe('5491123456789@c.us');
+ expect(key).toBe('msg-1');
+ expect(message).toMatchObject({
+ kind: 'PAYMENT_REMINDER',
+ studentName: 'Ana López',
+ groupName: 'Yoga Martes',
+ dueDate: '20/10',
+ paymentLink: 'https://mpago.la/pay-1',
+ });
+ expect(db.outboundMessage.update).toHaveBeenCalledWith({
+ where: { id: 'msg-1' },
+ data: expect.objectContaining({ status: 'SENT', providerMessageId: 'wamid-1' }),
+ });
+ });
+
+ it('skips a member already handled this week', async () => {
+ db.payment.findMany.mockResolvedValue([
+ payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' }),
+ ]);
+ db.outboundMessage.create.mockRejectedValueOnce(Object.assign(new Error('dup'), { code: 'P2002' }));
+ const provider = fakeProvider();
+
+ const totals = await reminders(provider).execute();
+
+ expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 });
+ expect(provider.send).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the guardian phone and skips members without a usable one', async () => {
+ db.payment.findMany.mockResolvedValue([
+ payment('pay-1', { id: 'att-1', fullName: 'Nene', guardianPhone: '1123456789' }),
+ payment('pay-2', { id: 'att-2', fullName: 'Sin tel' }),
+ ]);
+
+ const totals = await reminders(fakeProvider()).execute();
+
+ expect(totals).toEqual({ sent: 1, skipped: 1, failed: 0 });
+ expect(db.outboundMessage.create.mock.calls[1]?.[0]).toMatchObject({
+ data: { attendeeId: 'att-2', status: 'SKIPPED', errorCode: 'invalid_phone' },
+ });
+ });
+
+ it('logs numbers without WhatsApp as skipped', async () => {
+ db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]);
+ const provider = fakeProvider({
+ resolveRecipient: mock(async () => ({ ok: false as const, code: 'no_whatsapp' as const })),
+ });
+
+ const totals = await reminders(provider).execute();
+
+ expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 });
+ expect(db.outboundMessage.create.mock.calls[0]?.[0]).toMatchObject({
+ data: { status: 'SKIPPED', errorCode: 'no_whatsapp' },
+ });
+ expect(provider.send).not.toHaveBeenCalled();
+ });
+
+ it('skips owners whose templates are not approved yet', async () => {
+ db.payment.findMany.mockResolvedValue([payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456789' })]);
+ const provider = fakeProvider({ readiness: mock(async () => 'pending' as const) });
+
+ const totals = await reminders(provider).execute();
+
+ expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
+ expect(db.payment.findMany).not.toHaveBeenCalled();
+ });
+
+ it('paces sends and keeps going after a failure', async () => {
+ db.payment.findMany.mockResolvedValue([
+ payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }),
+ payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }),
+ payment('pay-3', { id: 'att-3', fullName: 'Caro', phone: '1123456783' }),
+ ]);
+ const send = mock(async () => ({ ok: true as const, providerMessageId: 'wamid' }));
+ send.mockResolvedValueOnce({ ok: true, providerMessageId: 'wamid-a' });
+ send.mockResolvedValueOnce({
+ ok: false,
+ retryable: true,
+ code: 'http_500',
+ message: 'engine error',
+ } as never);
+ const provider = fakeProvider({ send });
+
+ const totals = await reminders(provider).execute();
+
+ expect(totals).toEqual({ sent: 2, skipped: 0, failed: 1 });
+ expect(sleep).toHaveBeenCalledTimes(2);
+ expect(sleep).toHaveBeenCalledWith(5000);
+ expect(db.outboundMessage.update).toHaveBeenCalledWith({
+ where: { id: 'msg-2' },
+ data: { status: 'FAILED', errorCode: 'http_500', errorMessage: 'engine error' },
+ });
+ });
+
+ it('stops the account when the gateway rate limits it, freeing the unsent row', async () => {
+ db.payment.findMany.mockResolvedValue([
+ payment('pay-1', { id: 'att-1', fullName: 'Ana', phone: '1123456781' }),
+ payment('pay-2', { id: 'att-2', fullName: 'Beto', phone: '1123456782' }),
+ ]);
+ const send = mock(async () => ({
+ ok: false as const,
+ retryable: true,
+ rateLimitedForMs: 60_000,
+ code: 'SEND_PACING_LIMITED',
+ message: 'cap',
+ }));
+ const provider = fakeProvider({ send });
+
+ const totals = await reminders(provider).execute();
+
+ expect(totals).toEqual({ sent: 0, skipped: 1, failed: 0 });
+ expect(send).toHaveBeenCalledTimes(1);
+ expect(db.outboundMessage.delete).toHaveBeenCalledWith({ where: { id: 'msg-1' } });
+ });
+
+ it('does nothing when no group has the automation on', async () => {
+ db.group.findMany.mockResolvedValue([]);
+ const provider = fakeProvider();
+
+ const totals = await reminders(provider).execute();
+
+ expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
+ expect(provider.readiness).not.toHaveBeenCalled();
+ });
+});
+
+describe('re-engagement messages', () => {
+ function atRiskGroup() {
+ // Two sessions in the window, both missed by att-1: a streak of 2 (MEDIUM).
+ db.classSession.findMany.mockResolvedValue([{ id: 's1' }, { id: 's2' }]);
+ db.attendee.findMany
+ .mockResolvedValueOnce([
+ { id: 'att-1', fullName: 'Ana López', phone: '1123456789' },
+ { id: 'att-2', fullName: 'Beto', phone: '1198765432' },
+ ])
+ .mockResolvedValueOnce([
+ { id: 'att-1', phone: '1123456789', guardianPhone: null },
+ ]);
+ db.attendance.findMany.mockResolvedValue([
+ { attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
+ { attendeeId: 'att-1', status: 'ABSENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
+ { attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-16T10:00:00Z') } },
+ { attendeeId: 'att-2', status: 'PRESENT', classSession: { startsAt: new Date('2026-10-14T10:00:00Z') } },
+ ]);
+ }
+
+ it('writes to the members at risk, with the copy of the manual button', async () => {
+ atRiskGroup();
+ const provider = fakeProvider();
+
+ const totals = await reengagement(provider).execute();
+
+ expect(db.group.findMany.mock.calls[0]?.[0]).toMatchObject({ where: { autoReengagement: true } });
+ expect(totals).toEqual({ sent: 1, skipped: 0, failed: 0 });
+ const [, , message] = (provider.send as ReturnType).mock.calls[0] ?? [];
+ expect(message).toEqual({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga Martes' });
+ });
+
+ it('leaves alone members written to in the last 14 days', async () => {
+ atRiskGroup();
+ db.outboundMessage.findMany.mockResolvedValue([{ attendeeId: 'att-1' }]);
+ const provider = fakeProvider();
+
+ const totals = await reengagement(provider).execute();
+
+ expect(totals).toEqual({ sent: 0, skipped: 0, failed: 0 });
+ expect(db.outboundMessage.findMany.mock.calls[0]?.[0]).toMatchObject({
+ where: {
+ kind: 'REENGAGEMENT',
+ attendeeId: { in: ['att-1'] },
+ status: { in: ['SENT', 'DELIVERED', 'READ'] },
+ createdAt: { gte: new Date('2026-10-05T13:00:00.000Z') },
+ },
+ });
+ expect(provider.send).not.toHaveBeenCalled();
+ });
+});
+
+describe('helpers', () => {
+ it('keys messages by ISO week', () => {
+ expect(isoWeekKey(new Date('2026-10-19T13:00:00Z'))).toBe('2026-W43');
+ expect(isoWeekKey(new Date('2026-10-25T23:59:00Z'))).toBe('2026-W43');
+ expect(isoWeekKey(new Date('2027-01-01T10:00:00Z'))).toBe('2026-W53');
+ expect(isoWeekKey(new Date('2025-12-29T10:00:00Z'))).toBe('2026-W01');
+ });
+
+ it('renders the free-text messages with the first name', () => {
+ expect(
+ renderMessage({
+ kind: 'PAYMENT_REMINDER',
+ studentName: 'Ana López',
+ groupName: 'Yoga',
+ amount: '$ 25.000',
+ dueDate: '20/10',
+ paymentLink: 'https://mpago.la/x',
+ }),
+ ).toBe(
+ '¡Hola Ana! Te recordamos el pago de Yoga por $ 25.000, con vencimiento el 20/10. ' +
+ 'Podés pagarlo desde este link: https://mpago.la/x',
+ );
+ expect(renderMessage({ kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' })).toStartWith(
+ '¡Hola Ana! 👋 Te extrañamos en Yoga.',
+ );
+ });
+});
+
+describe('toWhatsappE164', () => {
+ it.each([
+ ['11 2345-6789', 'AR', '+5491123456789'],
+ ['011 15 2345-6789', 'AR', '+5491123456789'],
+ ['0351 15 123-4567', 'AR', '+5493511234567'],
+ ['9 11 2345 6789', 'AR', '+5491123456789'],
+ ['5491123456789', 'AR', '+5491123456789'],
+ ['+54 11 2345 6789', 'AR', '+5491123456789'],
+ ['+34 612 345 678', 'AR', '+34612345678'],
+ ['0034612345678', 'AR', '+34612345678'],
+ ['(11) 98765-4321', 'BR', '+5511987654321'],
+ ['9 8765 4321', 'CL', '+56987654321'],
+ ['300 123 4567', 'CO', '+573001234567'],
+ ['55 1234 5678', 'MX', '+525512345678'],
+ ['987 654 321', 'PE', '+51987654321'],
+ ['099 123 456', 'UY', '+59899123456'],
+ ] as const)('%s (%s) → %s', (input, country, expected) => {
+ expect(toWhatsappE164(input, country)).toBe(expected);
+ });
+
+ it.each([['', 'AR'], ['1234', 'AR'], ['12 3456', 'MX'], ['abc', 'UY']] as const)(
+ 'rejects %p (%s)',
+ (input, country) => {
+ expect(toWhatsappE164(input, country)).toBeNull();
+ },
+ );
+
+ it('assumes Argentina when the teacher has no country yet', () => {
+ expect(toWhatsappE164('11 2345 6789', null)).toBe('+5491123456789');
+ });
+});
diff --git a/apps/backend/test/whatsapp-providers.test.ts b/apps/backend/test/whatsapp-providers.test.ts
new file mode 100644
index 0000000..907a7cf
--- /dev/null
+++ b/apps/backend/test/whatsapp-providers.test.ts
@@ -0,0 +1,600 @@
+import { describe, expect, it, mock } from 'bun:test';
+import { createHmac } from 'node:crypto';
+import { KapsoProvider } from '@/modules/whatsapp/providers/kapso';
+import type { WhatsappAccountRecord } from '@/modules/whatsapp/providers/messaging-provider';
+import { OpenWaProvider, openWaSessionName } from '@/modules/whatsapp/providers/openwa';
+
+/* Both adapters against a recorded `fetch`: the requests they make and how they
+ read the answers. No network, no `mock.module`. */
+
+type Route = { method: string; path: string; status?: number; body?: unknown };
+
+function fakeFetch(routes: Route[]) {
+ const calls: { method: string; url: string; headers: Record; body: unknown }[] = [];
+ const fn = mock(async (url: string, init?: RequestInit) => {
+ const method = init?.method ?? 'GET';
+ calls.push({
+ method,
+ url,
+ headers: (init?.headers ?? {}) as Record,
+ body: init?.body ? JSON.parse(String(init.body)) : undefined,
+ });
+ const route = routes.find((candidate) => candidate.method === method && url.endsWith(candidate.path));
+ if (!route) return new Response(JSON.stringify({ statusCode: 404 }), { status: 404 });
+ return new Response(route.body === undefined ? null : JSON.stringify(route.body), {
+ status: route.status ?? 200,
+ });
+ });
+ return { fn, calls };
+}
+
+const openWaConfig = {
+ apiUrl: 'http://openwa:2785/api',
+ apiKey: 'owa_k1_test',
+ webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/openwa',
+ webhookSecret: 'a-very-long-webhook-secret',
+};
+
+function openWaAccount(overrides: Partial = {}): WhatsappAccountRecord {
+ return {
+ id: 'wa-1',
+ ownerId: 'user-1',
+ provider: 'OPENWA',
+ status: 'ACTIVE',
+ externalId: 'sess-1',
+ displayPhoneNumber: null,
+ providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' },
+ ...overrides,
+ };
+}
+
+function sign(body: string, secret: string) {
+ return createHmac('sha256', secret).update(body).digest('hex');
+}
+
+describe('OpenWA provider', () => {
+ it('creates a session, subscribes the webhook, starts it and returns the QR', async () => {
+ const { fn, calls } = fakeFetch([
+ {
+ method: 'POST',
+ path: '/sessions',
+ status: 201,
+ body: { id: 'sess-1', name: 'gruperly-user-1', status: 'created', engineLoaded: false },
+ },
+ { method: 'POST', path: '/sessions/sess-1/webhooks', status: 201, body: { id: 'wh-1' } },
+ {
+ method: 'POST',
+ path: '/sessions/sess-1/start',
+ body: { id: 'sess-1', name: 'gruperly-user-1', status: 'initializing', engineLoaded: true },
+ },
+ { method: 'GET', path: '/sessions/sess-1/qr', body: { qrCode: 'data:image/png;base64,QR', status: 'qr_ready' } },
+ ]);
+ const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
+
+ const result = await provider.startConnection({
+ ownerId: 'user-1',
+ ownerName: 'Ana',
+ returnTo: 'settings',
+ account: null,
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ start: { type: 'qr', qrCode: 'data:image/png;base64,QR' },
+ externalId: 'sess-1',
+ providerData: { sessionName: 'gruperly-user-1', webhookId: 'wh-1' },
+ },
+ });
+ expect(calls[0]).toMatchObject({ method: 'POST', body: { name: 'gruperly-user-1' } });
+ expect(calls[0]?.headers['X-API-Key']).toBe('owa_k1_test');
+ expect(calls[1]?.body).toMatchObject({
+ url: openWaConfig.webhookUrl,
+ secret: openWaConfig.webhookSecret,
+ events: expect.arrayContaining(['message.ack', 'session.authenticated']),
+ });
+ });
+
+ it('adopts a session that already exists under the teacher name', async () => {
+ const { fn } = fakeFetch([
+ { method: 'POST', path: '/sessions', status: 409, body: { statusCode: 409 } },
+ {
+ method: 'GET',
+ path: '/sessions?name=gruperly-user-1',
+ body: [{ id: 'sess-9', name: 'gruperly-user-1', status: 'qr_ready', engineLoaded: true }],
+ },
+ { method: 'POST', path: '/sessions/sess-9/webhooks', status: 201, body: { id: 'wh-9' } },
+ { method: 'GET', path: '/sessions/sess-9/qr', status: 400, body: { statusCode: 400 } },
+ ]);
+ const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
+
+ const result = await provider.startConnection({
+ ownerId: 'user-1',
+ ownerName: 'Ana',
+ returnTo: 'settings',
+ account: null,
+ });
+
+ expect(result.ok && result.value).toMatchObject({
+ start: { type: 'qr', qrCode: null },
+ externalId: 'sess-9',
+ });
+ });
+
+ it('answers a provider problem when OpenWA is down', async () => {
+ const fn = mock(async () => {
+ throw new TypeError('fetch failed');
+ });
+ const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
+
+ const result = await provider.startConnection({
+ ownerId: 'user-1',
+ ownerName: 'Ana',
+ returnTo: 'settings',
+ account: null,
+ });
+
+ expect(!result.ok && result.error.code).toBe('whatsapp_provider_error');
+ });
+
+ it('maps session states', async () => {
+ const cases = [
+ [{ status: 'ready', phone: '5491123456789', engineLoaded: true }, { state: 'active', displayPhoneNumber: '+5491123456789' }],
+ [{ status: 'initializing', engineLoaded: true }, { state: 'pending', qrCode: null }],
+ [{ status: 'disconnected', engineLoaded: true }, { state: 'pending', qrCode: null }],
+ [{ status: 'failed', lastError: 'boom', engineLoaded: false }, { state: 'disconnected', reason: 'boom' }],
+ ] as const;
+
+ for (const [session, expected] of cases) {
+ const { fn } = fakeFetch([{ method: 'GET', path: '/sessions/sess-1', body: { id: 'sess-1', ...session } }]);
+ const result = await new OpenWaProvider(openWaConfig, { fetch: fn }).refreshConnection(
+ openWaAccount({ status: 'PENDING' }),
+ );
+ expect(result).toEqual({ ok: true, value: expected as never });
+ }
+ });
+
+ it('resolves recipients through the contact check', async () => {
+ const { fn, calls } = fakeFetch([
+ {
+ method: 'GET',
+ path: '/sessions/sess-1/contacts/check/5491123456789',
+ body: { exists: true, whatsappId: '541123456789@c.us' },
+ },
+ ]);
+ const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
+
+ expect(await provider.resolveRecipient(openWaAccount(), '+5491123456789')).toEqual({
+ ok: true,
+ to: '541123456789@c.us',
+ });
+ expect(calls).toHaveLength(1);
+ });
+
+ it('sends free text with an idempotency key', async () => {
+ const { fn, calls } = fakeFetch([
+ {
+ method: 'POST',
+ path: '/sessions/sess-1/messages/send-text',
+ status: 201,
+ body: { messageId: 'true_5491123456789@c.us_3EB0', timestamp: 1 },
+ },
+ ]);
+ const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
+
+ const outcome = await provider.send(
+ openWaAccount(),
+ '5491123456789@c.us',
+ { kind: 'REENGAGEMENT', studentName: 'Ana López', groupName: 'Yoga' },
+ 'msg-1',
+ );
+
+ expect(outcome).toEqual({ ok: true, providerMessageId: 'true_5491123456789@c.us_3EB0' });
+ expect(calls[0]?.headers['Idempotency-Key']).toBe('msg-1');
+ expect(calls[0]?.body).toMatchObject({ chatId: '5491123456789@c.us' });
+ expect(String((calls[0]?.body as { text?: string } | undefined)?.text)).toStartWith('¡Hola Ana!');
+ });
+
+ it('turns send pacing into a rate limit for the account', async () => {
+ const { fn } = fakeFetch([
+ {
+ method: 'POST',
+ path: '/sessions/sess-1/messages/send-text',
+ status: 429,
+ body: { statusCode: 429, code: 'SEND_PACING_LIMITED', retryAfterSeconds: 120 },
+ },
+ ]);
+ const outcome = await new OpenWaProvider(openWaConfig, { fetch: fn }).send(
+ openWaAccount(),
+ 'x@c.us',
+ { kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' },
+ 'msg-1',
+ );
+
+ expect(outcome).toMatchObject({ ok: false, rateLimitedForMs: 120_000, code: 'SEND_PACING_LIMITED' });
+ });
+
+ it('verifies the webhook signature and normalizes acks and session events', () => {
+ const provider = new OpenWaProvider(openWaConfig);
+ const ack = JSON.stringify({
+ event: 'message.ack',
+ sessionId: 'sess-1',
+ idempotencyKey: 'ack_sess-1_m1_read',
+ deliveryId: 'dlv_1',
+ data: { id: 'row', messageId: 'm1', status: 'read', ack: 3 },
+ });
+ const good = new Headers({
+ 'X-OpenWA-Signature': `sha256=${sign(ack, openWaConfig.webhookSecret)}`,
+ 'X-OpenWA-Idempotency-Key': 'ack_sess-1_m1_read',
+ });
+
+ expect(provider.parseWebhook(ack, good)).toEqual({
+ ok: true,
+ value: {
+ dedupeKey: 'ack_sess-1_m1_read',
+ events: [{ type: 'message_status', providerMessageId: 'm1', status: 'READ', errorCode: null }],
+ },
+ });
+
+ const tampered = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(`${ack} `, openWaConfig.webhookSecret)}` });
+ expect(provider.parseWebhook(ack, tampered)).toEqual({ ok: false, error: 'invalid_signature' });
+ expect(provider.parseWebhook(ack, new Headers())).toEqual({ ok: false, error: 'invalid_signature' });
+
+ const auth = JSON.stringify({
+ event: 'session.authenticated',
+ sessionId: 'sess-1',
+ idempotencyKey: 'auth_1',
+ data: { sessionId: 'sess-1', phone: '5491123456789' },
+ });
+ const authHeaders = new Headers({ 'X-OpenWA-Signature': `sha256=${sign(auth, openWaConfig.webhookSecret)}` });
+ expect(provider.parseWebhook(auth, authHeaders)).toEqual({
+ ok: true,
+ value: {
+ dedupeKey: 'auth_1',
+ events: [
+ { type: 'connection', externalId: 'sess-1', status: 'active', displayPhoneNumber: '+5491123456789' },
+ ],
+ },
+ });
+ });
+
+ it('builds valid session names', () => {
+ expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd');
+ expect(openWaSessionName('weird_id.with@chars')).toBe('gruperly-weirdidwithchars');
+ });
+});
+
+const kapsoConfig = {
+ apiUrl: 'https://api.kapso.ai',
+ apiKey: 'kapso-key',
+ callbackUrl: 'https://api.example.com/api/v1/whatsapp/callback',
+ webhookUrl: 'https://api.example.com/api/v1/whatsapp/webhooks/kapso',
+ webhookSecret: 'kapso-webhook-secret',
+};
+
+function kapsoAccount(overrides: Partial = {}): WhatsappAccountRecord {
+ return {
+ id: 'wa-1',
+ ownerId: 'user-1',
+ provider: 'KAPSO',
+ status: 'PENDING',
+ externalId: null,
+ displayPhoneNumber: null,
+ providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
+ ...overrides,
+ };
+}
+
+function kapsoDb() {
+ return {
+ whatsappAccount: { update: mock(async () => ({})) },
+ whatsappTemplate: {
+ findUnique: mock(async () => null as unknown),
+ findMany: mock(async () => [] as unknown[]),
+ create: mock(async () => ({})),
+ update: mock(async () => ({})),
+ },
+ };
+}
+
+describe('Kapso provider', () => {
+ it('creates the customer once and a customer-billed setup link', async () => {
+ const { fn, calls } = fakeFetch([
+ { method: 'POST', path: '/platform/v1/customers', status: 201, body: { data: { id: 'cust-1' } } },
+ {
+ method: 'POST',
+ path: '/platform/v1/customers/cust-1/setup_links',
+ status: 201,
+ body: { data: { id: 'link-1', url: 'https://app.kapso.ai/whatsapp/setup/abc' } },
+ },
+ ]);
+ const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
+
+ const result = await provider.startConnection({
+ ownerId: 'user-1',
+ ownerName: 'Ana Profe',
+ returnTo: 'onboarding',
+ account: null,
+ });
+
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ start: { type: 'redirect', url: 'https://app.kapso.ai/whatsapp/setup/abc' },
+ externalId: null,
+ providerData: { customerId: 'cust-1', setupLinkId: 'link-1' },
+ },
+ });
+ expect(calls[0]?.body).toEqual({ customer: { name: 'Ana Profe', external_customer_id: 'user-1' } });
+ expect(calls[1]?.body).toMatchObject({
+ setup_link: {
+ success_redirect_url: `${kapsoConfig.callbackUrl}?returnTo=onboarding`,
+ meta_billing_mode: 'customer_managed',
+ language: 'es',
+ },
+ });
+
+ // Linking again reuses the customer.
+ const again = fakeFetch([
+ {
+ method: 'POST',
+ path: '/platform/v1/customers/cust-1/setup_links',
+ status: 201,
+ body: { data: { id: 'link-2', url: 'https://app.kapso.ai/whatsapp/setup/def' } },
+ },
+ ]);
+ await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: again.fn }).startConnection({
+ ownerId: 'user-1',
+ ownerName: 'Ana',
+ returnTo: 'settings',
+ account: kapsoAccount(),
+ });
+ expect(again.calls).toHaveLength(1);
+ });
+
+ it('does not trust the callback query', async () => {
+ const { fn } = fakeFetch([
+ {
+ method: 'GET',
+ path: '/platform/v1/whatsapp/phone_numbers/phone-1',
+ body: {
+ data: {
+ phone_number_id: 'phone-1',
+ business_account_id: 'waba-1',
+ display_phone_number: '+54 9 11 2345-6789',
+ customer_id: 'someone-else',
+ },
+ },
+ },
+ ]);
+ const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
+
+ expect(
+ await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'other', phone_number_id: 'phone-1' }),
+ ).toEqual({ ok: false, error: 'invalid_setup' });
+ expect(
+ await provider.completeRedirect(kapsoAccount(), { setup_link_id: 'link-1', error_code: 'facebook_auth_failed' }),
+ ).toEqual({ ok: false, error: 'setup_failed' });
+ expect(
+ await provider.completeRedirect(kapsoAccount(), {
+ setup_link_id: 'link-1',
+ status: 'completed',
+ phone_number_id: 'phone-1',
+ }),
+ ).toEqual({ ok: false, error: 'invalid_setup' });
+ });
+
+ it('completes a setup confirmed by Kapso', async () => {
+ const { fn } = fakeFetch([
+ {
+ method: 'GET',
+ path: '/platform/v1/whatsapp/phone_numbers/phone-1',
+ body: {
+ data: {
+ phone_number_id: 'phone-1',
+ business_account_id: 'waba-1',
+ display_phone_number: '+54 9 11 2345-6789',
+ customer_id: 'cust-1',
+ },
+ },
+ },
+ ]);
+ const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
+
+ expect(
+ await provider.completeRedirect(kapsoAccount(), {
+ setup_link_id: 'link-1',
+ status: 'completed',
+ phone_number_id: 'phone-1',
+ }),
+ ).toEqual({
+ ok: true,
+ value: {
+ externalId: 'phone-1',
+ displayPhoneNumber: '+5491123456789',
+ providerData: { customerId: 'cust-1', setupLinkId: 'link-1', businessAccountId: 'waba-1' },
+ },
+ });
+ });
+
+ it('subscribes the number and submits both templates after connecting', async () => {
+ const { fn, calls } = fakeFetch([
+ {
+ method: 'POST',
+ path: '/platform/v1/whatsapp/phone_numbers/phone-1/webhooks',
+ status: 201,
+ body: { data: { id: 'wh-1' } },
+ },
+ {
+ method: 'POST',
+ path: '/meta/whatsapp/v24.0/waba-1/message_templates',
+ body: { id: 'tpl-1', status: 'PENDING', category: 'UTILITY' },
+ },
+ ]);
+ const db = kapsoDb();
+ const provider = new KapsoProvider(kapsoConfig, { db: db as never, fetch: fn });
+
+ await provider.onConnected(
+ kapsoAccount({
+ status: 'ACTIVE',
+ externalId: 'phone-1',
+ providerData: { customerId: 'cust-1', businessAccountId: 'waba-1' },
+ }),
+ );
+
+ expect(calls[0]?.body).toMatchObject({
+ whatsapp_webhook: { url: kapsoConfig.webhookUrl, secret_key: kapsoConfig.webhookSecret, kind: 'kapso' },
+ });
+ const templates = calls.filter((call) => call.url.endsWith('/message_templates'));
+ expect(templates.map((call) => (call.body as { name: string; category: string }))).toEqual([
+ expect.objectContaining({ name: 'gruperly_payment_reminder', category: 'UTILITY' }),
+ expect.objectContaining({ name: 'gruperly_reengagement', category: 'MARKETING' }),
+ ]);
+ expect(db.whatsappAccount.update).toHaveBeenCalledWith({
+ where: { id: 'wa-1' },
+ data: { providerData: { customerId: 'cust-1', businessAccountId: 'waba-1', webhookId: 'wh-1' } },
+ });
+ expect(db.whatsappTemplate.create).toHaveBeenCalledTimes(2);
+ });
+
+ it('is ready only once the template is approved', async () => {
+ const db = kapsoDb();
+ const provider = new KapsoProvider(kapsoConfig, { db: db as never });
+ const active = kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' });
+
+ db.whatsappTemplate.findUnique.mockResolvedValueOnce(null);
+ expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('pending');
+ db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'APPROVED' });
+ expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('ready');
+ db.whatsappTemplate.findUnique.mockResolvedValueOnce({ status: 'REJECTED' });
+ expect(await provider.readiness(active, 'PAYMENT_REMINDER')).toBe('blocked');
+ expect(await provider.readiness(kapsoAccount(), 'PAYMENT_REMINDER')).toBe('blocked');
+ });
+
+ it('sends the approved template with named parameters', async () => {
+ const { fn, calls } = fakeFetch([
+ {
+ method: 'POST',
+ path: '/meta/whatsapp/v24.0/phone-1/messages',
+ body: { messaging_product: 'whatsapp', messages: [{ id: 'wamid.ABC' }] },
+ },
+ ]);
+ const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn });
+
+ const outcome = await provider.send(
+ kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }),
+ '5491123456789',
+ {
+ kind: 'PAYMENT_REMINDER',
+ studentName: 'Ana López',
+ groupName: 'Yoga',
+ amount: '$ 25.000',
+ dueDate: '20/10',
+ paymentLink: 'https://mpago.la/x',
+ },
+ 'msg-1',
+ );
+
+ expect(outcome).toEqual({ ok: true, providerMessageId: 'wamid.ABC' });
+ expect(calls[0]?.body).toMatchObject({
+ to: '5491123456789',
+ type: 'template',
+ template: {
+ name: 'gruperly_payment_reminder',
+ language: { code: 'es_AR' },
+ components: [
+ {
+ type: 'body',
+ parameters: expect.arrayContaining([
+ { type: 'text', parameter_name: 'student_name', text: 'Ana' },
+ { type: 'text', parameter_name: 'payment_link', text: 'https://mpago.la/x' },
+ ]),
+ },
+ ],
+ },
+ });
+ });
+
+ it('does not retry a marketing opt-out', async () => {
+ const { fn } = fakeFetch([
+ {
+ method: 'POST',
+ path: '/meta/whatsapp/v24.0/phone-1/messages',
+ status: 422,
+ body: { error: { code: 'marketing_preference_stopped' } },
+ },
+ ]);
+ const outcome = await new KapsoProvider(kapsoConfig, { db: kapsoDb() as never, fetch: fn }).send(
+ kapsoAccount({ status: 'ACTIVE', externalId: 'phone-1' }),
+ '5491123456789',
+ { kind: 'REENGAGEMENT', studentName: 'Ana', groupName: 'Yoga' },
+ 'msg-1',
+ );
+
+ expect(outcome).toMatchObject({ ok: false, retryable: false, code: 'marketing_preference_stopped' });
+ });
+
+ it('verifies the webhook and normalizes number and message events', () => {
+ const provider = new KapsoProvider(kapsoConfig, { db: kapsoDb() as never });
+ const created = JSON.stringify({
+ phone_number_id: 'phone-1',
+ business_account_id: 'waba-1',
+ display_phone_number: '+54 9 11 2345 6789',
+ customer: { id: 'cust-1', external_id: 'user-1' },
+ });
+ const headers = new Headers({
+ 'X-Webhook-Signature': sign(created, kapsoConfig.webhookSecret),
+ 'X-Webhook-Event': 'whatsapp.phone_number.created',
+ 'X-Idempotency-Key': 'idem-1',
+ });
+
+ expect(provider.parseWebhook(created, headers)).toEqual({
+ ok: true,
+ value: {
+ dedupeKey: 'idem-1',
+ events: [
+ {
+ type: 'connection',
+ externalId: 'phone-1',
+ ownerId: 'user-1',
+ status: 'active',
+ displayPhoneNumber: '+5491123456789',
+ providerData: { businessAccountId: 'waba-1' },
+ },
+ ],
+ },
+ });
+
+ const failed = JSON.stringify({
+ phone_number_id: 'phone-1',
+ message: {
+ id: 'wamid.ABC',
+ kapso: { status: 'failed', statuses: [{ status: 'failed', errors: [{ code: 131026, title: 'Undeliverable' }] }] },
+ },
+ });
+ const failedHeaders = new Headers({
+ 'X-Webhook-Signature': sign(failed, kapsoConfig.webhookSecret),
+ 'X-Webhook-Event': 'whatsapp.message.failed',
+ 'X-Idempotency-Key': 'idem-2',
+ });
+ expect(provider.parseWebhook(failed, failedHeaders)).toEqual({
+ ok: true,
+ value: {
+ dedupeKey: 'idem-2',
+ events: [
+ {
+ type: 'message_status',
+ providerMessageId: 'wamid.ABC',
+ status: 'FAILED',
+ errorCode: '131026',
+ errorMessage: 'Undeliverable',
+ },
+ ],
+ },
+ });
+
+ expect(
+ provider.parseWebhook(created, new Headers({ 'X-Webhook-Signature': 'deadbeef', 'X-Idempotency-Key': 'x' })),
+ ).toEqual({ ok: false, error: 'invalid_signature' });
+ });
+});
diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.ts
index 1ff1def..6838b88 100644
--- a/apps/web/src/components/ui/index.ts
+++ b/apps/web/src/components/ui/index.ts
@@ -7,3 +7,4 @@ export { Modal, type ModalProps } from './modal'
export { type Toast, ToastProvider, type ToastType, useToast } from './toast'
export { Tooltip, type TooltipProps } from './tooltip'
+export { Switch, type SwitchProps } from './switch'
diff --git a/apps/web/src/components/ui/switch.tsx b/apps/web/src/components/ui/switch.tsx
new file mode 100644
index 0000000..e156faf
--- /dev/null
+++ b/apps/web/src/components/ui/switch.tsx
@@ -0,0 +1,40 @@
+import { cn } from '../../lib/utils'
+
+export type SwitchProps = {
+ checked: boolean
+ onCheckedChange: (checked: boolean) => void
+ disabled?: boolean
+ /** Nombre accesible, cuando no hay un `
+
+
+
+ {isWhatsappConnected ? (
+ <>
+ Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la
+ ficha del grupo.
+ >
+ ) : (
+ <>
+ Para enviar recordatorios automáticos, vinculá{' '}
+ WhatsApp desde Ajustes.
+ >
+ )}
+