development #14
19
.env.example
19
.env.example
@@ -46,6 +46,25 @@ BETTER_AUTH_SECRET=""
|
|||||||
# MP_CLIENT_ID=""
|
# MP_CLIENT_ID=""
|
||||||
# MP_CLIENT_SECRET=""
|
# 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
|
# Only if you want the API on another domain: it is baked into the Vite bundle
|
||||||
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
|
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
|
||||||
# origin (recommended).
|
# origin (recommended).
|
||||||
|
|||||||
14
AGENTS.md
14
AGENTS.md
@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||||
- `src/logger.ts` — pino + pino-pretty.
|
- `src/logger.ts` — pino + pino-pretty.
|
||||||
- Módulos existentes: `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`).
|
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||||
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||||
@@ -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`.
|
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||||
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
- **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/<nombre>/`.
|
||||||
|
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
|
||||||
|
3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
|
||||||
|
4. La idempotencia de los envíos es el `@@unique([kind, attendeeId, periodKey])` de `outbound_messages` (semana ISO): la fila se crea **antes** de llamar al proveedor y su id es el `Idempotency-Key`.
|
||||||
|
5. Los teléfonos se guardan en formato nacional: el envío pasa por `toWhatsappE164` (shared) con el país del profesor.
|
||||||
|
6. Sin SDK de Kapso (trae su propio zod): `fetch` plano.
|
||||||
|
7. El sandbox de Kapso no soporta templates.
|
||||||
|
8. 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.
|
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||||
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
||||||
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
||||||
|
|||||||
30
README.md
30
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.
|
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.
|
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)
|
## Deploy en producción (Docker / Dokploy)
|
||||||
|
|
||||||
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
|
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
|
||||||
@@ -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`) |
|
| `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)) |
|
| `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 |
|
| `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 |
|
| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio |
|
||||||
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
||||||
|
|
||||||
|
|||||||
@@ -30,4 +30,28 @@ MP_CLIENT_SECRET=""
|
|||||||
MP_REDIRECT_URI=""
|
MP_REDIRECT_URI=""
|
||||||
# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM).
|
# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM).
|
||||||
# Generar con: openssl rand -base64 32
|
# Generar con: openssl rand -base64 32
|
||||||
TOKEN_ENCRYPTION_KEY=""
|
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"
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -20,6 +20,7 @@ model User {
|
|||||||
orgInvitations Invitation[] @relation("InvitedBy")
|
orgInvitations Invitation[] @relation("InvitedBy")
|
||||||
waitlist WaitlistEntry[]
|
waitlist WaitlistEntry[]
|
||||||
mpAccount MpAccount?
|
mpAccount MpAccount?
|
||||||
|
whatsappAccount WhatsappAccount?
|
||||||
|
|
||||||
@@map("users")
|
@@map("users")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,22 @@
|
|||||||
// Domain models
|
// Domain models
|
||||||
|
|
||||||
model Group {
|
model Group {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
name String
|
name String
|
||||||
description String?
|
description String?
|
||||||
days WeekDay[]
|
days WeekDay[]
|
||||||
time String?
|
time String?
|
||||||
capacity Int?
|
capacity Int?
|
||||||
price Decimal? @db.Decimal(10, 2)
|
price Decimal? @db.Decimal(10, 2)
|
||||||
billingType BillingType? @map("billing_type")
|
billingType BillingType? @map("billing_type")
|
||||||
dueDay Int? @map("due_day")
|
dueDay Int? @map("due_day")
|
||||||
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
|
// Weekly WhatsApp automations, off until the teacher turns them on.
|
||||||
createdById String @map("created_by_id")
|
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
autoReengagement Boolean @default(false) @map("auto_reengagement")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
|
||||||
|
createdById String @map("created_by_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
|
owner User @relation("OwnerGroups", fields: [createdById], references: [id], onDelete: Cascade, map: "groups_createdById_fkey")
|
||||||
members GroupMember[]
|
members GroupMember[]
|
||||||
@@ -22,6 +25,7 @@ model Group {
|
|||||||
waitlist GroupWaitlistEntry[]
|
waitlist GroupWaitlistEntry[]
|
||||||
preRegistrations GroupPreRegistration[]
|
preRegistrations GroupPreRegistration[]
|
||||||
classSessions ClassSession[]
|
classSessions ClassSession[]
|
||||||
|
outboundMessages OutboundMessage[]
|
||||||
|
|
||||||
@@map("groups")
|
@@map("groups")
|
||||||
}
|
}
|
||||||
@@ -81,33 +85,35 @@ model Attendee {
|
|||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
|
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "attendees_groupId_fkey")
|
||||||
payments Payment[]
|
payments Payment[]
|
||||||
attendances Attendance[]
|
attendances Attendance[]
|
||||||
slotReleases SlotRelease[]
|
slotReleases SlotRelease[]
|
||||||
|
outboundMessages OutboundMessage[]
|
||||||
|
|
||||||
@@index([groupId], map: "attendees_groupId_idx")
|
@@index([groupId], map: "attendees_groupId_idx")
|
||||||
@@map("attendees")
|
@@map("attendees")
|
||||||
}
|
}
|
||||||
|
|
||||||
model Payment {
|
model Payment {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
groupId String @map("group_id")
|
groupId String @map("group_id")
|
||||||
attendeeId String @map("attendee_id")
|
attendeeId String @map("attendee_id")
|
||||||
amount Decimal @db.Decimal(10, 2)
|
amount Decimal @db.Decimal(10, 2)
|
||||||
currency String @default("ARS")
|
currency String @default("ARS")
|
||||||
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
|
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
|
||||||
dueDate DateTime @map("due_date")
|
dueDate DateTime @map("due_date")
|
||||||
description String? @map("description")
|
description String? @map("description")
|
||||||
checkoutUrl String? @map("checkout_url")
|
checkoutUrl String? @map("checkout_url")
|
||||||
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
|
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
|
||||||
mpPaymentId String? @map("mp_payment_id")
|
mpPaymentId String? @map("mp_payment_id")
|
||||||
paidAt DateTime? @map("paid_at")
|
paidAt DateTime? @map("paid_at")
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "payments_groupId_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")
|
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "payments_attendeeId_fkey")
|
||||||
|
outboundMessages OutboundMessage[]
|
||||||
|
|
||||||
@@index([groupId], map: "payments_groupId_idx")
|
@@index([groupId], map: "payments_groupId_idx")
|
||||||
@@index([attendeeId], map: "payments_attendeeId_idx")
|
@@index([attendeeId], map: "payments_attendeeId_idx")
|
||||||
|
|||||||
130
apps/backend/prisma/models/whatsapp.prisma
Normal file
130
apps/backend/prisma/models/whatsapp.prisma
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
// WhatsApp messaging (automated payment reminders and re-engagement).
|
||||||
|
//
|
||||||
|
// Nothing here is tied to one provider: the teacher links their own number
|
||||||
|
// through whichever `MessagingProvider` the server runs (OpenWA for the MVP,
|
||||||
|
// Kapso afterwards) and the row records which one it was linked with. Changing
|
||||||
|
// `WHATSAPP_PROVIDER` leaves the old rows behind as "requires reconnect".
|
||||||
|
|
||||||
|
enum MessagingProviderId {
|
||||||
|
OPENWA
|
||||||
|
KAPSO
|
||||||
|
}
|
||||||
|
|
||||||
|
enum WhatsappAccountStatus {
|
||||||
|
PENDING
|
||||||
|
ACTIVE
|
||||||
|
DISCONNECTED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum WhatsappMessageKind {
|
||||||
|
PAYMENT_REMINDER
|
||||||
|
REENGAGEMENT
|
||||||
|
}
|
||||||
|
|
||||||
|
enum OutboundMessageStatus {
|
||||||
|
QUEUED
|
||||||
|
SENT
|
||||||
|
DELIVERED
|
||||||
|
READ
|
||||||
|
FAILED
|
||||||
|
SKIPPED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum WhatsappTemplateStatus {
|
||||||
|
PENDING
|
||||||
|
APPROVED
|
||||||
|
REJECTED
|
||||||
|
DISABLED
|
||||||
|
}
|
||||||
|
|
||||||
|
// The teacher's linked WhatsApp. One per teacher.
|
||||||
|
model WhatsappAccount {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
ownerId String @unique(map: "whatsapp_accounts_ownerId_key") @map("owner_id")
|
||||||
|
provider MessagingProviderId
|
||||||
|
status WhatsappAccountStatus @default(PENDING)
|
||||||
|
// OpenWA: session id. Kapso: phone_number_id (null until the setup finishes).
|
||||||
|
externalId String? @map("external_id")
|
||||||
|
displayPhoneNumber String? @map("display_phone_number")
|
||||||
|
// Provider-specific identifiers (Kapso: customerId, setupLinkId, businessAccountId).
|
||||||
|
// Never secrets: API keys and webhook secrets live in the environment.
|
||||||
|
providerData Json? @map("provider_data")
|
||||||
|
connectedAt DateTime? @map("connected_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "whatsapp_accounts_ownerId_fkey")
|
||||||
|
templates WhatsappTemplate[]
|
||||||
|
|
||||||
|
// A number (or session) cannot be linked to two teachers.
|
||||||
|
@@unique([provider, externalId], map: "whatsapp_accounts_provider_externalId_key")
|
||||||
|
@@map("whatsapp_accounts")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Message templates submitted to Meta for one account (Kapso only: OpenWA sends
|
||||||
|
// free text). Meta approves them per WhatsApp Business Account.
|
||||||
|
model WhatsappTemplate {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
accountId String @map("account_id")
|
||||||
|
kind WhatsappMessageKind
|
||||||
|
name String
|
||||||
|
language String
|
||||||
|
metaTemplateId String? @map("meta_template_id")
|
||||||
|
status WhatsappTemplateStatus @default(PENDING)
|
||||||
|
rejectedReason String? @map("rejected_reason")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
account WhatsappAccount @relation(fields: [accountId], references: [id], onDelete: Cascade, map: "whatsapp_templates_accountId_fkey")
|
||||||
|
|
||||||
|
@@unique([accountId, kind], map: "whatsapp_templates_accountId_kind_key")
|
||||||
|
@@index([status], map: "whatsapp_templates_status_idx")
|
||||||
|
@@map("whatsapp_templates")
|
||||||
|
}
|
||||||
|
|
||||||
|
// One automated message to one member. It is the send log and the idempotency
|
||||||
|
// key at once: the row is created before calling the provider, and the unique
|
||||||
|
// (kind, attendee, week) is what stops a second run of the weekly job from
|
||||||
|
// writing to the same person twice.
|
||||||
|
model OutboundMessage {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
ownerId String @map("owner_id")
|
||||||
|
groupId String @map("group_id")
|
||||||
|
attendeeId String @map("attendee_id")
|
||||||
|
paymentId String? @map("payment_id")
|
||||||
|
kind WhatsappMessageKind
|
||||||
|
provider MessagingProviderId
|
||||||
|
// ISO week the job ran for, e.g. "2026-W43".
|
||||||
|
periodKey String @map("period_key")
|
||||||
|
toPhone String @map("to_phone")
|
||||||
|
providerMessageId String? @map("provider_message_id")
|
||||||
|
status OutboundMessageStatus @default(QUEUED)
|
||||||
|
errorCode String? @map("error_code")
|
||||||
|
errorMessage String? @map("error_message")
|
||||||
|
sentAt DateTime? @map("sent_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade, map: "outbound_messages_groupId_fkey")
|
||||||
|
attendee Attendee @relation(fields: [attendeeId], references: [id], onDelete: Cascade, map: "outbound_messages_attendeeId_fkey")
|
||||||
|
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
|
||||||
|
|
||||||
|
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
|
||||||
|
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")
|
||||||
|
// Re-engagement cooldown: "was this member written to in the last 14 days?"
|
||||||
|
@@index([attendeeId, kind, createdAt], map: "outbound_messages_attendeeId_kind_createdAt_idx")
|
||||||
|
@@index([groupId, createdAt], map: "outbound_messages_groupId_createdAt_idx")
|
||||||
|
@@map("outbound_messages")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Webhook deliveries already processed. Both providers deliver at least once and
|
||||||
|
// retry, so the delivery's idempotency key is burned here before applying it.
|
||||||
|
model WhatsappWebhookEvent {
|
||||||
|
provider MessagingProviderId
|
||||||
|
dedupeKey String @map("dedupe_key")
|
||||||
|
receivedAt DateTime @default(now()) @map("received_at")
|
||||||
|
|
||||||
|
@@id([provider, dedupeKey], map: "whatsapp_webhook_events_pkey")
|
||||||
|
@@index([receivedAt], map: "whatsapp_webhook_events_receivedAt_idx")
|
||||||
|
@@map("whatsapp_webhook_events")
|
||||||
|
}
|
||||||
@@ -25,6 +25,7 @@ import { mpRoutes } from './modules/mp';
|
|||||||
import { onboardingRoutes } from './modules/onboarding';
|
import { onboardingRoutes } from './modules/onboarding';
|
||||||
import { paymentsRoutes } from './modules/payments';
|
import { paymentsRoutes } from './modules/payments';
|
||||||
import { waitlistRoutes } from './modules/waitlist';
|
import { waitlistRoutes } from './modules/waitlist';
|
||||||
|
import { whatsappRoutes } from './modules/whatsapp';
|
||||||
|
|
||||||
const app = new Hono<BackendEnv>();
|
const app = new Hono<BackendEnv>();
|
||||||
|
|
||||||
@@ -46,6 +47,7 @@ api.route('/groups', groupsRoutes);
|
|||||||
api.route('/home', homeRoutes);
|
api.route('/home', homeRoutes);
|
||||||
api.route('/onboarding', onboardingRoutes);
|
api.route('/onboarding', onboardingRoutes);
|
||||||
api.route('/mp', mpRoutes);
|
api.route('/mp', mpRoutes);
|
||||||
|
api.route('/whatsapp', whatsappRoutes);
|
||||||
api.route('/attendees', attendeesRoutes);
|
api.route('/attendees', attendeesRoutes);
|
||||||
api.route('/payments', paymentsRoutes);
|
api.route('/payments', paymentsRoutes);
|
||||||
api.route('/waitlist', waitlistRoutes);
|
api.route('/waitlist', waitlistRoutes);
|
||||||
|
|||||||
@@ -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 {
|
export function onboardingAlreadyCompletedProblem(): ProblemDetails {
|
||||||
return conflictProblem({
|
return conflictProblem({
|
||||||
detail: 'Ya completaste el onboarding de Gruperly.',
|
detail: 'Ya completaste el onboarding de Gruperly.',
|
||||||
|
|||||||
@@ -34,6 +34,14 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
|||||||
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
|
if (method === 'POST' && normalizedPath === '/api/v1/classes/notify-absence') {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
// WhatsApp provider webhooks: no session, authenticated by their HMAC signature.
|
||||||
|
if (
|
||||||
|
method === 'POST'
|
||||||
|
&& (normalizedPath === '/api/v1/whatsapp/webhooks/openwa'
|
||||||
|
|| normalizedPath === '/api/v1/whatsapp/webhooks/kapso')
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
normalizedPath === '/api/v1/health'
|
normalizedPath === '/api/v1/health'
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
import { ANALYTICS_WINDOW_MS } from '../get-overview/use-case';
|
||||||
|
|
||||||
type GetStudentsAtRiskDeps = {
|
type GetStudentsAtRiskDeps = {
|
||||||
db?: AnalyticsAccessDb & Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
|
db?: AnalyticsAccessDb & StudentsAtRiskDb;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -37,72 +37,13 @@ export class GetStudentsAtRisk {
|
|||||||
): Promise<Result<StudentsAtRisk, ProblemDetails>> {
|
): Promise<Result<StudentsAtRisk, ProblemDetails>> {
|
||||||
const db = this.deps.db ?? prisma;
|
const db = this.deps.db ?? prisma;
|
||||||
const now = this.deps.now ?? new Date();
|
const now = this.deps.now ?? new Date();
|
||||||
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
|
|
||||||
|
|
||||||
const access = await findGroupForUser(db, groupId, userId);
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
if (!access.ok) {
|
if (!access.ok) {
|
||||||
return access;
|
return access;
|
||||||
}
|
}
|
||||||
|
|
||||||
const [windowSessions, attendees, attendances] = await Promise.all([
|
const atRisk = await findStudentsAtRisk(db, groupId, now);
|
||||||
db.classSession.findMany({
|
|
||||||
where: { groupId, startsAt: { gte: since } },
|
|
||||||
select: { id: true },
|
|
||||||
}),
|
|
||||||
db.attendee.findMany({
|
|
||||||
where: { groupId, status: 'ACTIVE' },
|
|
||||||
select: { id: true, fullName: true, phone: true },
|
|
||||||
}),
|
|
||||||
db.attendance.findMany({
|
|
||||||
where: { attendee: { groupId } },
|
|
||||||
select: {
|
|
||||||
attendeeId: true,
|
|
||||||
status: true,
|
|
||||||
classSession: { select: { startsAt: true } },
|
|
||||||
},
|
|
||||||
orderBy: { classSession: { startsAt: 'desc' } },
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const totalWindowSessions = windowSessions.length;
|
|
||||||
const streamByAttendee = groupAttendanceByAttendee(attendances);
|
|
||||||
|
|
||||||
const atRisk: StudentAtRisk[] = [];
|
|
||||||
for (const attendee of attendees) {
|
|
||||||
const stream = (streamByAttendee.get(attendee.id) ?? []).map((row) => ({
|
|
||||||
status: row.status,
|
|
||||||
occurredAt: row.classSession.startsAt,
|
|
||||||
}));
|
|
||||||
const consecutiveAbsences = trailingAbsentStreak(stream);
|
|
||||||
const attendedAt = lastAttendedAt(stream);
|
|
||||||
const monthlyRate = monthlyAttendanceRate(
|
|
||||||
stream.filter((entry) => entry.occurredAt.getTime() >= since.getTime()),
|
|
||||||
totalWindowSessions,
|
|
||||||
);
|
|
||||||
const riskLevel = classifyRisk(consecutiveAbsences, monthlyRate);
|
|
||||||
if (!riskLevel) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
atRisk.push({
|
|
||||||
attendeeId: attendee.id,
|
|
||||||
fullName: attendee.fullName,
|
|
||||||
phone: attendee.phone,
|
|
||||||
riskLevel,
|
|
||||||
consecutiveAbsences,
|
|
||||||
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
|
|
||||||
monthlyAttendanceRate: monthlyRate,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
atRisk.sort((a, b) => {
|
|
||||||
if (a.riskLevel !== b.riskLevel) {
|
|
||||||
return a.riskLevel === 'HIGH' ? -1 : 1;
|
|
||||||
}
|
|
||||||
if (a.consecutiveAbsences !== b.consecutiveAbsences) {
|
|
||||||
return b.consecutiveAbsences - a.consecutiveAbsences;
|
|
||||||
}
|
|
||||||
return a.monthlyAttendanceRate - b.monthlyAttendanceRate;
|
|
||||||
});
|
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
groupName: access.value.name,
|
groupName: access.value.name,
|
||||||
@@ -111,6 +52,83 @@ export class GetStudentsAtRisk {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type StudentsAtRiskDb = Pick<PrismaClient, 'classSession' | 'attendee' | 'attendance'>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The ACTIVE members of a group who are at risk, most urgent first. Shared by
|
||||||
|
* the "Alumnos en riesgo" screen and the weekly re-engagement job, 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<StudentAtRisk[]> {
|
||||||
|
const since = new Date(now.getTime() - ANALYTICS_WINDOW_MS);
|
||||||
|
|
||||||
|
const [windowSessions, attendees, attendances] = await Promise.all([
|
||||||
|
db.classSession.findMany({
|
||||||
|
where: { groupId, startsAt: { gte: since } },
|
||||||
|
select: { id: true },
|
||||||
|
}),
|
||||||
|
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<string, AttendanceStreamRow[]> {
|
function groupAttendanceByAttendee(rows: AttendanceStreamRow[]): Map<string, AttendanceStreamRow[]> {
|
||||||
const byAttendee = new Map<string, AttendanceStreamRow[]>();
|
const byAttendee = new Map<string, AttendanceStreamRow[]>();
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ export type GroupRecord = {
|
|||||||
billingType: BillingType | null;
|
billingType: BillingType | null;
|
||||||
dueDay: number | null;
|
dueDay: number | null;
|
||||||
inviteToken?: string | null;
|
inviteToken?: string | null;
|
||||||
|
autoPaymentReminders?: boolean;
|
||||||
|
autoReengagement?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
/* The listing adds the occupancy counters to each group so the card can show
|
/* The listing adds the occupancy counters to each group so the card can show
|
||||||
@@ -44,6 +46,8 @@ export function toGroupDto(record: GroupRecord): GroupDto {
|
|||||||
billingType: record.billingType,
|
billingType: record.billingType,
|
||||||
dueDay: record.dueDay,
|
dueDay: record.dueDay,
|
||||||
inviteToken: record.inviteToken ?? null,
|
inviteToken: record.inviteToken ?? null,
|
||||||
|
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
||||||
|
autoReengagement: record.autoReengagement ?? false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import updateAttendeeRoute from '../attendees/features/update/route';
|
|||||||
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
import groupPreRegistrationRoutes from '../group-preregistrations/routes';
|
||||||
import groupWaitlistRoutes from '../group-waitlist/routes';
|
import groupWaitlistRoutes from '../group-waitlist/routes';
|
||||||
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
|
||||||
|
import updateGroupAutomationsRoute from '../whatsapp/features/update-automations/route';
|
||||||
import createGroupRoute from './features/create/route';
|
import createGroupRoute from './features/create/route';
|
||||||
import getAllRoute from './features/get-all/route';
|
import getAllRoute from './features/get-all/route';
|
||||||
import getByIdRoute from './features/get-by-id/route';
|
import getByIdRoute from './features/get-by-id/route';
|
||||||
@@ -26,6 +27,7 @@ routes.route('/', createAttendeeRoute);
|
|||||||
routes.route('/', bulkCreateAttendeesRoute);
|
routes.route('/', bulkCreateAttendeesRoute);
|
||||||
routes.route('/', getByIdRoute);
|
routes.route('/', getByIdRoute);
|
||||||
routes.route('/', createPaymentsBatchRoute);
|
routes.route('/', createPaymentsBatchRoute);
|
||||||
|
routes.route('/', updateGroupAutomationsRoute);
|
||||||
routes.route('/', addToGroupWaitlistRoute);
|
routes.route('/', addToGroupWaitlistRoute);
|
||||||
routes.route('/', groupWaitlistRoutes);
|
routes.route('/', groupWaitlistRoutes);
|
||||||
routes.route('/', groupPreRegistrationRoutes);
|
routes.route('/', groupPreRegistrationRoutes);
|
||||||
|
|||||||
@@ -3,8 +3,11 @@ import type { OnboardingStatusDto, ProblemDetails, Result } from '@gruperly/shar
|
|||||||
import { err, ok } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import { problemDetails } from '@/http/problem-details';
|
import { problemDetails } from '@/http/problem-details';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { isWhatsappAccountUsable } from '@/modules/whatsapp/lib/account';
|
||||||
|
|
||||||
type GetOnboardingStatusDeps = { db?: Pick<PrismaClient, 'user' | 'mpAccount'> };
|
type GetOnboardingStatusDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'user' | 'mpAccount' | 'whatsappAccount'>;
|
||||||
|
};
|
||||||
|
|
||||||
export class GetOnboardingStatus {
|
export class GetOnboardingStatus {
|
||||||
constructor(private readonly deps: GetOnboardingStatusDeps = {}) {}
|
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) {
|
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
|
// 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.
|
// need to see the "Cobros" step again. A `revoked` row is not usable.
|
||||||
const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } });
|
const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } });
|
||||||
if (mpAccount && mpAccount.status === 'ACTIVE') {
|
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 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,8 @@ export type OnboardingGroupRecord = {
|
|||||||
price: PriceLike | number | null;
|
price: PriceLike | number | null;
|
||||||
billingType: BillingType | null;
|
billingType: BillingType | null;
|
||||||
dueDay: number | null;
|
dueDay: number | null;
|
||||||
|
autoPaymentReminders?: boolean;
|
||||||
|
autoReengagement?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
|
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()),
|
price: record.price == null ? null : Number(record.price.toString()),
|
||||||
billingType: record.billingType,
|
billingType: record.billingType,
|
||||||
dueDay: record.dueDay,
|
dueDay: record.dueDay,
|
||||||
|
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
||||||
|
autoReengagement: record.autoReengagement ?? false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
33
apps/backend/src/modules/whatsapp/features/callback/route.ts
Normal file
33
apps/backend/src/modules/whatsapp/features/callback/route.ts
Normal file
@@ -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;
|
||||||
@@ -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<PrismaClient, 'whatsappAccount'>;
|
||||||
|
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<string, string | undefined>,
|
||||||
|
): Promise<WhatsappCallbackOutcome> {
|
||||||
|
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();
|
||||||
|
}
|
||||||
21
apps/backend/src/modules/whatsapp/features/connect/route.ts
Normal file
21
apps/backend/src/modules/whatsapp/features/connect/route.ts
Normal file
@@ -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;
|
||||||
@@ -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<PrismaClient, 'whatsappAccount'>;
|
||||||
|
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<Result<WhatsappConnectResultDto, ProblemDetails>> {
|
||||||
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
@@ -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<PrismaClient, 'whatsappAccount'>;
|
||||||
|
/** 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<Result<WhatsappDisconnectResultDto, ProblemDetails>> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
16
apps/backend/src/modules/whatsapp/features/status/route.ts
Normal file
16
apps/backend/src/modules/whatsapp/features/status/route.ts
Normal file
@@ -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;
|
||||||
105
apps/backend/src/modules/whatsapp/features/status/use-case.ts
Normal file
105
apps/backend/src/modules/whatsapp/features/status/use-case.ts
Normal file
@@ -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<PrismaClient, 'whatsappAccount'>;
|
||||||
|
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<Result<WhatsappStatusDto, ProblemDetails>> {
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
@@ -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<PrismaClient, 'group'> };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<Result<GroupAutomationsDto, ProblemDetails>> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
32
apps/backend/src/modules/whatsapp/features/webhook/route.ts
Normal file
32
apps/backend/src/modules/whatsapp/features/webhook/route.ts
Normal file
@@ -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<string, MessagingProviderId> = { 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;
|
||||||
138
apps/backend/src/modules/whatsapp/features/webhook/use-case.ts
Normal file
138
apps/backend/src/modules/whatsapp/features/webhook/use-case.ts
Normal file
@@ -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<PrismaClient, 'whatsappAccount' | 'whatsappWebhookEvent' | 'outboundMessage'>;
|
||||||
|
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<MessageDeliveryStatus, OutboundMessageStatus[]> = {
|
||||||
|
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<Result<{ duplicate: boolean; applied: number }, WebhookFailure>> {
|
||||||
|
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<HandleWhatsappWebhookDeps['db']>,
|
||||||
|
provider: MessagingProvider,
|
||||||
|
event: NormalizedEvent,
|
||||||
|
): Promise<boolean> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
2
apps/backend/src/modules/whatsapp/index.ts
Normal file
2
apps/backend/src/modules/whatsapp/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { startWhatsappJobs } from './jobs';
|
||||||
|
export { default as whatsappRoutes } from './routes';
|
||||||
59
apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts
Normal file
59
apps/backend/src/modules/whatsapp/jobs/eligible-accounts.ts
Normal file
@@ -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<PrismaClient, 'group'>,
|
||||||
|
provider: MessagingProvider,
|
||||||
|
flag: AutomationFlag,
|
||||||
|
kind: WhatsappMessageKind,
|
||||||
|
): Promise<EligibleAccount[]> {
|
||||||
|
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<string, EligibleAccount>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
4
apps/backend/src/modules/whatsapp/jobs/index.ts
Normal file
4
apps/backend/src/modules/whatsapp/jobs/index.ts
Normal file
@@ -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';
|
||||||
63
apps/backend/src/modules/whatsapp/jobs/schedule.ts
Normal file
63
apps/backend/src/modules/whatsapp/jobs/schedule.ts
Normal file
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
113
apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts
Normal file
113
apps/backend/src/modules/whatsapp/jobs/send-payment-reminders.ts
Normal file
@@ -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<PrismaClient, 'group' | 'payment' | 'outboundMessage'>;
|
||||||
|
provider?: MessagingProvider;
|
||||||
|
now?: Date;
|
||||||
|
intervalMs?: number;
|
||||||
|
sleep?: (ms: number) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<DispatchTotals> {
|
||||||
|
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<string>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<PrismaClient, 'group' | 'attendee' | 'outboundMessage'> & StudentsAtRiskDb;
|
||||||
|
provider?: MessagingProvider;
|
||||||
|
now?: Date;
|
||||||
|
intervalMs?: number;
|
||||||
|
sleep?: (ms: number) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<DispatchTotals> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>;
|
||||||
|
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<SyncKapsoTemplatesResult> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
43
apps/backend/src/modules/whatsapp/lib/account.ts
Normal file
43
apps/backend/src/modules/whatsapp/lib/account.ts
Normal file
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
74
apps/backend/src/modules/whatsapp/lib/activate-account.ts
Normal file
74
apps/backend/src/modules/whatsapp/lib/activate-account.ts
Normal file
@@ -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<PrismaClient, 'whatsappAccount'>;
|
||||||
|
|
||||||
|
/** 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<string, string> | 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<string, string> | null | undefined,
|
||||||
|
): Prisma.InputJsonObject {
|
||||||
|
const base = current && typeof current === 'object' && !Array.isArray(current) ? current : {};
|
||||||
|
return { ...(base as Record<string, string>), ...(next ?? {}) };
|
||||||
|
}
|
||||||
171
apps/backend/src/modules/whatsapp/lib/dispatch.ts
Normal file
171
apps/backend/src/modules/whatsapp/lib/dispatch.ts
Normal file
@@ -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<PrismaClient, 'outboundMessage'>;
|
||||||
|
|
||||||
|
/** 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<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 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<void>((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<DispatchTotals> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
50
apps/backend/src/modules/whatsapp/lib/format.ts
Normal file
50
apps/backend/src/modules/whatsapp/lib/format.ts
Normal file
@@ -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<CountryCode, string> = {
|
||||||
|
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<CountryCode, string> = {
|
||||||
|
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);
|
||||||
|
}
|
||||||
24
apps/backend/src/modules/whatsapp/lib/hmac.ts
Normal file
24
apps/backend/src/modules/whatsapp/lib/hmac.ts
Normal file
@@ -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=<hex>` (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);
|
||||||
|
}
|
||||||
16
apps/backend/src/modules/whatsapp/lib/period.ts
Normal file
16
apps/backend/src/modules/whatsapp/lib/period.ts
Normal file
@@ -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')}`;
|
||||||
|
}
|
||||||
33
apps/backend/src/modules/whatsapp/lib/render-message.ts
Normal file
33
apps/backend/src/modules/whatsapp/lib/render-message.ts
Normal file
@@ -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;
|
||||||
|
}
|
||||||
19
apps/backend/src/modules/whatsapp/providers/active.ts
Normal file
19
apps/backend/src/modules/whatsapp/providers/active.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import type { MessagingProviderId } from './messaging-provider';
|
||||||
|
|
||||||
|
const PROVIDERS: Record<string, MessagingProviderId> = {
|
||||||
|
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;
|
||||||
|
}
|
||||||
40
apps/backend/src/modules/whatsapp/providers/index.ts
Normal file
40
apps/backend/src/modules/whatsapp/providers/index.ts
Normal file
@@ -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/<name>/` 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<MessagingProvider, ProblemDetails> {
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
47
apps/backend/src/modules/whatsapp/providers/kapso/config.ts
Normal file
47
apps/backend/src/modules/whatsapp/providers/kapso/config.ts
Normal file
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
210
apps/backend/src/modules/whatsapp/providers/kapso/http.ts
Normal file
210
apps/backend/src/modules/whatsapp/providers/kapso/http.ts
Normal file
@@ -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<Response>;
|
||||||
|
|
||||||
|
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<KapsoPhoneNumber> {
|
||||||
|
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<MetaTemplate[]> {
|
||||||
|
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<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||||
|
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);
|
||||||
|
}
|
||||||
436
apps/backend/src/modules/whatsapp/providers/kapso/index.ts
Normal file
436
apps/backend/src/modules/whatsapp/providers/kapso/index.ts
Normal file
@@ -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<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>;
|
||||||
|
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<Result<StartConnectionResult, ProblemDetails>> {
|
||||||
|
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<Result<ConnectionSnapshot, ProblemDetails>> {
|
||||||
|
// 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<string, string | undefined>,
|
||||||
|
): Promise<Result<CompletedConnection, WhatsappCallbackReason>> {
|
||||||
|
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<Result<void, ProblemDetails>> {
|
||||||
|
// 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<void> {
|
||||||
|
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<WhatsappReadiness> {
|
||||||
|
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<RecipientResolution> {
|
||||||
|
// 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<SendOutcome> {
|
||||||
|
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<ParsedWebhook, WebhookParseError> {
|
||||||
|
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<number> {
|
||||||
|
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<void> {
|
||||||
|
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<string, MessageDeliveryStatus> = {
|
||||||
|
'whatsapp.message.sent': 'SENT',
|
||||||
|
'whatsapp.message.delivered': 'DELIVERED',
|
||||||
|
'whatsapp.message.read': 'READ',
|
||||||
|
'whatsapp.message.failed': 'FAILED',
|
||||||
|
};
|
||||||
|
|
||||||
|
function toEvents(item: Record<string, unknown>, 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<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stringAt(value: Record<string, unknown>, ...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<string, string> {
|
||||||
|
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) };
|
||||||
|
}
|
||||||
104
apps/backend/src/modules/whatsapp/providers/kapso/templates.ts
Normal file
104
apps/backend/src/modules/whatsapp/providers/kapso/templates.ts
Normal file
@@ -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<WhatsappMessageKind, TemplateSpec> = {
|
||||||
|
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';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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/<name>/`. 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<string, string> | 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<string, string> | 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<string, string> | 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<Result<StartConnectionResult, ProblemDetails>>;
|
||||||
|
|
||||||
|
/** Asks the provider how the linking is going (fresh QR, linked, failed). */
|
||||||
|
refreshConnection(
|
||||||
|
account: WhatsappAccountRecord,
|
||||||
|
): Promise<Result<ConnectionSnapshot, ProblemDetails>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finishes a redirect-based linking from the callback query. Only providers
|
||||||
|
* whose `startConnection` answers `redirect` implement it.
|
||||||
|
*/
|
||||||
|
completeRedirect?(
|
||||||
|
account: WhatsappAccountRecord,
|
||||||
|
query: Record<string, string | undefined>,
|
||||||
|
): Promise<Result<CompletedConnection, WhatsappCallbackReason>>;
|
||||||
|
|
||||||
|
/** Unlinks the number on the provider side. Best effort. */
|
||||||
|
disconnect(account: WhatsappAccountRecord): Promise<Result<void, ProblemDetails>>;
|
||||||
|
|
||||||
|
/** Runs once the account becomes ACTIVE (Kapso: templates and webhooks). */
|
||||||
|
onConnected?(account: WhatsappAccountRecord): Promise<void>;
|
||||||
|
|
||||||
|
/** Whether a message of this kind can be sent from the account right now. */
|
||||||
|
readiness(account: WhatsappAccountRecord, kind: WhatsappMessageKind): Promise<WhatsappReadiness>;
|
||||||
|
|
||||||
|
/** Turns an E.164 number into the provider's recipient id, or says it has no WhatsApp. */
|
||||||
|
resolveRecipient(account: WhatsappAccountRecord, e164: string): Promise<RecipientResolution>;
|
||||||
|
|
||||||
|
send(
|
||||||
|
account: WhatsappAccountRecord,
|
||||||
|
to: string,
|
||||||
|
message: WhatsappMessage,
|
||||||
|
idempotencyKey: string,
|
||||||
|
): Promise<SendOutcome>;
|
||||||
|
|
||||||
|
/** Verifies the signature over the raw body and normalizes the payload. */
|
||||||
|
parseWebhook(
|
||||||
|
rawBody: string,
|
||||||
|
headers: Headers,
|
||||||
|
): Result<ParsedWebhook, WebhookParseError>;
|
||||||
|
}
|
||||||
51
apps/backend/src/modules/whatsapp/providers/openwa/config.ts
Normal file
51
apps/backend/src/modules/whatsapp/providers/openwa/config.ts
Normal file
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
156
apps/backend/src/modules/whatsapp/providers/openwa/http.ts
Normal file
156
apps/backend/src/modules/whatsapp/providers/openwa/http.ts
Normal file
@@ -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<Response>;
|
||||||
|
|
||||||
|
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<OpenWaSession> {
|
||||||
|
return this.request('GET', `/sessions/${encodeURIComponent(sessionId)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findSessionByName(name: string): Promise<OpenWaSession | null> {
|
||||||
|
const sessions = await this.request<OpenWaSession[]>(
|
||||||
|
'GET',
|
||||||
|
`/sessions?name=${encodeURIComponent(name)}`,
|
||||||
|
);
|
||||||
|
return sessions[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
createSession(name: string): Promise<OpenWaSession> {
|
||||||
|
return this.request('POST', '/sessions', { name });
|
||||||
|
}
|
||||||
|
|
||||||
|
startSession(sessionId: string): Promise<OpenWaSession> {
|
||||||
|
return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/start`);
|
||||||
|
}
|
||||||
|
|
||||||
|
logoutSession(sessionId: string): Promise<OpenWaSession> {
|
||||||
|
return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/logout`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteSession(sessionId: string): Promise<void> {
|
||||||
|
await this.request('DELETE', `/sessions/${encodeURIComponent(sessionId)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getQrCode(sessionId: string): Promise<string | null> {
|
||||||
|
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<T>(
|
||||||
|
method: string,
|
||||||
|
path: string,
|
||||||
|
body?: unknown,
|
||||||
|
extraHeaders: Record<string, string> = {},
|
||||||
|
): Promise<T> {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
374
apps/backend/src/modules/whatsapp/providers/openwa/index.ts
Normal file
374
apps/backend/src/modules/whatsapp/providers/openwa/index.ts
Normal file
@@ -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<Result<StartConnectionResult, ProblemDetails>> {
|
||||||
|
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<Result<ConnectionSnapshot, ProblemDetails>> {
|
||||||
|
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<Result<void, ProblemDetails>> {
|
||||||
|
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<WhatsappReadiness> {
|
||||||
|
return account.status === 'ACTIVE' ? 'ready' : 'blocked';
|
||||||
|
}
|
||||||
|
|
||||||
|
async resolveRecipient(
|
||||||
|
account: WhatsappAccountRecord,
|
||||||
|
e164: string,
|
||||||
|
): Promise<RecipientResolution> {
|
||||||
|
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<SendOutcome> {
|
||||||
|
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<ParsedWebhook, WebhookParseError> {
|
||||||
|
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<OpenWaSession | null> {
|
||||||
|
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<OpenWaSession> {
|
||||||
|
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<string | null> {
|
||||||
|
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<string | null> {
|
||||||
|
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<string, unknown>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ACK_STATUSES: Record<string, MessageDeliveryStatus> = {
|
||||||
|
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<string, string | undefined> {
|
||||||
|
return value && typeof value === 'object' ? (value as Record<string, string | undefined>) : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
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) };
|
||||||
|
}
|
||||||
18
apps/backend/src/modules/whatsapp/routes.ts
Normal file
18
apps/backend/src/modules/whatsapp/routes.ts
Normal file
@@ -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;
|
||||||
@@ -3,6 +3,7 @@ import { getPrismaClient } from '@/lib/prisma';
|
|||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { startMpJobs } from '@/modules/mp';
|
import { startMpJobs } from '@/modules/mp';
|
||||||
import { startPaymentJobs } from '@/modules/payments';
|
import { startPaymentJobs } from '@/modules/payments';
|
||||||
|
import { startWhatsappJobs } from '@/modules/whatsapp';
|
||||||
|
|
||||||
const port = Number(process.env.PORT ?? 4000);
|
const port = Number(process.env.PORT ?? 4000);
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ const server = Bun.serve({
|
|||||||
|
|
||||||
startMpJobs();
|
startMpJobs();
|
||||||
startPaymentJobs();
|
startPaymentJobs();
|
||||||
|
startWhatsappJobs();
|
||||||
|
|
||||||
async function shutdown(): Promise<void> {
|
async function shutdown(): Promise<void> {
|
||||||
server.stop(true);
|
server.stop(true);
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ const group = {
|
|||||||
billingType: null,
|
billingType: null,
|
||||||
dueDay: null,
|
dueDay: null,
|
||||||
inviteToken: null,
|
inviteToken: null,
|
||||||
|
autoPaymentReminders: false,
|
||||||
|
autoReengagement: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
function makeApp(userValue: unknown) {
|
function makeApp(userValue: unknown) {
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ const db = {
|
|||||||
mpAccount: {
|
mpAccount: {
|
||||||
findUnique: mock(),
|
findUnique: mock(),
|
||||||
},
|
},
|
||||||
|
whatsappAccount: {
|
||||||
|
findUnique: mock(async () => null),
|
||||||
|
},
|
||||||
group: {
|
group: {
|
||||||
create: mock(),
|
create: mock(),
|
||||||
},
|
},
|
||||||
@@ -54,6 +57,8 @@ const group = {
|
|||||||
price: 150.5,
|
price: 150.5,
|
||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 5,
|
dueDay: 5,
|
||||||
|
autoPaymentReminders: false,
|
||||||
|
autoReengagement: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const firstGroupPayload = {
|
const firstGroupPayload = {
|
||||||
@@ -83,6 +88,7 @@ describe('onboarding routes', () => {
|
|||||||
expect(await res.json()).toEqual({
|
expect(await res.json()).toEqual({
|
||||||
step: 'NOT_STARTED',
|
step: 'NOT_STARTED',
|
||||||
paymentConnected: false,
|
paymentConnected: false,
|
||||||
|
whatsappConnected: false,
|
||||||
completed: false,
|
completed: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -97,6 +103,7 @@ describe('onboarding routes', () => {
|
|||||||
expect(await res.json()).toEqual({
|
expect(await res.json()).toEqual({
|
||||||
step: 'PAYMENT_CONNECTED',
|
step: 'PAYMENT_CONNECTED',
|
||||||
paymentConnected: true,
|
paymentConnected: true,
|
||||||
|
whatsappConnected: false,
|
||||||
completed: false,
|
completed: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -115,6 +122,7 @@ describe('onboarding routes', () => {
|
|||||||
expect(await res.json()).toEqual({
|
expect(await res.json()).toEqual({
|
||||||
step: 'NOT_STARTED',
|
step: 'NOT_STARTED',
|
||||||
paymentConnected: false,
|
paymentConnected: false,
|
||||||
|
whatsappConnected: false,
|
||||||
completed: false,
|
completed: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -128,6 +136,7 @@ describe('onboarding routes', () => {
|
|||||||
expect(await res.json()).toEqual({
|
expect(await res.json()).toEqual({
|
||||||
step: 'COMPLETED',
|
step: 'COMPLETED',
|
||||||
paymentConnected: true,
|
paymentConnected: true,
|
||||||
|
whatsappConnected: false,
|
||||||
completed: true,
|
completed: true,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -166,6 +175,8 @@ describe('onboarding routes', () => {
|
|||||||
price: 150.5,
|
price: 150.5,
|
||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 5,
|
dueDay: 5,
|
||||||
|
autoPaymentReminders: false,
|
||||||
|
autoReengagement: false,
|
||||||
},
|
},
|
||||||
onboardingCompleted: true,
|
onboardingCompleted: true,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -50,6 +50,17 @@ describe('session auth', () => {
|
|||||||
).toBe(false);
|
).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 () => {
|
it('allows public requests without a session', async () => {
|
||||||
const app = new Hono();
|
const app = new Hono();
|
||||||
app.use('*', sessionAuthMiddleware);
|
app.use('*', sessionAuthMiddleware);
|
||||||
|
|||||||
590
apps/backend/test/whatsapp-core.test.ts
Normal file
590
apps/backend/test/whatsapp-core.test.ts
Normal file
@@ -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> = {}): 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<string, unknown> = {}) {
|
||||||
|
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<string, unknown> }) => account({ ...data })),
|
||||||
|
},
|
||||||
|
whatsappWebhookEvent: {
|
||||||
|
create: mock(async () => ({})),
|
||||||
|
delete: mock(async () => ({})),
|
||||||
|
},
|
||||||
|
outboundMessage: {
|
||||||
|
updateMany: mock(async () => ({ count: 1 })),
|
||||||
|
},
|
||||||
|
group: {
|
||||||
|
findUnique: mock(),
|
||||||
|
update: mock(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type Db = ReturnType<typeof makeDb>;
|
||||||
|
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<string, unknown>;
|
||||||
|
update: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
383
apps/backend/test/whatsapp-jobs.test.ts
Normal file
383
apps/backend/test/whatsapp-jobs.test.ts
Normal file
@@ -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<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
id: 'group-1',
|
||||||
|
name: 'Yoga Martes',
|
||||||
|
createdById: ownerId,
|
||||||
|
owner: { country: 'AR', whatsappAccount: activeAccount },
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function payment(id: string, attendee: Record<string, unknown>, overrides: Record<string, unknown> = {}) {
|
||||||
|
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> = {}): 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<typeof makeDb>;
|
||||||
|
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<typeof mock>).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<typeof mock>).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');
|
||||||
|
});
|
||||||
|
});
|
||||||
600
apps/backend/test/whatsapp-providers.test.ts
Normal file
600
apps/backend/test/whatsapp-providers.test.ts
Normal file
@@ -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<string, string>; body: unknown }[] = [];
|
||||||
|
const fn = mock(async (url: string, init?: RequestInit) => {
|
||||||
|
const method = init?.method ?? 'GET';
|
||||||
|
calls.push({
|
||||||
|
method,
|
||||||
|
url,
|
||||||
|
headers: (init?.headers ?? {}) as Record<string, string>,
|
||||||
|
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> = {}): 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> = {}): 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' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -7,3 +7,4 @@ export { Modal, type ModalProps } from './modal'
|
|||||||
export { type Toast, ToastProvider, type ToastType, useToast } from './toast'
|
export { type Toast, ToastProvider, type ToastType, useToast } from './toast'
|
||||||
export { Tooltip, type TooltipProps } from './tooltip'
|
export { Tooltip, type TooltipProps } from './tooltip'
|
||||||
|
|
||||||
|
export { Switch, type SwitchProps } from './switch'
|
||||||
|
|||||||
40
apps/web/src/components/ui/switch.tsx
Normal file
40
apps/web/src/components/ui/switch.tsx
Normal file
@@ -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 `<label>` asociado. */
|
||||||
|
'aria-label'?: string
|
||||||
|
'aria-describedby'?: string
|
||||||
|
id?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Interruptor on/off accesible (`role="switch"`), sin Radix. */
|
||||||
|
export function Switch({ checked, onCheckedChange, disabled, id, ...aria }: SwitchProps) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
id={id}
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-checked={checked}
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => onCheckedChange(!checked)}
|
||||||
|
className={cn(
|
||||||
|
'relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors',
|
||||||
|
'focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent',
|
||||||
|
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
checked ? 'bg-accent' : 'bg-foreground/20',
|
||||||
|
)}
|
||||||
|
{...aria}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn(
|
||||||
|
'inline-block size-5 rounded-full bg-white shadow transition-transform',
|
||||||
|
checked ? 'translate-x-5' : 'translate-x-0.5',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
89
apps/web/src/features/groups/detail/GroupAutomationsCard.tsx
Normal file
89
apps/web/src/features/groups/detail/GroupAutomationsCard.tsx
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import type { GroupAutomationsDto } from '@gruperly/shared'
|
||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { MessageCircle } from 'lucide-react'
|
||||||
|
import { Switch } from '../../../components/ui'
|
||||||
|
import { automationBlockedReason, useWhatsappStatus, WEEKLY_SEND_LABEL } from '../../whatsapp'
|
||||||
|
import { useGroupDetail } from './GroupDetailProvider'
|
||||||
|
|
||||||
|
type Automation = {
|
||||||
|
key: keyof GroupAutomationsDto
|
||||||
|
kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT'
|
||||||
|
title: string
|
||||||
|
description: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const AUTOMATIONS: readonly Automation[] = [
|
||||||
|
{
|
||||||
|
key: 'autoPaymentReminders',
|
||||||
|
kind: 'PAYMENT_REMINDER',
|
||||||
|
title: 'Recordatorio semanal de pago',
|
||||||
|
description: 'A quien tenga un cobro pendiente o vencido, con su link de pago.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'autoReengagement',
|
||||||
|
kind: 'REENGAGEMENT',
|
||||||
|
title: 'Mensaje de reenganche semanal',
|
||||||
|
description: 'A los miembros en riesgo por faltas. Como mucho uno cada 2 semanas.',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Los envíos automáticos por WhatsApp del grupo. Solo el dueño los cambia: los
|
||||||
|
* mensajes salen de su número. Se pueden apagar siempre; prenderlos exige un
|
||||||
|
* WhatsApp vinculado y el mensaje aprobado.
|
||||||
|
*/
|
||||||
|
export function GroupAutomationsCard() {
|
||||||
|
const { group, updateAutomations, isUpdatingAutomations, isGroupOwner } = useGroupDetail()
|
||||||
|
const whatsappQuery = useWhatsappStatus({ enabled: isGroupOwner })
|
||||||
|
if (!group || !isGroupOwner) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-xl border border-border bg-surface">
|
||||||
|
<header className="flex items-start gap-3 px-4 pt-3">
|
||||||
|
<span className="rounded-lg bg-success-soft p-2">
|
||||||
|
<MessageCircle className="size-4 text-success" />
|
||||||
|
</span>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<h2 className="text-sm font-semibold text-primary">Mensajes automáticos por WhatsApp</h2>
|
||||||
|
<p className="text-xs text-foreground/50">{WEEKLY_SEND_LABEL}</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<ul className="divide-y divide-border">
|
||||||
|
{AUTOMATIONS.map((automation) => {
|
||||||
|
const checked = group[automation.key]
|
||||||
|
const blocked = automationBlockedReason(whatsappQuery.data, automation.kind)
|
||||||
|
const hintId = `automation-${automation.key}-hint`
|
||||||
|
return (
|
||||||
|
<li key={automation.key} className="flex items-start gap-3 px-4 py-3">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm text-primary">{automation.title}</p>
|
||||||
|
<p id={hintId} className="text-xs text-foreground/50">
|
||||||
|
{automation.description}
|
||||||
|
{blocked && !checked ? (
|
||||||
|
<>
|
||||||
|
{' '}
|
||||||
|
<span className="text-warning">{blocked}</span>{' '}
|
||||||
|
{whatsappQuery.data?.status !== 'active' ? (
|
||||||
|
<Link to="/settings" className="font-medium text-accent-fg underline">
|
||||||
|
Ir a Ajustes
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={checked}
|
||||||
|
disabled={isUpdatingAutomations || (!checked && blocked !== null)}
|
||||||
|
aria-label={automation.title}
|
||||||
|
aria-describedby={hintId}
|
||||||
|
onCheckedChange={(next) => updateAutomations({ [automation.key]: next })}
|
||||||
|
/>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'
|
|||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import type {
|
import type {
|
||||||
AttendeeDto,
|
AttendeeDto,
|
||||||
|
UpdateGroupAutomations,
|
||||||
AttendeeListItem,
|
AttendeeListItem,
|
||||||
GroupDto,
|
GroupDto,
|
||||||
GroupPreRegistrationDto,
|
GroupPreRegistrationDto,
|
||||||
@@ -10,6 +11,7 @@ import type {
|
|||||||
GroupRiskLevel,
|
GroupRiskLevel,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
import { useToast } from '../../../components/ui'
|
import { useToast } from '../../../components/ui'
|
||||||
|
import { useAuth } from '../../../context/AuthProvider'
|
||||||
import {
|
import {
|
||||||
ApiError,
|
ApiError,
|
||||||
approveGroupPreRegistration,
|
approveGroupPreRegistration,
|
||||||
@@ -22,6 +24,7 @@ import {
|
|||||||
promoteGroupWaitlistEntry,
|
promoteGroupWaitlistEntry,
|
||||||
rejectGroupPreRegistration,
|
rejectGroupPreRegistration,
|
||||||
removeGroupWaitlistEntry,
|
removeGroupWaitlistEntry,
|
||||||
|
updateGroupAutomations,
|
||||||
} from '../../../lib/api'
|
} from '../../../lib/api'
|
||||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||||
|
|
||||||
@@ -80,6 +83,10 @@ type GroupDetailContextValue = {
|
|||||||
copyInviteLink: () => Promise<void>
|
copyInviteLink: () => Promise<void>
|
||||||
copyWhatsappMessage: () => Promise<void>
|
copyWhatsappMessage: () => Promise<void>
|
||||||
openWhatsapp: () => Promise<void>
|
openWhatsapp: () => Promise<void>
|
||||||
|
/** Solo el dueño ve y cambia las automatizaciones: salen de su WhatsApp. */
|
||||||
|
isGroupOwner: boolean
|
||||||
|
updateAutomations: (patch: UpdateGroupAutomations) => void
|
||||||
|
isUpdatingAutomations: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
||||||
@@ -87,6 +94,7 @@ const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
|||||||
export function GroupDetailProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
export function GroupDetailProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const toast = useToast()
|
const toast = useToast()
|
||||||
|
const { user } = useAuth()
|
||||||
|
|
||||||
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
||||||
const [listSection, setListSectionState] = useState<ListSection>('members')
|
const [listSection, setListSectionState] = useState<ListSection>('members')
|
||||||
@@ -172,6 +180,19 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const automationsMutation = useMutation({
|
||||||
|
mutationFn: (patch: UpdateGroupAutomations) => updateGroupAutomations(groupId, patch),
|
||||||
|
onSuccess: (automations) => {
|
||||||
|
queryClient.setQueryData<GroupDto>(['group', groupId], (current) =>
|
||||||
|
current ? { ...current, ...automations } : current,
|
||||||
|
)
|
||||||
|
toast.success('Guardamos los mensajes automáticos del grupo.')
|
||||||
|
},
|
||||||
|
onError: (err: Error) => {
|
||||||
|
toast.error(err.message || 'No se pudieron guardar los mensajes automáticos.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const removeAttendeeMutation = useRemoveAttendee({
|
const removeAttendeeMutation = useRemoveAttendee({
|
||||||
groupId,
|
groupId,
|
||||||
onRemoved: () => setAttendeeToRemove(null),
|
onRemoved: () => setAttendeeToRemove(null),
|
||||||
@@ -303,6 +324,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
|||||||
group,
|
group,
|
||||||
groupTitle,
|
groupTitle,
|
||||||
groupQueryPending: groupQuery.isPending,
|
groupQueryPending: groupQuery.isPending,
|
||||||
|
isGroupOwner: Boolean(group && user && group.createdById === user.id),
|
||||||
|
updateAutomations: (patch) => automationsMutation.mutate(patch),
|
||||||
|
isUpdatingAutomations: automationsMutation.isPending,
|
||||||
riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE',
|
riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE',
|
||||||
attendees,
|
attendees,
|
||||||
attendeesTotal,
|
attendeesTotal,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Loader2 } from 'lucide-react'
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { Button } from '../../../components/ui'
|
import { Button } from '../../../components/ui'
|
||||||
import { ChargeMembersModal } from './ChargeMembersModal'
|
import { ChargeMembersModal } from './ChargeMembersModal'
|
||||||
|
import { GroupAutomationsCard } from './GroupAutomationsCard'
|
||||||
import { GroupHeader } from './GroupHeader'
|
import { GroupHeader } from './GroupHeader'
|
||||||
import { GroupInfoCard } from './GroupInfoCard'
|
import { GroupInfoCard } from './GroupInfoCard'
|
||||||
import { InviteLinkModal } from './InviteLinkModal'
|
import { InviteLinkModal } from './InviteLinkModal'
|
||||||
@@ -52,6 +53,7 @@ export function GroupDetailView() {
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<GroupInfoCard />
|
<GroupInfoCard />
|
||||||
|
<GroupAutomationsCard />
|
||||||
<MembersWaitlistSection />
|
<MembersWaitlistSection />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import type { OnboardingGroupDto } from '@gruperly/shared'
|
import type { OnboardingGroupDto } from '@gruperly/shared'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { ArrowRight, CheckCircle2, CreditCard } from 'lucide-react'
|
import { ArrowRight, CheckCircle2, CreditCard, MessageCircle } from 'lucide-react'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { Badge, Button } from '../../components/ui'
|
||||||
import { useAuth } from '../../context/AuthProvider'
|
import { useAuth } from '../../context/AuthProvider'
|
||||||
import { MP_PROVIDER_NAME, useMpStatus } from '../mp'
|
import { MP_PROVIDER_NAME, useMpStatus } from '../mp'
|
||||||
|
import { useWhatsappStatus } from '../whatsapp'
|
||||||
import { BILLING_LABELS, formatPrice, formatSchedule } from './constants'
|
import { BILLING_LABELS, formatPrice, formatSchedule } from './constants'
|
||||||
|
|
||||||
type ConfirmationStepProps = {
|
type ConfirmationStepProps = {
|
||||||
@@ -17,6 +18,8 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
|
|||||||
const { refresh } = useAuth()
|
const { refresh } = useAuth()
|
||||||
const statusQuery = useMpStatus()
|
const statusQuery = useMpStatus()
|
||||||
const isMpConnected = statusQuery.data?.status === 'active'
|
const isMpConnected = statusQuery.data?.status === 'active'
|
||||||
|
const whatsappQuery = useWhatsappStatus()
|
||||||
|
const isWhatsappConnected = whatsappQuery.data?.status === 'active'
|
||||||
|
|
||||||
const goToDashboard = () => {
|
const goToDashboard = () => {
|
||||||
// Revalidates the cache (onboarding state, session, groups) before redirecting.
|
// Revalidates the cache (onboarding state, session, groups) before redirecting.
|
||||||
@@ -86,6 +89,23 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
|
||||||
|
<MessageCircle className="size-4 shrink-0 text-accent" />
|
||||||
|
<p className="text-xs text-primary">
|
||||||
|
{isWhatsappConnected ? (
|
||||||
|
<>
|
||||||
|
Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la
|
||||||
|
ficha del grupo.
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
Para enviar recordatorios automáticos, vinculá{' '}
|
||||||
|
<span className="font-semibold">WhatsApp</span> desde Ajustes.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Button variant="primary" className="w-full" onClick={goToDashboard}>
|
<Button variant="primary" className="w-full" onClick={goToDashboard}>
|
||||||
Ir a mi Panel
|
Ir a mi Panel
|
||||||
<ArrowRight className="size-4" />
|
<ArrowRight className="size-4" />
|
||||||
|
|||||||
@@ -9,10 +9,13 @@ import { useAuth } from '../../context/AuthProvider'
|
|||||||
import { getOnboardingStatus } from '../../lib/api'
|
import { getOnboardingStatus } from '../../lib/api'
|
||||||
import type { MpCallbackFeedback } from '../mp'
|
import type { MpCallbackFeedback } from '../mp'
|
||||||
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
||||||
|
import type { WhatsappCallbackFeedback } from '../whatsapp'
|
||||||
|
import { readWhatsappCallbackFeedback, whatsappStatusQueryKey } from '../whatsapp'
|
||||||
|
|
||||||
const WELCOME_STEP = 0
|
const WELCOME_STEP = 0
|
||||||
const PAYMENT_STEP = 2
|
const PAYMENT_STEP = 2
|
||||||
const FIRST_GROUP_STEP = 3
|
const WHATSAPP_STEP = 3
|
||||||
|
const FIRST_GROUP_STEP = 4
|
||||||
|
|
||||||
type OnboardingContextValue = {
|
type OnboardingContextValue = {
|
||||||
step: number
|
step: number
|
||||||
@@ -22,6 +25,8 @@ type OnboardingContextValue = {
|
|||||||
setCountry: (country: CountryCode) => void
|
setCountry: (country: CountryCode) => void
|
||||||
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
|
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
|
||||||
mpFeedback: MpCallbackFeedback | null
|
mpFeedback: MpCallbackFeedback | null
|
||||||
|
/** Lo que volvió de una vinculación de WhatsApp por redirect en `?wa=`. */
|
||||||
|
waFeedback: WhatsappCallbackFeedback | null
|
||||||
createdGroup: OnboardingGroupDto | null
|
createdGroup: OnboardingGroupDto | null
|
||||||
setCreatedGroup: (group: OnboardingGroupDto) => void
|
setCreatedGroup: (group: OnboardingGroupDto) => void
|
||||||
statusQuery: UseQueryResult<OnboardingStatusDto>
|
statusQuery: UseQueryResult<OnboardingStatusDto>
|
||||||
@@ -37,6 +42,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
const [step, setStep] = useState(WELCOME_STEP)
|
const [step, setStep] = useState(WELCOME_STEP)
|
||||||
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
|
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
|
||||||
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
|
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
|
||||||
|
const [waFeedback, setWaFeedback] = useState<WhatsappCallbackFeedback | null>(null)
|
||||||
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
|
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
|
||||||
|
|
||||||
const statusQuery = useQuery({
|
const statusQuery = useQuery({
|
||||||
@@ -68,14 +74,33 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
void navigate({ to: '/onboarding', search: {}, replace: true })
|
void navigate({ to: '/onboarding', search: {}, replace: true })
|
||||||
}, [callbackFeedback, navigate, queryClient])
|
}, [callbackFeedback, navigate, queryClient])
|
||||||
|
|
||||||
|
const whatsappCallbackFeedback = useMemo(
|
||||||
|
() => readWhatsappCallbackFeedback(search.wa, search.reason),
|
||||||
|
[search.wa, search.reason],
|
||||||
|
)
|
||||||
|
|
||||||
|
// Igual que `?mp=`: al volver de una vinculación por redirect (Kapso) se
|
||||||
|
// muestra el resultado en el paso de WhatsApp y se limpian los parámetros.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!whatsappCallbackFeedback) return
|
||||||
|
|
||||||
|
setWaFeedback(whatsappCallbackFeedback)
|
||||||
|
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||||
|
setStep(WHATSAPP_STEP)
|
||||||
|
void navigate({ to: '/onboarding', search: {}, replace: true })
|
||||||
|
}, [whatsappCallbackFeedback, navigate, queryClient])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const status = statusQuery.data
|
const status = statusQuery.data
|
||||||
if (!status) return
|
if (!status) return
|
||||||
// Si dejó el onboarding después de vincular los cobros, se retoma en el
|
// Si dejó el onboarding después de vincular los cobros, se retoma en
|
||||||
// grupo. Con la cuenta ya activa el paso 1 ya muestra "Cambiar de cuenta",
|
// WhatsApp (o en el grupo, si también lo vinculó). Con la cuenta ya activa
|
||||||
// así que solo se salta desde la bienvenida.
|
// el paso de Cobros muestra "Cambiar de cuenta", así que solo se salta
|
||||||
|
// desde la bienvenida.
|
||||||
if (status.step === 'PAYMENT_CONNECTED') {
|
if (status.step === 'PAYMENT_CONNECTED') {
|
||||||
setStep((current) => (current === WELCOME_STEP ? FIRST_GROUP_STEP : current))
|
const resumeAt = status.whatsappConnected ? FIRST_GROUP_STEP : WHATSAPP_STEP
|
||||||
|
setStep((current) => (current === WELCOME_STEP ? resumeAt : current))
|
||||||
}
|
}
|
||||||
}, [statusQuery.data])
|
}, [statusQuery.data])
|
||||||
|
|
||||||
@@ -87,6 +112,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
country,
|
country,
|
||||||
setCountry,
|
setCountry,
|
||||||
mpFeedback,
|
mpFeedback,
|
||||||
|
waFeedback,
|
||||||
createdGroup,
|
createdGroup,
|
||||||
setCreatedGroup,
|
setCreatedGroup,
|
||||||
statusQuery,
|
statusQuery,
|
||||||
|
|||||||
@@ -11,11 +11,13 @@ import { useOnboarding } from './OnboardingProvider'
|
|||||||
import { PaymentStep } from './PaymentStep'
|
import { PaymentStep } from './PaymentStep'
|
||||||
import { Stepper } from './Stepper'
|
import { Stepper } from './Stepper'
|
||||||
import { WelcomeStep } from './WelcomeStep'
|
import { WelcomeStep } from './WelcomeStep'
|
||||||
|
import { WhatsappStep } from './WhatsappStep'
|
||||||
|
|
||||||
const STEPS = [
|
const STEPS = [
|
||||||
{ label: 'Bienvenida' },
|
{ label: 'Bienvenida' },
|
||||||
{ label: 'País' },
|
{ label: 'País' },
|
||||||
{ label: 'Cobros' },
|
{ label: 'Cobros' },
|
||||||
|
{ label: 'WhatsApp' },
|
||||||
{ label: 'Tu grupo' },
|
{ label: 'Tu grupo' },
|
||||||
{ label: 'Listo' },
|
{ label: 'Listo' },
|
||||||
]
|
]
|
||||||
@@ -23,7 +25,8 @@ const STEPS = [
|
|||||||
export function OnboardingView() {
|
export function OnboardingView() {
|
||||||
const { user, isPending: authPending } = useAuth()
|
const { user, isPending: authPending } = useAuth()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { step, setStep, mpFeedback, createdGroup, setCreatedGroup, statusQuery } = useOnboarding()
|
const { step, setStep, mpFeedback, waFeedback, createdGroup, setCreatedGroup, statusQuery } =
|
||||||
|
useOnboarding()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (statusQuery.data?.completed) {
|
if (statusQuery.data?.completed) {
|
||||||
@@ -89,15 +92,18 @@ export function OnboardingView() {
|
|||||||
<PaymentStep feedback={mpFeedback} onNext={() => setStep(3)} onBack={() => setStep(1)} />
|
<PaymentStep feedback={mpFeedback} onNext={() => setStep(3)} onBack={() => setStep(1)} />
|
||||||
) : null}
|
) : null}
|
||||||
{step === 3 ? (
|
{step === 3 ? (
|
||||||
|
<WhatsappStep feedback={waFeedback} onNext={() => setStep(4)} onBack={() => setStep(2)} />
|
||||||
|
) : null}
|
||||||
|
{step === 4 ? (
|
||||||
<FirstGroupStep
|
<FirstGroupStep
|
||||||
onBack={() => setStep(2)}
|
onBack={() => setStep(3)}
|
||||||
onCompleted={(group) => {
|
onCompleted={(group) => {
|
||||||
setCreatedGroup(group)
|
setCreatedGroup(group)
|
||||||
setStep(4)
|
setStep(5)
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{step === 4 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
|
{step === 5 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
)
|
)
|
||||||
|
|||||||
123
apps/web/src/features/onboarding/WhatsappStep.tsx
Normal file
123
apps/web/src/features/onboarding/WhatsappStep.tsx
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
import { ArrowLeft, ArrowRight, BadgeCheck, CheckCircle2, Loader2 } from 'lucide-react'
|
||||||
|
import { Badge, Button } from '../../components/ui'
|
||||||
|
import type { WhatsappCallbackFeedback } from '../whatsapp'
|
||||||
|
import {
|
||||||
|
linksWithQr,
|
||||||
|
useStartWhatsappConnection,
|
||||||
|
useWhatsappStatus,
|
||||||
|
WhatsappQrModal,
|
||||||
|
whatsappCallbackErrorMessage,
|
||||||
|
whatsappStatusBadgeVariant,
|
||||||
|
whatsappStatusLabel,
|
||||||
|
} from '../whatsapp'
|
||||||
|
|
||||||
|
type WhatsappStepProps = {
|
||||||
|
/** Resultado de una vinculación por redirect, leído de `?wa=` al volver. */
|
||||||
|
feedback: WhatsappCallbackFeedback | null
|
||||||
|
onNext: () => void
|
||||||
|
onBack: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Paso "WhatsApp" del onboarding: vincular el número desde el que salen los
|
||||||
|
* recordatorios de pago y los mensajes de reenganche.
|
||||||
|
*
|
||||||
|
* Es salteable igual que "Cobros": se puede hacer después desde Ajustes, y los
|
||||||
|
* envíos automáticos se activan grupo por grupo.
|
||||||
|
*/
|
||||||
|
export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
||||||
|
const statusQuery = useWhatsappStatus()
|
||||||
|
const connection = useStartWhatsappConnection()
|
||||||
|
|
||||||
|
const status = statusQuery.data?.status ?? 'none'
|
||||||
|
const isConnected = status === 'active'
|
||||||
|
const usesQr = statusQuery.data ? linksWithQr(statusQuery.data.provider) : true
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="space-y-5">
|
||||||
|
<header className="space-y-1">
|
||||||
|
<h2 className="text-2xl font-bold text-primary">Conectá tu WhatsApp</h2>
|
||||||
|
<p className="text-sm text-foreground/60">
|
||||||
|
Gruperly le recuerda los pagos a tus miembros y escribe a los que dejaron de venir, una
|
||||||
|
vez por semana y desde tu número.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{feedback?.kind === 'success' || (isConnected && !feedback) ? (
|
||||||
|
<p className="flex items-start gap-2 rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
|
||||||
|
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
|
||||||
|
Tu WhatsApp quedó vinculado
|
||||||
|
{statusQuery.data?.displayPhoneNumber ? ` (${statusQuery.data.displayPhoneNumber})` : ''}.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{feedback?.kind === 'error' ? (
|
||||||
|
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
|
{whatsappCallbackErrorMessage(feedback.reason)}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||||
|
<div className="flex items-center justify-between gap-3 px-4 py-3">
|
||||||
|
<p className="text-sm font-medium text-primary">WhatsApp</p>
|
||||||
|
<Badge variant={whatsappStatusBadgeVariant(status)}>{whatsappStatusLabel(status)}</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-4 py-3">
|
||||||
|
{statusQuery.isPending ? (
|
||||||
|
<p className="flex items-center gap-2 text-sm text-foreground/50">
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
Consultando tu WhatsApp…
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-foreground/60">
|
||||||
|
{usesQr
|
||||||
|
? 'Vas a escanear un código QR desde WhatsApp, como cuando usás WhatsApp Web.'
|
||||||
|
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}{' '}
|
||||||
|
Los envíos automáticos los prendés después en cada grupo.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!isConnected ? (
|
||||||
|
<div className="px-4 py-3">
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
className="w-full"
|
||||||
|
disabled={connection.isStarting || statusQuery.isError}
|
||||||
|
onClick={() => void connection.start('onboarding')}
|
||||||
|
>
|
||||||
|
{connection.isStarting ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<BadgeCheck className="size-4" />
|
||||||
|
)}
|
||||||
|
{connection.isStarting ? 'Abriendo…' : 'Vincular WhatsApp'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{connection.error ? (
|
||||||
|
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<WhatsappQrModal
|
||||||
|
isOpen={connection.isQrOpen}
|
||||||
|
onClose={connection.closeQr}
|
||||||
|
initialQrCode={connection.initialQrCode}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Button variant="outline" onClick={onBack} className="hidden lg:inline-flex">
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
Volver
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" className="flex-1 lg:flex-none" onClick={onNext}>
|
||||||
|
{isConnected ? 'Continuar' : 'Lo hago después'}
|
||||||
|
<ArrowRight className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,9 +3,13 @@ import { Fingerprint } from 'lucide-react'
|
|||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { signOut } from '../../lib/auth-client'
|
import { signOut } from '../../lib/auth-client'
|
||||||
import { MpStatusCard } from '../mp'
|
import { MpStatusCard } from '../mp'
|
||||||
|
import { WhatsappStatusCard } from '../whatsapp'
|
||||||
import { AppearanceCard } from './AppearanceCard'
|
import { AppearanceCard } from './AppearanceCard'
|
||||||
|
import { useCallbackFeedbackToast } from './useCallbackFeedbackToast'
|
||||||
|
|
||||||
export function SettingsView() {
|
export function SettingsView() {
|
||||||
|
useCallbackFeedbackToast()
|
||||||
|
|
||||||
const handleSignOut = async () => {
|
const handleSignOut = async () => {
|
||||||
await signOut({
|
await signOut({
|
||||||
fetchOptions: { headers: { 'Cache-Control': 'no-cache' } },
|
fetchOptions: { headers: { 'Cache-Control': 'no-cache' } },
|
||||||
@@ -34,6 +38,8 @@ export function SettingsView() {
|
|||||||
|
|
||||||
<MpStatusCard />
|
<MpStatusCard />
|
||||||
|
|
||||||
|
<WhatsappStatusCard />
|
||||||
|
|
||||||
<AppearanceCard />
|
<AppearanceCard />
|
||||||
|
|
||||||
<Button variant="outline" onClick={handleSignOut}>
|
<Button variant="outline" onClick={handleSignOut}>
|
||||||
|
|||||||
43
apps/web/src/features/settings/useCallbackFeedbackToast.ts
Normal file
43
apps/web/src/features/settings/useCallbackFeedbackToast.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useNavigate, useSearch } from '@tanstack/react-router'
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { useToast } from '../../components/ui'
|
||||||
|
import { mpCallbackErrorMessage, mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
||||||
|
import {
|
||||||
|
readWhatsappCallbackFeedback,
|
||||||
|
whatsappCallbackErrorMessage,
|
||||||
|
whatsappStatusQueryKey,
|
||||||
|
} from '../whatsapp'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Al volver a Ajustes desde Mercado Pago (`?mp=`) o desde una vinculación de
|
||||||
|
* WhatsApp por redirect (`?wa=`) se avisa el resultado con un toast y se limpian
|
||||||
|
* los parámetros: si no, recargar la página repetiría el aviso.
|
||||||
|
*/
|
||||||
|
export function useCallbackFeedbackToast() {
|
||||||
|
const search = useSearch({ from: '/_authenticated/settings' })
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const toast = useToast()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const mp = readMpCallbackFeedback(search.mp, search.reason)
|
||||||
|
const wa = readWhatsappCallbackFeedback(search.wa, search.reason)
|
||||||
|
if (!mp && !wa) return
|
||||||
|
|
||||||
|
if (mp) {
|
||||||
|
if (mp.kind === 'success') toast.success('Tu cuenta de Mercado Pago quedó vinculada.')
|
||||||
|
else toast.error(mpCallbackErrorMessage(mp.reason))
|
||||||
|
void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey })
|
||||||
|
}
|
||||||
|
if (wa) {
|
||||||
|
if (wa.kind === 'success') toast.success('Tu WhatsApp quedó vinculado.')
|
||||||
|
else toast.error(whatsappCallbackErrorMessage(wa.reason))
|
||||||
|
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||||
|
}
|
||||||
|
|
||||||
|
void navigate({ to: '/settings', search: {}, replace: true })
|
||||||
|
// `toast` cambia en cada aviso: el efecto depende solo de la URL, si no se
|
||||||
|
// dispararía otra vez con cada toast.
|
||||||
|
}, [search.mp, search.wa, search.reason, navigate, queryClient])
|
||||||
|
}
|
||||||
67
apps/web/src/features/whatsapp/WhatsappQrModal.tsx
Normal file
67
apps/web/src/features/whatsapp/WhatsappQrModal.tsx
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { Loader2, Smartphone } from 'lucide-react'
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { Modal, useToast } from '../../components/ui'
|
||||||
|
import { useWhatsappStatus } from './useWhatsappStatus'
|
||||||
|
|
||||||
|
type WhatsappQrModalProps = {
|
||||||
|
isOpen: boolean
|
||||||
|
onClose: () => void
|
||||||
|
/** QR de la respuesta de `connect`; se reemplaza por el del estado apenas llega. */
|
||||||
|
initialQrCode: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vinculación por QR: el profesor lo escanea desde su teléfono como un
|
||||||
|
* "dispositivo vinculado". El estado se consulta cada 2 s mientras está
|
||||||
|
* pendiente, así que el QR se renueva y el modal se cierra solo al vincularse.
|
||||||
|
*/
|
||||||
|
export function WhatsappQrModal({ isOpen, onClose, initialQrCode }: WhatsappQrModalProps) {
|
||||||
|
const toast = useToast()
|
||||||
|
const statusQuery = useWhatsappStatus({ enabled: isOpen })
|
||||||
|
const status = statusQuery.data?.status
|
||||||
|
const qrCode = statusQuery.data?.qrCode ?? initialQrCode
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isOpen) return
|
||||||
|
if (status === 'active') {
|
||||||
|
toast.success('¡Listo! Tu WhatsApp quedó vinculado.')
|
||||||
|
onClose()
|
||||||
|
} else if (status === 'disconnected') {
|
||||||
|
toast.error('La vinculación no se completó. Volvé a intentarlo.')
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
}, [isOpen, status, onClose, toast])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
isOpen={isOpen}
|
||||||
|
onClose={onClose}
|
||||||
|
title="Vinculá tu WhatsApp"
|
||||||
|
description="Escaneá el código con el teléfono donde usás WhatsApp."
|
||||||
|
maxWidth="sm"
|
||||||
|
>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="mx-auto flex size-64 items-center justify-center rounded-xl border border-border bg-white p-2">
|
||||||
|
{qrCode ? (
|
||||||
|
<img src={qrCode} alt="Código QR para vincular WhatsApp" className="size-full" />
|
||||||
|
) : (
|
||||||
|
<Loader2 className="size-8 animate-spin text-foreground/40" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ol className="space-y-1.5 text-sm text-foreground/70">
|
||||||
|
<li>1. Abrí WhatsApp en tu teléfono.</li>
|
||||||
|
<li>
|
||||||
|
2. Tocá <span className="font-medium text-primary">Dispositivos vinculados</span> y
|
||||||
|
después <span className="font-medium text-primary">Vincular un dispositivo</span>.
|
||||||
|
</li>
|
||||||
|
<li>3. Apuntá la cámara a este código.</li>
|
||||||
|
</ol>
|
||||||
|
<p className="flex items-start gap-2 rounded-xl bg-primary-soft px-3 py-2 text-xs text-foreground/70">
|
||||||
|
<Smartphone className="mt-0.5 size-4 shrink-0 text-accent" />
|
||||||
|
Los mensajes van a salir desde tu número. Podés desvincularlo cuando quieras desde
|
||||||
|
Ajustes o desde tu teléfono.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
)
|
||||||
|
}
|
||||||
175
apps/web/src/features/whatsapp/WhatsappStatusCard.tsx
Normal file
175
apps/web/src/features/whatsapp/WhatsappStatusCard.tsx
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
import { BadgeCheck, Loader2, MessageCircle, Unlink } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { Badge, Button, Modal } from '../../components/ui'
|
||||||
|
import { formatMpConnectionDate } from '../mp'
|
||||||
|
import {
|
||||||
|
linksWithQr,
|
||||||
|
readinessLabel,
|
||||||
|
WEEKLY_SEND_LABEL,
|
||||||
|
WHATSAPP_UNAVAILABLE_MESSAGE,
|
||||||
|
whatsappStatusBadgeVariant,
|
||||||
|
whatsappStatusLabel,
|
||||||
|
} from './copy'
|
||||||
|
import { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||||
|
import { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||||
|
import { useWhatsappStatus } from './useWhatsappStatus'
|
||||||
|
import { WhatsappQrModal } from './WhatsappQrModal'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WhatsApp en Ajustes: vincular el número desde el que salen los recordatorios
|
||||||
|
* de pago y los mensajes de reenganche, ver si cada mensaje ya se puede enviar
|
||||||
|
* y desvincularlo. El mismo control vive en el paso del onboarding.
|
||||||
|
*/
|
||||||
|
export function WhatsappStatusCard() {
|
||||||
|
const statusQuery = useWhatsappStatus()
|
||||||
|
const connection = useStartWhatsappConnection()
|
||||||
|
const { disconnectWhatsapp: disconnect, isDisconnecting } = useDisconnectWhatsapp()
|
||||||
|
const [isConfirmingDisconnect, setIsConfirmingDisconnect] = useState(false)
|
||||||
|
|
||||||
|
if (statusQuery.isPending) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
|
||||||
|
<Loader2 className="size-4 animate-spin text-foreground/40" />
|
||||||
|
<p className="text-sm text-foreground/50">Consultando tu WhatsApp…</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (statusQuery.isError || !statusQuery.data) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-border bg-surface px-4 py-3">
|
||||||
|
<p className="text-sm font-medium text-primary">WhatsApp</p>
|
||||||
|
<p className="mt-0.5 text-xs text-foreground/50">{WHATSAPP_UNAVAILABLE_MESSAGE}</p>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = statusQuery.data
|
||||||
|
const status = data.status
|
||||||
|
const connectedAt = formatMpConnectionDate(data.connectedAt)
|
||||||
|
const isActive = status === 'active'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||||
|
<div className="px-4 py-3">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<p className="text-sm font-medium text-primary">WhatsApp</p>
|
||||||
|
<Badge variant={whatsappStatusBadgeVariant(status)}>{whatsappStatusLabel(status)}</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
|
Tu número para los recordatorios de pago y los mensajes de reenganche automáticos.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isActive ? (
|
||||||
|
<>
|
||||||
|
<div className="flex items-center gap-3 px-4 py-3">
|
||||||
|
<span className="rounded-lg bg-success-soft p-2">
|
||||||
|
<MessageCircle className="size-4 text-success" />
|
||||||
|
</span>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm text-primary">
|
||||||
|
{data.displayPhoneNumber ?? 'Número vinculado'}
|
||||||
|
</p>
|
||||||
|
{connectedAt ? (
|
||||||
|
<p className="text-xs text-foreground/50">Vinculado el {connectedAt}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setIsConfirmingDisconnect(true)}
|
||||||
|
disabled={isDisconnecting}
|
||||||
|
>
|
||||||
|
{isDisconnecting ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Unlink className="size-4" />
|
||||||
|
)}
|
||||||
|
Desvincular
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<dl className="space-y-1.5 px-4 py-3 text-sm">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<dt className="text-foreground/60">Recordatorio de pago</dt>
|
||||||
|
<dd className="text-primary">{readinessLabel(data.readiness.PAYMENT_REMINDER)}</dd>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<dt className="text-foreground/60">Mensaje de reenganche</dt>
|
||||||
|
<dd className="text-primary">{readinessLabel(data.readiness.REENGAGEMENT)}</dd>
|
||||||
|
</div>
|
||||||
|
<p className="pt-1 text-xs text-foreground/50">
|
||||||
|
Los activás en cada grupo. {WEEKLY_SEND_LABEL}
|
||||||
|
</p>
|
||||||
|
</dl>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-start gap-3 px-4 py-3">
|
||||||
|
<span className="rounded-lg bg-primary-soft p-2">
|
||||||
|
<MessageCircle className="size-4 text-foreground/70" />
|
||||||
|
</span>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-sm text-primary">
|
||||||
|
{status === 'requires_reconnect' ? 'Volvé a vincular tu número' : 'Vinculá tu número'}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-foreground/50">
|
||||||
|
{linksWithQr(data.provider)
|
||||||
|
? 'Escaneás un código QR desde WhatsApp, como en WhatsApp Web.'
|
||||||
|
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
size="sm"
|
||||||
|
disabled={connection.isStarting}
|
||||||
|
onClick={() => void connection.start('settings')}
|
||||||
|
>
|
||||||
|
{connection.isStarting ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<BadgeCheck className="size-4" />
|
||||||
|
)}
|
||||||
|
{connection.isStarting ? 'Abriendo…' : 'Vincular'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{connection.error ? (
|
||||||
|
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<WhatsappQrModal
|
||||||
|
isOpen={connection.isQrOpen}
|
||||||
|
onClose={connection.closeQr}
|
||||||
|
initialQrCode={connection.initialQrCode}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
isOpen={isConfirmingDisconnect}
|
||||||
|
onClose={() => setIsConfirmingDisconnect(false)}
|
||||||
|
title="Desvincular WhatsApp"
|
||||||
|
description="Los recordatorios y los mensajes de reenganche automáticos dejan de enviarse hasta que lo vuelvas a vincular."
|
||||||
|
maxWidth="sm"
|
||||||
|
>
|
||||||
|
<div className="flex justify-end gap-3">
|
||||||
|
<Button variant="outline" onClick={() => setIsConfirmingDisconnect(false)}>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
disabled={isDisconnecting}
|
||||||
|
onClick={() => {
|
||||||
|
setIsConfirmingDisconnect(false)
|
||||||
|
disconnect()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isDisconnecting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||||
|
Desvincular
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
126
apps/web/src/features/whatsapp/copy.ts
Normal file
126
apps/web/src/features/whatsapp/copy.ts
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
import type {
|
||||||
|
WhatsappAccountStatus,
|
||||||
|
WhatsappCallbackReason,
|
||||||
|
WhatsappProvider,
|
||||||
|
WhatsappReadiness,
|
||||||
|
WhatsappStatusDto,
|
||||||
|
} from '@gruperly/shared'
|
||||||
|
|
||||||
|
/* Copy de WhatsApp en un solo lugar: el paso del onboarding, la tarjeta de
|
||||||
|
Ajustes y las automatizaciones del grupo dicen exactamente lo mismo. Las
|
||||||
|
funciones son puras para cubrirlas con tests sin renderizar nada. */
|
||||||
|
|
||||||
|
export const WHATSAPP_CONNECT_ERROR_MESSAGE =
|
||||||
|
'No pudimos empezar la vinculación. Revisá tu conexión e intentá de nuevo.'
|
||||||
|
|
||||||
|
export const WHATSAPP_UNAVAILABLE_MESSAGE =
|
||||||
|
'La vinculación con WhatsApp no está disponible en este momento.'
|
||||||
|
|
||||||
|
/** Día y hora en que salen los mensajes automáticos (lo fija el job del backend). */
|
||||||
|
export const WEEKLY_SEND_LABEL = 'Se envían los lunes a las 10:00 (hora de Argentina).'
|
||||||
|
|
||||||
|
/** El resultado de una vinculación por redirect (Kapso), tal como vuelve en `?wa=`. */
|
||||||
|
export type WhatsappCallbackFeedback =
|
||||||
|
| { kind: 'success' }
|
||||||
|
| { kind: 'error'; reason: WhatsappCallbackReason }
|
||||||
|
|
||||||
|
const KNOWN_REASONS: readonly WhatsappCallbackReason[] = [
|
||||||
|
'invalid_setup',
|
||||||
|
'setup_failed',
|
||||||
|
'provider_error',
|
||||||
|
'number_in_use',
|
||||||
|
]
|
||||||
|
|
||||||
|
/** Traduce `?wa=` de la URL a la retroalimentación que se muestra en pantalla. */
|
||||||
|
export function readWhatsappCallbackFeedback(
|
||||||
|
wa: string | undefined,
|
||||||
|
reason: string | undefined,
|
||||||
|
): WhatsappCallbackFeedback | null {
|
||||||
|
if (wa === 'success') return { kind: 'success' }
|
||||||
|
if (wa !== 'error') return null
|
||||||
|
return {
|
||||||
|
kind: 'error',
|
||||||
|
reason: KNOWN_REASONS.includes(reason as WhatsappCallbackReason)
|
||||||
|
? (reason as WhatsappCallbackReason)
|
||||||
|
: 'provider_error',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const REASON_MESSAGES: Record<WhatsappCallbackReason, string> = {
|
||||||
|
invalid_setup: 'La vinculación venció o ya se había usado. Volvé a intentarlo.',
|
||||||
|
setup_failed: 'No se pudo terminar la vinculación en Meta. Volvé a intentarlo.',
|
||||||
|
provider_error: 'WhatsApp no pudo completar la vinculación.',
|
||||||
|
number_in_use: 'Ese número de WhatsApp ya está vinculado a otro profesor.',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function whatsappCallbackErrorMessage(reason: WhatsappCallbackReason): string {
|
||||||
|
return REASON_MESSAGES[reason]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function whatsappStatusLabel(status: WhatsappAccountStatus): string {
|
||||||
|
switch (status) {
|
||||||
|
case 'active':
|
||||||
|
return 'Vinculado'
|
||||||
|
case 'pending':
|
||||||
|
return 'Vinculando…'
|
||||||
|
case 'requires_reconnect':
|
||||||
|
return 'Necesita vincularse de nuevo'
|
||||||
|
case 'disconnected':
|
||||||
|
case 'none':
|
||||||
|
return 'Sin vincular'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function whatsappStatusBadgeVariant(
|
||||||
|
status: WhatsappAccountStatus,
|
||||||
|
): 'success' | 'warning' | 'neutral' | 'info' {
|
||||||
|
switch (status) {
|
||||||
|
case 'active':
|
||||||
|
return 'success'
|
||||||
|
case 'pending':
|
||||||
|
return 'info'
|
||||||
|
case 'requires_reconnect':
|
||||||
|
return 'warning'
|
||||||
|
case 'disconnected':
|
||||||
|
case 'none':
|
||||||
|
return 'neutral'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Qué se le explica al profesor según el estado de un tipo de mensaje. */
|
||||||
|
export function readinessLabel(readiness: WhatsappReadiness): string {
|
||||||
|
switch (readiness) {
|
||||||
|
case 'ready':
|
||||||
|
return 'Listo para enviar'
|
||||||
|
case 'pending':
|
||||||
|
return 'En revisión por Meta'
|
||||||
|
case 'blocked':
|
||||||
|
return 'No disponible'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Si la vinculación se hace escaneando un QR dentro de Gruperly. */
|
||||||
|
export function linksWithQr(provider: WhatsappProvider): boolean {
|
||||||
|
return provider === 'OPENWA'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Por qué un switch de automatización está deshabilitado, o null si se puede
|
||||||
|
* usar. Se puede apagar siempre: lo que se bloquea es prenderla sin WhatsApp.
|
||||||
|
*/
|
||||||
|
export function automationBlockedReason(
|
||||||
|
status: WhatsappStatusDto | undefined,
|
||||||
|
kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT',
|
||||||
|
): string | null {
|
||||||
|
if (!status || status.status !== 'active') {
|
||||||
|
return 'Vinculá tu WhatsApp en Ajustes para activar los envíos automáticos.'
|
||||||
|
}
|
||||||
|
switch (status.readiness[kind]) {
|
||||||
|
case 'ready':
|
||||||
|
return null
|
||||||
|
case 'pending':
|
||||||
|
return 'Meta todavía está revisando el mensaje. Suele tardar hasta 24 horas.'
|
||||||
|
case 'blocked':
|
||||||
|
return 'Meta rechazó este mensaje. Escribinos para revisarlo.'
|
||||||
|
}
|
||||||
|
}
|
||||||
16
apps/web/src/features/whatsapp/index.ts
Normal file
16
apps/web/src/features/whatsapp/index.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export {
|
||||||
|
automationBlockedReason,
|
||||||
|
linksWithQr,
|
||||||
|
readinessLabel,
|
||||||
|
readWhatsappCallbackFeedback,
|
||||||
|
WEEKLY_SEND_LABEL,
|
||||||
|
type WhatsappCallbackFeedback,
|
||||||
|
whatsappCallbackErrorMessage,
|
||||||
|
whatsappStatusBadgeVariant,
|
||||||
|
whatsappStatusLabel,
|
||||||
|
} from './copy'
|
||||||
|
export { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||||
|
export { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||||
|
export { useWhatsappStatus, whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||||
|
export { WhatsappQrModal } from './WhatsappQrModal'
|
||||||
|
export { WhatsappStatusCard } from './WhatsappStatusCard'
|
||||||
28
apps/web/src/features/whatsapp/useDisconnectWhatsapp.ts
Normal file
28
apps/web/src/features/whatsapp/useDisconnectWhatsapp.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useToast } from '../../components/ui'
|
||||||
|
import { disconnectWhatsapp } from '../../lib/api'
|
||||||
|
import { whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||||
|
|
||||||
|
export function useDisconnectWhatsapp() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const toast = useToast()
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: disconnectWhatsapp,
|
||||||
|
onSuccess: (result) => {
|
||||||
|
if (result.disconnected) {
|
||||||
|
toast.success('Desvinculamos tu WhatsApp. Los envíos automáticos quedan en pausa.')
|
||||||
|
}
|
||||||
|
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||||
|
},
|
||||||
|
onError: (error: Error) => {
|
||||||
|
toast.error(error.message || 'No pudimos desvincular tu WhatsApp.')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
disconnectWhatsapp: () => mutation.mutate(),
|
||||||
|
isDisconnecting: mutation.isPending,
|
||||||
|
}
|
||||||
|
}
|
||||||
55
apps/web/src/features/whatsapp/useStartWhatsappConnection.ts
Normal file
55
apps/web/src/features/whatsapp/useStartWhatsappConnection.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import type { WhatsappReturnTo } from '@gruperly/shared'
|
||||||
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { ApiError, startWhatsappConnection } from '../../lib/api'
|
||||||
|
import { WHATSAPP_CONNECT_ERROR_MESSAGE, WHATSAPP_UNAVAILABLE_MESSAGE } from './copy'
|
||||||
|
import { whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Empieza la vinculación de WhatsApp sin saber qué proveedor hay detrás:
|
||||||
|
* - `redirect` (Kapso): el navegador navega al flujo de Meta y vuelve con `?wa=`.
|
||||||
|
* - `qr` (OpenWA): se abre el modal con el QR; el estado se consulta solo hasta
|
||||||
|
* que el teléfono lo escanea.
|
||||||
|
*/
|
||||||
|
export function useStartWhatsappConnection() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [isStarting, setIsStarting] = useState(false)
|
||||||
|
const [qrCode, setQrCode] = useState<string | null>(null)
|
||||||
|
const [isQrOpen, setIsQrOpen] = useState(false)
|
||||||
|
|
||||||
|
const start = async (returnTo: WhatsappReturnTo) => {
|
||||||
|
setError(null)
|
||||||
|
setIsStarting(true)
|
||||||
|
try {
|
||||||
|
const { start: next } = await startWhatsappConnection(returnTo)
|
||||||
|
if (next.type === 'redirect') {
|
||||||
|
window.location.assign(next.url)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setQrCode(next.qrCode)
|
||||||
|
// El estado pasa a `pending` y empieza el sondeo que trae el QR nuevo. Se
|
||||||
|
// espera el refetch antes de abrir el modal: con el estado viejo en caché
|
||||||
|
// (`disconnected`) el modal se cerraría apenas abre.
|
||||||
|
await queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||||
|
setIsQrOpen(true)
|
||||||
|
} catch (caught) {
|
||||||
|
setError(
|
||||||
|
caught instanceof ApiError && caught.status === 503
|
||||||
|
? WHATSAPP_UNAVAILABLE_MESSAGE
|
||||||
|
: WHATSAPP_CONNECT_ERROR_MESSAGE,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
setIsStarting(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
start,
|
||||||
|
isStarting,
|
||||||
|
error,
|
||||||
|
/** QR de la respuesta inicial; el modal prefiere el del estado, que se renueva. */
|
||||||
|
initialQrCode: qrCode,
|
||||||
|
isQrOpen,
|
||||||
|
closeQr: () => setIsQrOpen(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
28
apps/web/src/features/whatsapp/useWhatsappStatus.ts
Normal file
28
apps/web/src/features/whatsapp/useWhatsappStatus.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { getWhatsappStatus } from '../../lib/api'
|
||||||
|
|
||||||
|
/** La misma clave en toda la app: el onboarding, Ajustes y la ficha del grupo. */
|
||||||
|
export const whatsappStatusQueryKey = ['whatsapp', 'status'] as const
|
||||||
|
|
||||||
|
/** Cada cuánto se consulta mientras la vinculación está en curso (QR en pantalla). */
|
||||||
|
const PENDING_POLL_MS = 2000
|
||||||
|
|
||||||
|
type UseWhatsappStatusOptions = {
|
||||||
|
enabled?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Estado del WhatsApp del profesor. Mientras está `pending` se consulta cada 2 s:
|
||||||
|
* así el QR se renueva y la vinculación se completa sola, aunque el webhook del
|
||||||
|
* proveedor no llegue (desarrollo local).
|
||||||
|
*/
|
||||||
|
export function useWhatsappStatus({ enabled = true }: UseWhatsappStatusOptions = {}) {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: whatsappStatusQueryKey,
|
||||||
|
queryFn: getWhatsappStatus,
|
||||||
|
enabled,
|
||||||
|
retry: false,
|
||||||
|
refetchInterval: (query) =>
|
||||||
|
query.state.data?.status === 'pending' ? PENDING_POLL_MS : false,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -53,6 +53,12 @@ import type {
|
|||||||
StudentsAtRisk,
|
StudentsAtRisk,
|
||||||
UpdateAttendee,
|
UpdateAttendee,
|
||||||
UpdateStudentStatusResult,
|
UpdateStudentStatusResult,
|
||||||
|
GroupAutomationsDto,
|
||||||
|
UpdateGroupAutomations,
|
||||||
|
WhatsappConnectResultDto,
|
||||||
|
WhatsappDisconnectResultDto,
|
||||||
|
WhatsappReturnTo,
|
||||||
|
WhatsappStatusDto,
|
||||||
} from '@gruperly/shared'
|
} from '@gruperly/shared'
|
||||||
|
|
||||||
import { browserTimezone } from './region'
|
import { browserTimezone } from './region'
|
||||||
@@ -124,6 +130,25 @@ export const getMpStatus = () => apiFetch<MpStatusDto>('/api/v1/mp/status')
|
|||||||
export const disconnectMp = () =>
|
export const disconnectMp = () =>
|
||||||
apiFetch<MpDisconnectResultDto>('/api/v1/mp/connect', { method: 'DELETE' })
|
apiFetch<MpDisconnectResultDto>('/api/v1/mp/connect', { method: 'DELETE' })
|
||||||
|
|
||||||
|
// --- WhatsApp (recordatorios y reenganche automáticos) ---
|
||||||
|
|
||||||
|
export const startWhatsappConnection = (returnTo: WhatsappReturnTo) =>
|
||||||
|
apiFetch<WhatsappConnectResultDto>('/api/v1/whatsapp/connect', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ returnTo }),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const getWhatsappStatus = () => apiFetch<WhatsappStatusDto>('/api/v1/whatsapp/status')
|
||||||
|
|
||||||
|
export const disconnectWhatsapp = () =>
|
||||||
|
apiFetch<WhatsappDisconnectResultDto>('/api/v1/whatsapp/connect', { method: 'DELETE' })
|
||||||
|
|
||||||
|
export const updateGroupAutomations = (groupId: string, payload: UpdateGroupAutomations) =>
|
||||||
|
apiFetch<GroupAutomationsDto>(`/api/v1/groups/${groupId}/automations`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
})
|
||||||
|
|
||||||
// — Cobros —
|
// — Cobros —
|
||||||
|
|
||||||
export const getPayments = (params: PaymentQuery) => {
|
export const getPayments = (params: PaymentQuery) => {
|
||||||
|
|||||||
@@ -2,5 +2,14 @@ import { createFileRoute } from '@tanstack/react-router'
|
|||||||
import { SettingsView } from '../../features/settings/SettingsView'
|
import { SettingsView } from '../../features/settings/SettingsView'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/settings')({
|
export const Route = createFileRoute('/_authenticated/settings')({
|
||||||
|
/* Los callbacks de Mercado Pago (`?mp=`) y de WhatsApp por redirect (`?wa=`)
|
||||||
|
vuelven acá cuando el flujo empezó en Ajustes. */
|
||||||
|
validateSearch: (
|
||||||
|
search: Record<string, unknown>,
|
||||||
|
): { mp?: string; wa?: string; reason?: string } => ({
|
||||||
|
mp: typeof search.mp === 'string' ? search.mp : undefined,
|
||||||
|
wa: typeof search.wa === 'string' ? search.wa : undefined,
|
||||||
|
reason: typeof search.reason === 'string' ? search.reason : undefined,
|
||||||
|
}),
|
||||||
component: SettingsView,
|
component: SettingsView,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -3,11 +3,15 @@ import { OnboardingProvider } from '../features/onboarding/OnboardingProvider'
|
|||||||
import { OnboardingView } from '../features/onboarding/OnboardingView'
|
import { OnboardingView } from '../features/onboarding/OnboardingView'
|
||||||
|
|
||||||
export const Route = createFileRoute('/onboarding')({
|
export const Route = createFileRoute('/onboarding')({
|
||||||
/* El callback de Mercado Pago devuelve el control acá con `?mp=success` o
|
/* Los callbacks de Mercado Pago (`?mp=`) y de WhatsApp por redirect (`?wa=`)
|
||||||
`?mp=error&reason=…`. Se valida como search param para que el provider tenga
|
devuelven el control acá con `success` o `error&reason=…`. Se validan como
|
||||||
los dos valores ya tipados y no tenga que leer el `location` crudo. */
|
search params para que el provider tenga los valores ya tipados y no tenga
|
||||||
validateSearch: (search: Record<string, unknown>): { mp?: string; reason?: string } => ({
|
que leer el `location` crudo. */
|
||||||
|
validateSearch: (
|
||||||
|
search: Record<string, unknown>,
|
||||||
|
): { mp?: string; wa?: string; reason?: string } => ({
|
||||||
mp: typeof search.mp === 'string' ? search.mp : undefined,
|
mp: typeof search.mp === 'string' ? search.mp : undefined,
|
||||||
|
wa: typeof search.wa === 'string' ? search.wa : undefined,
|
||||||
reason: typeof search.reason === 'string' ? search.reason : undefined,
|
reason: typeof search.reason === 'string' ? search.reason : undefined,
|
||||||
}),
|
}),
|
||||||
component: () => (
|
component: () => (
|
||||||
|
|||||||
79
apps/web/test/whatsapp-copy.test.ts
Normal file
79
apps/web/test/whatsapp-copy.test.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import type { WhatsappStatusDto } from '@gruperly/shared'
|
||||||
|
import { describe, expect, test } from 'bun:test'
|
||||||
|
import {
|
||||||
|
automationBlockedReason,
|
||||||
|
linksWithQr,
|
||||||
|
readinessLabel,
|
||||||
|
readWhatsappCallbackFeedback,
|
||||||
|
whatsappCallbackErrorMessage,
|
||||||
|
whatsappStatusBadgeVariant,
|
||||||
|
whatsappStatusLabel,
|
||||||
|
} from '../src/features/whatsapp/copy'
|
||||||
|
|
||||||
|
/* El copy de WhatsApp lo comparten el onboarding, Ajustes y la ficha del grupo. */
|
||||||
|
|
||||||
|
function status(overrides: Partial<WhatsappStatusDto> = {}): WhatsappStatusDto {
|
||||||
|
return {
|
||||||
|
status: 'active',
|
||||||
|
provider: 'OPENWA',
|
||||||
|
displayPhoneNumber: '+5491123456789',
|
||||||
|
connectedAt: '2026-10-19T13:00:00.000Z',
|
||||||
|
qrCode: null,
|
||||||
|
readiness: { PAYMENT_REMINDER: 'ready', REENGAGEMENT: 'ready' },
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('readWhatsappCallbackFeedback', () => {
|
||||||
|
test('lee el resultado de la vinculación desde la URL', () => {
|
||||||
|
expect(readWhatsappCallbackFeedback('success', undefined)).toEqual({ kind: 'success' })
|
||||||
|
expect(readWhatsappCallbackFeedback('error', 'number_in_use')).toEqual({
|
||||||
|
kind: 'error',
|
||||||
|
reason: 'number_in_use',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('un motivo desconocido es un error genérico y sin `wa` no hay nada', () => {
|
||||||
|
expect(readWhatsappCallbackFeedback('error', 'otra-cosa')).toEqual({
|
||||||
|
kind: 'error',
|
||||||
|
reason: 'provider_error',
|
||||||
|
})
|
||||||
|
expect(readWhatsappCallbackFeedback(undefined, 'number_in_use')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('cada motivo tiene su mensaje', () => {
|
||||||
|
expect(whatsappCallbackErrorMessage('number_in_use')).toContain('otro profesor')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('estado', () => {
|
||||||
|
test('etiquetas y variantes', () => {
|
||||||
|
expect(whatsappStatusLabel('active')).toBe('Vinculado')
|
||||||
|
expect(whatsappStatusLabel('disconnected')).toBe('Sin vincular')
|
||||||
|
expect(whatsappStatusBadgeVariant('pending')).toBe('info')
|
||||||
|
expect(whatsappStatusBadgeVariant('requires_reconnect')).toBe('warning')
|
||||||
|
expect(readinessLabel('pending')).toBe('En revisión por Meta')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('solo OpenWA se vincula con QR', () => {
|
||||||
|
expect(linksWithQr('OPENWA')).toBe(true)
|
||||||
|
expect(linksWithQr('KAPSO')).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('automationBlockedReason', () => {
|
||||||
|
test('sin WhatsApp activo pide vincularlo', () => {
|
||||||
|
expect(automationBlockedReason(undefined, 'PAYMENT_REMINDER')).toContain('Vinculá')
|
||||||
|
expect(automationBlockedReason(status({ status: 'pending' }), 'REENGAGEMENT')).toContain('Vinculá')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('con el mensaje en revisión o rechazado explica por qué', () => {
|
||||||
|
const reviewing = status({ readiness: { PAYMENT_REMINDER: 'pending', REENGAGEMENT: 'blocked' } })
|
||||||
|
expect(automationBlockedReason(reviewing, 'PAYMENT_REMINDER')).toContain('revisando')
|
||||||
|
expect(automationBlockedReason(reviewing, 'REENGAGEMENT')).toContain('rechazó')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('listo para enviar no bloquea', () => {
|
||||||
|
expect(automationBlockedReason(status(), 'PAYMENT_REMINDER')).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -32,6 +32,26 @@ x-backend-env: &backend-env
|
|||||||
# Clave de 32 bytes en base64 (openssl rand -base64 32) para cifrar los tokens
|
# Clave de 32 bytes en base64 (openssl rand -base64 32) para cifrar los tokens
|
||||||
# en reposo. Sin ella, mp/callback falla al guardar la cuenta.
|
# en reposo. Sin ella, mp/callback falla al guardar la cuenta.
|
||||||
TOKEN_ENCRYPTION_KEY: ${TOKEN_ENCRYPTION_KEY:-}
|
TOKEN_ENCRYPTION_KEY: ${TOKEN_ENCRYPTION_KEY:-}
|
||||||
|
# WhatsApp (recordatorios de pago y reenganche semanales). Ver docs/whatsapp.md.
|
||||||
|
# `openwa` (MVP, servicio de abajo) o `kapso` (API oficial de Meta). Sin las
|
||||||
|
# variables del proveedor elegido, /whatsapp/* responde 503 y el paso del
|
||||||
|
# onboarding es salteable.
|
||||||
|
WHATSAPP_PROVIDER: ${WHATSAPP_PROVIDER:-openwa}
|
||||||
|
# Pausa entre dos envios del mismo profesor (ms). No bajar de ~4000 con OpenWA.
|
||||||
|
WHATSAPP_SEND_INTERVAL_MS: ${WHATSAPP_SEND_INTERVAL_MS:-5000}
|
||||||
|
OPENWA_API_URL: ${OPENWA_API_URL:-http://openwa:2785/api}
|
||||||
|
# Key OPERATOR sin `allowedSessions` (crea sesiones). Se crea con la key ADMIN
|
||||||
|
# que OpenWA escribe en /app/data/.api-key la primera vez que arranca.
|
||||||
|
OPENWA_API_KEY: ${OPENWA_API_KEY:-}
|
||||||
|
# Opcional: sin webhook la vinculacion funciona igual (polling), pero no se
|
||||||
|
# registran las confirmaciones de entrega/lectura. Por la red interna:
|
||||||
|
# http://api:4000/api/v1/whatsapp/webhooks/openwa (requiere el secreto).
|
||||||
|
OPENWA_WEBHOOK_URL: ${OPENWA_WEBHOOK_URL:-}
|
||||||
|
OPENWA_WEBHOOK_SECRET: ${OPENWA_WEBHOOK_SECRET:-}
|
||||||
|
KAPSO_API_KEY: ${KAPSO_API_KEY:-}
|
||||||
|
KAPSO_CALLBACK_URL: ${KAPSO_CALLBACK_URL:-}
|
||||||
|
KAPSO_WEBHOOK_URL: ${KAPSO_WEBHOOK_URL:-}
|
||||||
|
KAPSO_WEBHOOK_SECRET: ${KAPSO_WEBHOOK_SECRET:-}
|
||||||
|
|
||||||
services:
|
services:
|
||||||
api:
|
api:
|
||||||
@@ -47,6 +67,36 @@ services:
|
|||||||
- default
|
- default
|
||||||
- dokploy-network
|
- dokploy-network
|
||||||
|
|
||||||
|
# Gateway de WhatsApp para el MVP (rmyndharis/OpenWA, MIT). Solo en la red
|
||||||
|
# interna: la API le habla por http://openwa:2785 y el puerto no se publica.
|
||||||
|
# Imagen pineada: el proyecto todavia no llego a 1.0 y rompe compatibilidad.
|
||||||
|
# Con WHATSAPP_PROVIDER=kapso este servicio no se usa (se puede quitar).
|
||||||
|
openwa:
|
||||||
|
image: ghcr.io/rmyndharis/openwa:${OPENWA_IMAGE_TAG:-0.25.0}
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
NODE_ENV: production
|
||||||
|
# Baileys habla el protocolo por WebSocket: sin Chromium por sesion.
|
||||||
|
ENGINE_TYPE: baileys
|
||||||
|
# Sesiones (credenciales de WhatsApp de cada profesor) y la key inicial.
|
||||||
|
DATABASE_TYPE: sqlite
|
||||||
|
SESSION_DATA_PATH: /app/data/sessions
|
||||||
|
# Reconecta al reiniciar las sesiones que estaban vinculadas.
|
||||||
|
AUTO_START_SESSIONS: "true"
|
||||||
|
# Anti-ban: tope diario que crece con la antiguedad del numero y tope de
|
||||||
|
# conversaciones nuevas. Ver docs/whatsapp.md antes de tocarlo.
|
||||||
|
SEND_PACING_ENABLED: "true"
|
||||||
|
SIMULATE_TYPING: "true"
|
||||||
|
# El webhook apunta a la API por la red interna; el guard SSRF lo rechaza
|
||||||
|
# si el host no esta permitido.
|
||||||
|
SSRF_ALLOWED_HOSTS: api
|
||||||
|
volumes:
|
||||||
|
- openwa-data:/app/data
|
||||||
|
expose:
|
||||||
|
- "2785"
|
||||||
|
networks:
|
||||||
|
- default
|
||||||
|
|
||||||
web:
|
web:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
@@ -77,3 +127,7 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
dokploy-network:
|
dokploy-network:
|
||||||
external: true
|
external: true
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
# Sesiones de OpenWA: perderlo obliga a cada profesor a escanear el QR otra vez.
|
||||||
|
openwa-data:
|
||||||
|
|||||||
312
docs/whatsapp.md
Normal file
312
docs/whatsapp.md
Normal file
@@ -0,0 +1,312 @@
|
|||||||
|
# WhatsApp: recordatorios de pago y reenganche automáticos
|
||||||
|
|
||||||
|
Gruperly le escribe por WhatsApp a los miembros de un grupo **una vez por semana** (lunes 10:00, hora de Argentina), desde el **número del profesor** dueño del grupo:
|
||||||
|
|
||||||
|
- **Recordatorio de pago**: a quien tenga un cobro `PENDING` u `OVERDUE` con link de Checkout Pro y vencimiento dentro de los próximos 7 días (o ya vencido). Va un mensaje por miembro con el cobro más viejo.
|
||||||
|
- **Reenganche**: a los miembros que aparecen en **Alumnos en riesgo** (misma regla: 2+ faltas seguidas o menos de 50% de asistencia en 30 días). Como máximo uno cada 14 días por miembro.
|
||||||
|
|
||||||
|
Cada automatización se prende **por grupo** (ficha del grupo → "Mensajes automáticos por WhatsApp"); vienen apagadas. El botón manual "Reenganchar por WhatsApp" de Alumnos en riesgo sigue funcionando igual (abre `wa.me`).
|
||||||
|
|
||||||
|
El envío pasa por un **proveedor intercambiable**:
|
||||||
|
|
||||||
|
| | **OpenWA** (MVP, default) | **Kapso** (fase 2) |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Qué es | Gateway self-hosted ([rmyndharis/OpenWA](https://github.com/rmyndharis/OpenWA), MIT) sobre WhatsApp Web | Plataforma sobre la **API oficial** de WhatsApp Cloud (Meta) |
|
||||||
|
| Vinculación | El profesor escanea un **QR** dentro de Gruperly ("dispositivo vinculado") | El profesor va a un **setup link** de Meta (Facebook login + verificación del número) y vuelve |
|
||||||
|
| Mensajes | Texto libre | **Templates** aprobados por Meta por cada cuenta |
|
||||||
|
| Costo | Infraestructura propia | Plan de Kapso + tarifa de Meta por mensaje (la paga el profesor) |
|
||||||
|
| Riesgo | **No oficial**: viola los términos de WhatsApp; el número se puede bloquear | Ninguno de ToS |
|
||||||
|
|
||||||
|
Se elige con `WHATSAPP_PROVIDER=openwa|kapso`. El dominio, los jobs y la UI no saben cuál está activo.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Arquitectura
|
||||||
|
|
||||||
|
```text
|
||||||
|
apps/backend/src/modules/whatsapp/
|
||||||
|
├── providers/
|
||||||
|
│ ├── messaging-provider.ts # el puerto (interfaz MessagingProvider) + tipos normalizados
|
||||||
|
│ ├── index.ts # getMessagingProvider(): único lugar que mapea id → adaptador
|
||||||
|
│ ├── active.ts # WHATSAPP_PROVIDER
|
||||||
|
│ ├── openwa/ # config, cliente HTTP, adaptador
|
||||||
|
│ └── kapso/ # config, cliente HTTP, templates, adaptador
|
||||||
|
├── lib/
|
||||||
|
│ ├── render-message.ts # copy en español (texto libre; base de los templates)
|
||||||
|
│ ├── dispatch.ts # pipeline de envío: log → send → estado, pacing, rate limit
|
||||||
|
│ ├── activate-account.ts # PENDING → ACTIVE + onConnected (idempotente)
|
||||||
|
│ ├── account.ts # estado visible (none/pending/active/…/requires_reconnect)
|
||||||
|
│ ├── hmac.ts, period.ts, format.ts
|
||||||
|
├── features/
|
||||||
|
│ ├── connect/ # POST /whatsapp/connect → { start: qr | redirect }
|
||||||
|
│ ├── status/ # GET /whatsapp/status (hace polling al proveedor si está PENDING)
|
||||||
|
│ ├── disconnect/ # DELETE /whatsapp/connect
|
||||||
|
│ ├── callback/ # GET /whatsapp/callback (solo Kapso; siempre 302)
|
||||||
|
│ ├── webhook/ # POST /whatsapp/webhooks/:provider (público, HMAC)
|
||||||
|
│ └── update-automations/ # PATCH /groups/:groupId/automations (montado desde groups)
|
||||||
|
└── jobs/ # SendPaymentReminders, SendReengagementMessages, SyncKapsoTemplates
|
||||||
|
```
|
||||||
|
|
||||||
|
### El puerto `MessagingProvider`
|
||||||
|
|
||||||
|
| Método | OpenWA | Kapso |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `startConnection` | Crea/adopta la sesión `gruperly-<userId>`, registra su webhook, la arranca y devuelve `{ type: 'qr' }` | Crea el customer (una vez) y un setup link `customer_managed`; devuelve `{ type: 'redirect' }` |
|
||||||
|
| `refreshConnection` | `GET /sessions/:id` (QR nuevo, `ready`, `failed`) | No hay QR: `pending` hasta el callback o el webhook |
|
||||||
|
| `completeRedirect` | — | Valida `setup_link_id` y que el número sea del customer del profesor |
|
||||||
|
| `onConnected` | — | Suscribe el webhook del número y envía los templates a Meta |
|
||||||
|
| `readiness(kind)` | `ready` si la cuenta está activa | `ready` solo con el template `APPROVED` |
|
||||||
|
| `resolveRecipient` | `contacts/check` (resuelve el `9` de Argentina) | E.164 en dígitos |
|
||||||
|
| `send` | `send-text` con `Idempotency-Key` | Template con parámetros NAMED |
|
||||||
|
| `parseWebhook` | `X-OpenWA-Signature: sha256=<hex>`, dedupe `X-OpenWA-Idempotency-Key` | `X-Webhook-Signature` (hex), dedupe `X-Idempotency-Key` |
|
||||||
|
|
||||||
|
**Para agregar un proveedor**: crear `providers/<nombre>/` que implemente `MessagingProvider`, sumar el id al enum `MessagingProviderId` (Prisma) y a `whatsappProviderSchema` (shared), un `case` en `getMessagingProvider()`, el valor en `providers/active.ts`, la ruta pública del webhook en `isPublicApiRequest` y sus tests en `test/whatsapp-providers.test.ts`.
|
||||||
|
|
||||||
|
### Datos
|
||||||
|
|
||||||
|
- `whatsapp_accounts`: una fila por profesor (`provider`, `status` `PENDING|ACTIVE|DISCONNECTED`, `external_id` = sesión de OpenWA o `phone_number_id` de Kapso, `provider_data` con ids del proveedor — **nunca secretos**). `@@unique([provider, externalId])`: un número no se vincula a dos profesores.
|
||||||
|
- `whatsapp_templates`: templates de Kapso por cuenta y tipo, con el estado de revisión de Meta.
|
||||||
|
- `outbound_messages`: log de cada envío automático y **llave de idempotencia** (`@@unique([kind, attendeeId, periodKey])`, con `periodKey` = semana ISO). Estados `QUEUED → SENT → DELIVERED → READ`, o `FAILED` / `SKIPPED` (`invalid_phone`, `no_whatsapp`).
|
||||||
|
- `whatsapp_webhook_events`: claves de idempotencia de webhooks ya procesados.
|
||||||
|
- `groups.auto_payment_reminders` / `groups.auto_reengagement`.
|
||||||
|
|
||||||
|
### Vinculación
|
||||||
|
|
||||||
|
```text
|
||||||
|
OpenWA (QR)
|
||||||
|
POST /whatsapp/connect ─▶ OpenWA: crear sesión + webhook + start ─▶ { start: { type: 'qr', qrCode } }
|
||||||
|
modal con el QR ── GET /whatsapp/status cada 2 s ──▶ OpenWA GET /sessions/:id
|
||||||
|
qr_ready → QR nuevo · ready → ACTIVE (se cierra el modal)
|
||||||
|
(en paralelo, si hay webhook: session.authenticated → ACTIVE)
|
||||||
|
|
||||||
|
Kapso (redirect)
|
||||||
|
POST /whatsapp/connect ─▶ Kapso: customer + setup link ─▶ { start: { type: 'redirect', url } }
|
||||||
|
navegador ─▶ Meta (login + verificación) ─▶ GET /whatsapp/callback?setup_link_id&phone_number_id…
|
||||||
|
valida link + dueño del número ─▶ ACTIVE + webhook del número + templates a Meta
|
||||||
|
─▶ 302 /onboarding|/settings?wa=success | ?wa=error&reason=…
|
||||||
|
(respaldo: webhook whatsapp.phone_number.created → ACTIVE)
|
||||||
|
```
|
||||||
|
|
||||||
|
Si `WHATSAPP_PROVIDER` cambia, las cuentas vinculadas con el proveedor anterior se muestran como **"Necesita vincularse de nuevo"** (`requires_reconnect`) y no envían nada hasta que el profesor vuelva a vincular. La fila no se borra, así que volver atrás no pierde nada.
|
||||||
|
|
||||||
|
### Job semanal
|
||||||
|
|
||||||
|
```text
|
||||||
|
Bun.cron('0 13 * * 1', UTC) ── lunes 13:00 UTC = 10:00 AR
|
||||||
|
1. SendPaymentReminders 2. SendReengagementMessages
|
||||||
|
grupos con el switch prendido + dueño con cuenta ACTIVE del proveedor activo + readiness 'ready'
|
||||||
|
por cada miembro: teléfono (propio o del tutor) → E.164 con el país del profesor
|
||||||
|
→ resolveRecipient → INSERT outbound_messages (QUEUED) ← unique por semana: no duplica
|
||||||
|
→ send(…, idempotencyKey = id de la fila) → SENT | FAILED
|
||||||
|
pausa WHATSAPP_SEND_INTERVAL_MS entre envíos del mismo profesor
|
||||||
|
429 / rate limit → se corta ESE profesor; lo no enviado queda para la semana siguiente
|
||||||
|
```
|
||||||
|
|
||||||
|
El recordatorio va antes que el reenganche: si el gateway corta a mitad de camino, el mensaje de plata es el que ya salió. Con Kapso además corre `SyncKapsoTemplates` cada 30 min (no hay webhook documentado para el veredicto de Meta).
|
||||||
|
|
||||||
|
**Teléfonos.** Los de los miembros se guardan como se escribieron (`normalizePhone` solo deja dígitos), así que `toWhatsappE164` (`packages/shared/src/lib/phone.ts`) les agrega el código del país del profesor. Para Argentina acepta `011 15 2345-6789`, `11 2345 6789`, `9 11…`, `54 9 11…` y devuelve `+54 9 11 2345 6789`. Un número que ya trae `+` o `00` se respeta. Si no se puede interpretar, el envío queda `SKIPPED invalid_phone`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## OpenWA (MVP)
|
||||||
|
|
||||||
|
### Riesgos: leer antes de prender
|
||||||
|
|
||||||
|
OpenWA automatiza **WhatsApp Web**, no la API oficial. Eso **viola los Términos de WhatsApp**, y WhatsApp puede restringir o bloquear el número del profesor, sobre todo si:
|
||||||
|
|
||||||
|
- el número es nuevo o se vinculó hace poco (recién vinculado → pocos mensajes),
|
||||||
|
- se escribe a mucha gente que nunca habló con ese número ("cold reachout"),
|
||||||
|
- los mensajes son idénticos y salen en ráfaga, o se envía desde IPs de datacenter.
|
||||||
|
|
||||||
|
Mitigaciones que ya están en el código o el compose:
|
||||||
|
|
||||||
|
- `SEND_PACING_ENABLED=true`: tope diario que crece con la antigüedad de la sesión y tope de conversaciones nuevas. Cuando se llega al tope, OpenWA responde `429 SEND_PACING_LIMITED`. El job corta ese profesor y lo pendiente queda para la semana siguiente.
|
||||||
|
- Un envío cada `WHATSAPP_SEND_INTERVAL_MS` (5 s, unos 12 por minuto) por profesor. El documento de riesgo de OpenWA marca alerta a los 15/min.
|
||||||
|
- `SIMULATE_TYPING=true` y mensajes personalizados (nombre, grupo, monto).
|
||||||
|
- Los destinatarios son miembros del grupo del profesor, no gente desconocida.
|
||||||
|
|
||||||
|
Igual: **es para validar el MVP con pocos profesores**, idealmente con su consentimiento informado. Para escalar, pasar a Kapso.
|
||||||
|
|
||||||
|
### Deploy
|
||||||
|
|
||||||
|
El compose trae el servicio `openwa`:
|
||||||
|
|
||||||
|
- **Imagen**: `ghcr.io/rmyndharis/openwa:${OPENWA_IMAGE_TAG:-0.25.0}`. Va pineada; el proyecto todavía no llegó a 1.0. Antes de subirla, revisar el changelog y confirmar en ghcr que el tag existe.
|
||||||
|
- **Motor**: `ENGINE_TYPE=baileys`, por WebSocket y sin Chromium por sesión, mucho más liviano.
|
||||||
|
- **Persistencia**: SQLite y sesiones en el volumen `openwa-data` (`/app/data`). **Si se pierde ese volumen, todos los profesores tienen que volver a escanear el QR.** Para algo más robusto: `DATABASE_TYPE=postgres` con una base aparte.
|
||||||
|
- **Red**: solo la interna, y la API le habla por `http://openwa:2785/api`. No publicar el puerto: cualquiera con la key manda mensajes desde los números de los profesores.
|
||||||
|
- **Webhook**: `SSRF_ALLOWED_HOSTS=api` deja que OpenWA llame a la API por la red interna. Sin eso, su guard SSRF rechaza el webhook.
|
||||||
|
|
||||||
|
**Primera vez (API key):**
|
||||||
|
|
||||||
|
1. `docker compose up -d openwa`. En el primer arranque OpenWA escribe una key **ADMIN** en `/app/data/.api-key`:
|
||||||
|
```bash
|
||||||
|
docker compose exec openwa cat /app/data/.api-key
|
||||||
|
```
|
||||||
|
2. Con esa key, crear la key **OPERATOR** que usa Gruperly (sin `allowedSessions`, porque crea sesiones):
|
||||||
|
```bash
|
||||||
|
# desde el contenedor de la API, que está en la misma red (el puerto no se publica)
|
||||||
|
docker compose exec api bun -e "const r = await fetch('http://openwa:2785/api/auth/api-keys', { \
|
||||||
|
method: 'POST', headers: { 'X-API-Key': '<ADMIN>', 'Content-Type': 'application/json' }, \
|
||||||
|
body: JSON.stringify({ name: 'gruperly-api', role: 'operator' }) }); console.log(await r.json())"
|
||||||
|
```
|
||||||
|
El campo `apiKey` (`owa_k1_…`) de la respuesta es `OPENWA_API_KEY`. Se devuelve **una sola vez**.
|
||||||
|
3. Cargar en el entorno de la API:
|
||||||
|
|
||||||
|
| Variable | ¿Obligatoria? | Descripción |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `WHATSAPP_PROVIDER` | no | `openwa` (default) |
|
||||||
|
| `OPENWA_API_URL` | sí | `http://openwa:2785/api` en el compose, `http://localhost:2785/api` en local |
|
||||||
|
| `OPENWA_API_KEY` | sí | Key OPERATOR del paso 2 |
|
||||||
|
| `OPENWA_WEBHOOK_URL` | no | `http://api:4000/api/v1/whatsapp/webhooks/openwa`. Sin webhook la vinculación funciona igual (polling), pero no se registran entregas ni lecturas |
|
||||||
|
| `OPENWA_WEBHOOK_SECRET` | si hay webhook | 16+ caracteres: `openssl rand -hex 24`. Se registra en cada sesión y firma cada entrega |
|
||||||
|
| `WHATSAPP_SEND_INTERVAL_MS` | no | Default `5000` |
|
||||||
|
|
||||||
|
Si falta una obligatoria, `/whatsapp/*` responde `503 whatsapp_not_configured` (con el nombre de la variable en el log, nunca su valor), el paso del onboarding se puede saltear y los jobs no hacen nada.
|
||||||
|
|
||||||
|
### Local
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d openwa # o: docker run -d -p 2785:2785 -v openwa-data:/app/data \
|
||||||
|
# -e ENGINE_TYPE=baileys -e SEND_PACING_ENABLED=true \
|
||||||
|
# ghcr.io/rmyndharis/openwa:0.25.0
|
||||||
|
# apps/backend/.env
|
||||||
|
OPENWA_API_URL="http://localhost:2785/api"
|
||||||
|
OPENWA_API_KEY="owa_k1_…"
|
||||||
|
```
|
||||||
|
|
||||||
|
El webhook es opcional en local. Si se quiere probar, OpenWA tiene que alcanzar la API: `OPENWA_WEBHOOK_URL=http://host.docker.internal:4000/api/v1/whatsapp/webhooks/openwa` y `SSRF_ALLOWED_HOSTS=host.docker.internal` en el contenedor.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Kapso (fase 2)
|
||||||
|
|
||||||
|
### Setup
|
||||||
|
|
||||||
|
1. Crear un proyecto en [Kapso](https://app.kapso.ai) y una **API key** (`KAPSO_API_KEY`).
|
||||||
|
2. **Project webhook** (dashboard → Webhooks):
|
||||||
|
- URL `https://<api pública>/api/v1/whatsapp/webhooks/kapso`.
|
||||||
|
- Eventos `whatsapp.phone_number.created`, `whatsapp.phone_number.disconnected`, `whatsapp.phone_number.deleted` y `whatsapp.phone_number.offboarded`.
|
||||||
|
- Un secreto propio (`KAPSO_WEBHOOK_SECRET`; Kapso no lo genera).
|
||||||
|
|
||||||
|
Los eventos de mensajes (`whatsapp.message.sent|delivered|read|failed`) se suscriben **por número**, solos, cuando el profesor vincula (`onConnected`), con el mismo secreto.
|
||||||
|
3. **Plan**: el Free admite **un solo número**, así que sirve para desarrollo. Varios profesores requieren el plan **Platform**, que incluye 50 números.
|
||||||
|
4. **Facturación de Meta**: los setup links se crean con `meta_billing_mode: customer_managed`. Cada profesor carga su tarjeta en Meta durante el flujo, y Gruperly no paga ni re-factura mensajes. El modo queda fijo al crear el link.
|
||||||
|
5. Variables de la API (`WHATSAPP_PROVIDER=kapso`):
|
||||||
|
|
||||||
|
| Variable | ¿Obligatoria? | Descripción |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `KAPSO_API_KEY` | sí | Header `X-API-Key` |
|
||||||
|
| `KAPSO_CALLBACK_URL` | sí | `https://<api pública>/api/v1/whatsapp/callback`: adonde vuelve el setup link |
|
||||||
|
| `KAPSO_WEBHOOK_URL` | sí | `https://<api pública>/api/v1/whatsapp/webhooks/kapso` |
|
||||||
|
| `KAPSO_WEBHOOK_SECRET` | sí | El secreto del project webhook |
|
||||||
|
| `KAPSO_API_URL` | no | Default `https://api.kapso.ai` |
|
||||||
|
|
||||||
|
En local, las dos URLs pasan por el mismo túnel que Mercado Pago (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`).
|
||||||
|
|
||||||
|
### Templates
|
||||||
|
|
||||||
|
Meta solo deja escribir fuera de la ventana de 24 h con **templates aprobados**, y los aprueba **por cuenta** (WABA). Por eso, al vincular, se envían los dos de `providers/kapso/templates.ts` (`es_AR`, parámetros NAMED):
|
||||||
|
|
||||||
|
| Template | Categoría | Parámetros |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `gruperly_payment_reminder` | `UTILITY` | `student_name`, `group_name`, `amount`, `due_date`, `payment_link` |
|
||||||
|
| `gruperly_reengagement` | `MARKETING` | `student_name`, `group_name` |
|
||||||
|
|
||||||
|
- La revisión tarda hasta unas 24 h. Mientras tanto, Ajustes muestra "En revisión por Meta" y el switch del grupo no se puede prender.
|
||||||
|
- **No se editan**: cambiar el texto implica un nombre nuevo (`…_v2`) y otra revisión. El cuerpo sigue el copy de `lib/render-message.ts` (OpenWA); si cambia uno, cambiar el otro.
|
||||||
|
- El recordatorio es `UTILITY` mientras **no tenga nada promocional**. Meta puede recategorizarlo solo.
|
||||||
|
- El reenganche es `MARKETING`: el alumno puede haberse dado de baja de marketing (`marketing_preference_stopped`), y entonces el envío queda `FAILED` y no se reintenta.
|
||||||
|
- Meta no deja que el cuerpo empiece o termine con una variable (por eso el "¡Gracias!" del final).
|
||||||
|
|
||||||
|
### Seguridad del callback
|
||||||
|
|
||||||
|
Los parámetros de `/whatsapp/callback` los puede escribir cualquiera, así que no se confía en ellos. `setup_link_id` tiene que ser el último link creado para ese profesor, y `GET /platform/v1/whatsapp/phone_numbers/{id}` tiene que confirmar que el número pertenece a su customer de Kapso. Si el número ya está vinculado a otro profesor, la respuesta es `?wa=error&reason=number_in_use`.
|
||||||
|
|
||||||
|
### Sandbox
|
||||||
|
|
||||||
|
El sandbox de Kapso **no soporta templates**, así que el flujo completo se prueba con un número real en el plan Free. Los webhooks se pueden disparar con el "test webhook" del dashboard.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Webhooks (los dos proveedores)
|
||||||
|
|
||||||
|
`POST /api/v1/whatsapp/webhooks/openwa|kapso` es **público**: está en `isPublicApiRequest` con match exacto. El flujo:
|
||||||
|
|
||||||
|
1. Lee el **raw body**: la firma se calcula sobre los bytes exactos, no sobre el JSON re-serializado.
|
||||||
|
2. Verifica el HMAC-SHA256 en tiempo constante. Si falla, responde `401` sin tocar la base.
|
||||||
|
3. Quema la clave de idempotencia en `whatsapp_webhook_events`. Si ya existía, responde `200 { duplicate: true }`.
|
||||||
|
4. Aplica los eventos normalizados:
|
||||||
|
- **conexión**: la cuenta pasa a `ACTIVE` (con `onConnected` una sola vez) o a `DISCONNECTED`.
|
||||||
|
- **estado de mensaje**: avanza `outbound_messages` por `provider_message_id` y nunca retrocede (un `delivered` tardío no pisa un `read`).
|
||||||
|
5. Si aplicar falla, des-quema la clave y responde `500`, para que el reintento del proveedor entre.
|
||||||
|
|
||||||
|
Kapso reintenta si no recibe un 200 en 10 s.
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
| Endpoint | Qué hace |
|
||||||
|
| --- | --- |
|
||||||
|
| `POST /api/v1/whatsapp/connect` | Body `{ returnTo: 'onboarding' \| 'settings' }`. Responde `{ start: { type: 'qr', qrCode } \| { type: 'redirect', url } }` |
|
||||||
|
| `GET /api/v1/whatsapp/status` | `{ status, provider, displayPhoneNumber, connectedAt, qrCode, readiness: { PAYMENT_REMINDER, REENGAGEMENT } }`. Con la cuenta `PENDING` consulta al proveedor (para el modal del QR) |
|
||||||
|
| `DELETE /api/v1/whatsapp/connect` | Desvincula: con OpenWA hace logout del teléfono y borra la sesión. Localmente la fila queda `DISCONNECTED`, sin número |
|
||||||
|
| `GET /api/v1/whatsapp/callback` | Solo Kapso. Siempre responde `302` |
|
||||||
|
| `POST /api/v1/whatsapp/webhooks/:provider` | Público, firmado |
|
||||||
|
| `PATCH /api/v1/groups/:groupId/automations` | `{ autoPaymentReminders?, autoReengagement? }`. Solo el dueño (`403 group_owner_required`) |
|
||||||
|
|
||||||
|
**Errores típicos**:
|
||||||
|
|
||||||
|
- `503 whatsapp_not_configured`: faltan variables del proveedor activo.
|
||||||
|
- `502 whatsapp_provider_error`: el gateway no responde o rechazó el pedido.
|
||||||
|
- `409`: conflicto.
|
||||||
|
|
||||||
|
## Verificar a mano (OpenWA)
|
||||||
|
|
||||||
|
1. `docker compose up -d openwa`, crear la key OPERATOR y cargar `OPENWA_*` en `apps/backend/.env`. Después `bun dev`.
|
||||||
|
2. **Onboarding**:
|
||||||
|
- Cuenta nueva → paso "WhatsApp" → "Vincular WhatsApp" abre el QR.
|
||||||
|
- Escanearlo desde WhatsApp → Dispositivos vinculados.
|
||||||
|
- El modal se cierra solo y el paso muestra el número.
|
||||||
|
- "Lo hago después" deja seguir sin vincular.
|
||||||
|
3. **Ajustes → WhatsApp**: muestra "Vinculado", el número y "Listo para enviar" en los dos mensajes. "Desvincular" pide confirmación y el dispositivo desaparece del teléfono.
|
||||||
|
4. **Grupo**: en la ficha, prender "Recordatorio semanal de pago" y "Mensaje de reenganche semanal". Sin WhatsApp vinculado los switches quedan deshabilitados, con link a Ajustes.
|
||||||
|
5. **Job a mano**, con un grupo que tenga un cobro pendiente con link y un alumno con 2 faltas seguidas:
|
||||||
|
```bash
|
||||||
|
cd apps/backend
|
||||||
|
bun -e "import { SendPaymentReminders, SendReengagementMessages } from './src/modules/whatsapp/jobs'; \
|
||||||
|
console.log(await new SendPaymentReminders().execute()); \
|
||||||
|
console.log(await new SendReengagementMessages().execute())"
|
||||||
|
```
|
||||||
|
Tienen que llegar los mensajes y quedar filas en `outbound_messages`:
|
||||||
|
```sql
|
||||||
|
SELECT kind, status, to_phone, error_code, period_key FROM outbound_messages ORDER BY created_at DESC;
|
||||||
|
```
|
||||||
|
6. **Idempotencia**: correr el job otra vez en la misma semana. Responde `sent: 0` y no llega nada nuevo.
|
||||||
|
7. **Entregas** (con webhook): las filas pasan a `DELIVERED` y `READ` a medida que el alumno abre el mensaje.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Síntoma | Causa probable |
|
||||||
|
| --- | --- |
|
||||||
|
| `503 whatsapp_not_configured` | Falta `OPENWA_API_URL`/`OPENWA_API_KEY` (o las `KAPSO_*`). El log dice cuál. `OPENWA_WEBHOOK_URL` sin `OPENWA_WEBHOOK_SECRET` también cuenta como mal configurado |
|
||||||
|
| El QR no aparece | La sesión todavía está `initializing`; el modal reintenta cada 2 s. Si sigue, revisar los logs de `openwa` (red hacia WhatsApp, `MAX_CONCURRENT_SESSIONS`) |
|
||||||
|
| Webhook `401` | El secreto no coincide, o hay un proxy que modifica el body |
|
||||||
|
| OpenWA no llama al webhook | Falta `SSRF_ALLOWED_HOSTS` para un host interno |
|
||||||
|
| `SKIPPED invalid_phone` | El teléfono del miembro no se pudo pasar a E.164 con el país del profesor |
|
||||||
|
| `SKIPPED no_whatsapp` | El número no tiene WhatsApp (contact check de OpenWA) |
|
||||||
|
| `FAILED SEND_PACING_LIMITED` / envíos cortados | Tope diario de OpenWA. Esperar a la semana siguiente o revisar `SEND_PACING_*` |
|
||||||
|
| Kapso `FAILED 131047` | Ventana de 24 h. No debería pasar con templates |
|
||||||
|
| Kapso `FAILED marketing_preference_stopped` | El alumno se dio de baja de marketing (solo afecta al reenganche) |
|
||||||
|
| Kapso: switch deshabilitado "En revisión por Meta" | Template `PENDING`. `SyncKapsoTemplates` lo actualiza cada 30 min |
|
||||||
|
| Cuenta en "Necesita vincularse de nuevo" | Se cambió `WHATSAPP_PROVIDER`; el profesor tiene que vincular con el proveedor nuevo |
|
||||||
|
|
||||||
|
## Guía para el profesor
|
||||||
|
|
||||||
|
**Con OpenWA (hoy):**
|
||||||
|
|
||||||
|
1. En Gruperly: Ajustes → WhatsApp → **Vincular** (o el paso "WhatsApp" del onboarding).
|
||||||
|
2. En el teléfono: WhatsApp → **Dispositivos vinculados** → **Vincular un dispositivo** → escanear el código.
|
||||||
|
3. En cada grupo, prender los mensajes automáticos que quieras. Salen los lunes a las 10:00, desde tu número, y las respuestas de tus alumnos te llegan a tu WhatsApp de siempre.
|
||||||
|
4. Para cortar: Ajustes → WhatsApp → Desvincular, o quitar el dispositivo desde el teléfono.
|
||||||
|
|
||||||
|
**Con Kapso (más adelante):** "Vincular" te lleva a Meta. Ahí iniciás sesión con Facebook, conectás o creás tu cuenta de WhatsApp Business, verificás el número por SMS y cargás un medio de pago: Meta cobra cada mensaje según la categoría y el país. Tarda unos 5 minutos. Después Meta revisa los dos mensajes de Gruperly (hasta 24 h) y recién ahí se pueden prender en los grupos.
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
export * from './lib/attendance-risk.js';
|
export * from './lib/attendance-risk.js';
|
||||||
|
export * from './lib/phone.js';
|
||||||
export * from './lib/problem-details.js';
|
export * from './lib/problem-details.js';
|
||||||
export * from './lib/result.js';
|
export * from './lib/result.js';
|
||||||
export * from './schemas/analytics.js';
|
export * from './schemas/analytics.js';
|
||||||
@@ -15,4 +16,5 @@ export * from './schemas/pagination.js';
|
|||||||
export * from './schemas/payments.js';
|
export * from './schemas/payments.js';
|
||||||
export * from './schemas/preregistrations.js';
|
export * from './schemas/preregistrations.js';
|
||||||
export * from './schemas/problem-details.js';
|
export * from './schemas/problem-details.js';
|
||||||
export * from './schemas/waitlist.js';
|
export * from './schemas/waitlist.js';
|
||||||
|
export * from './schemas/whatsapp.js';
|
||||||
100
packages/shared/src/lib/phone.ts
Normal file
100
packages/shared/src/lib/phone.ts
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
import type { CountryCode } from '../schemas/country.js';
|
||||||
|
|
||||||
|
type CountryDialPlan = {
|
||||||
|
callingCode: string;
|
||||||
|
// Length of the national number once the trunk prefix ("0") is gone.
|
||||||
|
nationalLengths: readonly number[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const DIAL_PLANS: Record<CountryCode, CountryDialPlan> = {
|
||||||
|
// Argentina is special-cased below (mobile "9" and the local "15").
|
||||||
|
AR: { callingCode: '54', nationalLengths: [10] },
|
||||||
|
BR: { callingCode: '55', nationalLengths: [10, 11] },
|
||||||
|
CL: { callingCode: '56', nationalLengths: [9] },
|
||||||
|
CO: { callingCode: '57', nationalLengths: [10] },
|
||||||
|
MX: { callingCode: '52', nationalLengths: [10] },
|
||||||
|
PE: { callingCode: '51', nationalLengths: [9] },
|
||||||
|
UY: { callingCode: '598', nationalLengths: [8] },
|
||||||
|
};
|
||||||
|
|
||||||
|
const MIN_E164_DIGITS = 10;
|
||||||
|
const MAX_E164_DIGITS = 15;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns a phone number as the teacher typed it into the E.164 form WhatsApp
|
||||||
|
* expects (`+5491123456789`), or `null` when it cannot tell which number it is.
|
||||||
|
*
|
||||||
|
* Attendee phones are stored the way they were entered (`normalizePhone` keeps
|
||||||
|
* digits only), so most of them are national numbers: the country of the teacher
|
||||||
|
* decides the calling code. A number that already starts with `+` or `00` is
|
||||||
|
* international and is kept as is.
|
||||||
|
*
|
||||||
|
* Argentina needs extra care: WhatsApp numbers there are `54 9 <area> <number>`,
|
||||||
|
* while people write them as `0<area> 15 <number>` or `<area> <number>`.
|
||||||
|
*/
|
||||||
|
export function toWhatsappE164(phone: string, country: CountryCode | null | undefined): string | null {
|
||||||
|
const trimmed = phone.trim();
|
||||||
|
if (!trimmed) return null;
|
||||||
|
|
||||||
|
const isInternational = trimmed.startsWith('+') || trimmed.startsWith('00');
|
||||||
|
let digits = trimmed.replace(/\D/g, '');
|
||||||
|
if (trimmed.startsWith('00')) digits = digits.slice(2);
|
||||||
|
if (!digits) return null;
|
||||||
|
|
||||||
|
if (isInternational) {
|
||||||
|
return finalize(digits.startsWith('54') ? argentinaInternational(digits) : digits);
|
||||||
|
}
|
||||||
|
|
||||||
|
const plan = DIAL_PLANS[country ?? 'AR'];
|
||||||
|
|
||||||
|
// Written with the calling code but without "+" (e.g. "5491123456789").
|
||||||
|
if (digits.startsWith(plan.callingCode)) {
|
||||||
|
const rest = digits.slice(plan.callingCode.length);
|
||||||
|
if (country === 'AR' || !country) {
|
||||||
|
const national = argentinaNational(rest);
|
||||||
|
if (national) return finalize(`54${national}`);
|
||||||
|
} else if (plan.nationalLengths.includes(rest.length)) {
|
||||||
|
return finalize(digits);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (country === 'AR' || !country) {
|
||||||
|
const national = argentinaNational(digits);
|
||||||
|
return national ? finalize(`54${national}`) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const national = digits.startsWith('0') ? digits.slice(1) : digits;
|
||||||
|
if (!plan.nationalLengths.includes(national.length)) return null;
|
||||||
|
return finalize(`${plan.callingCode}${national}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Argentine national number to `9<area><number>` (11 digits), accepting the
|
||||||
|
* trunk "0", the mobile "9" and the local "15" after the area code.
|
||||||
|
*/
|
||||||
|
function argentinaNational(input: string): string | null {
|
||||||
|
let digits = input.startsWith('0') ? input.slice(1) : input;
|
||||||
|
if (digits.length === 11 && digits.startsWith('9')) digits = digits.slice(1);
|
||||||
|
|
||||||
|
if (digits.length === 12) {
|
||||||
|
// Area codes are 2 to 4 digits long; the "15" goes right after them.
|
||||||
|
for (const areaLength of [2, 3, 4]) {
|
||||||
|
if (digits.slice(areaLength, areaLength + 2) === '15') {
|
||||||
|
digits = digits.slice(0, areaLength) + digits.slice(areaLength + 2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return digits.length === 10 ? `9${digits}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function argentinaInternational(digits: string): string {
|
||||||
|
const national = argentinaNational(digits.slice(2));
|
||||||
|
return national ? `54${national}` : digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
function finalize(digits: string): string | null {
|
||||||
|
if (digits.length < MIN_E164_DIGITS || digits.length > MAX_E164_DIGITS) return null;
|
||||||
|
return `+${digits}`;
|
||||||
|
}
|
||||||
@@ -23,6 +23,9 @@ export const GroupDtoSchema = z.object({
|
|||||||
billingType: billingTypeSchema.nullable(),
|
billingType: billingTypeSchema.nullable(),
|
||||||
dueDay: z.number().int().min(1).max(28).nullable(),
|
dueDay: z.number().int().min(1).max(28).nullable(),
|
||||||
inviteToken: z.string().nullable().optional(),
|
inviteToken: z.string().nullable().optional(),
|
||||||
|
// Weekly WhatsApp automations (payment reminder and re-engagement).
|
||||||
|
autoPaymentReminders: z.boolean(),
|
||||||
|
autoReengagement: z.boolean(),
|
||||||
});
|
});
|
||||||
export type GroupDto = z.output<typeof GroupDtoSchema>;
|
export type GroupDto = z.output<typeof GroupDtoSchema>;
|
||||||
|
|
||||||
|
|||||||
@@ -62,6 +62,8 @@ export type OnboardingStep = z.output<typeof onboardingStepSchema>;
|
|||||||
export const OnboardingStatusDtoSchema = z.object({
|
export const OnboardingStatusDtoSchema = z.object({
|
||||||
step: onboardingStepSchema,
|
step: onboardingStepSchema,
|
||||||
paymentConnected: z.boolean(),
|
paymentConnected: z.boolean(),
|
||||||
|
// WhatsApp is its own skippable step and does not move `step`.
|
||||||
|
whatsappConnected: z.boolean(),
|
||||||
completed: z.boolean(),
|
completed: z.boolean(),
|
||||||
});
|
});
|
||||||
export type OnboardingStatusDto = z.output<typeof OnboardingStatusDtoSchema>;
|
export type OnboardingStatusDto = z.output<typeof OnboardingStatusDtoSchema>;
|
||||||
111
packages/shared/src/schemas/whatsapp.ts
Normal file
111
packages/shared/src/schemas/whatsapp.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Which gateway the server sends WhatsApp messages through. The teacher never
|
||||||
|
// picks it: it is a deployment setting (`WHATSAPP_PROVIDER`).
|
||||||
|
export const whatsappProviderSchema = z.enum(['OPENWA', 'KAPSO']);
|
||||||
|
export type WhatsappProvider = z.output<typeof whatsappProviderSchema>;
|
||||||
|
|
||||||
|
// State of the teacher's WhatsApp, as the app sees it.
|
||||||
|
// - `pending`: linking started (QR on screen, or the teacher is at Meta).
|
||||||
|
// - `requires_reconnect`: linked with a provider the server no longer uses.
|
||||||
|
export const whatsappAccountStatusSchema = z.enum([
|
||||||
|
'none',
|
||||||
|
'pending',
|
||||||
|
'active',
|
||||||
|
'disconnected',
|
||||||
|
'requires_reconnect',
|
||||||
|
]);
|
||||||
|
export type WhatsappAccountStatus = z.output<typeof whatsappAccountStatusSchema>;
|
||||||
|
|
||||||
|
export const whatsappMessageKindSchema = z.enum(['PAYMENT_REMINDER', 'REENGAGEMENT']);
|
||||||
|
export type WhatsappMessageKind = z.output<typeof whatsappMessageKindSchema>;
|
||||||
|
|
||||||
|
// Whether automated messages of one kind can go out right now.
|
||||||
|
// `pending`: the account is linked but Meta has not approved the template yet.
|
||||||
|
export const whatsappReadinessSchema = z.enum(['ready', 'pending', 'blocked']);
|
||||||
|
export type WhatsappReadiness = z.output<typeof whatsappReadinessSchema>;
|
||||||
|
|
||||||
|
export const whatsappReturnToSchema = z.enum(['onboarding', 'settings']);
|
||||||
|
export type WhatsappReturnTo = z.output<typeof whatsappReturnToSchema>;
|
||||||
|
|
||||||
|
export const WhatsappConnectSchema = z.strictObject({
|
||||||
|
returnTo: whatsappReturnToSchema.default('settings'),
|
||||||
|
});
|
||||||
|
export type WhatsappConnect = z.output<typeof WhatsappConnectSchema>;
|
||||||
|
|
||||||
|
// How the browser continues the linking: show a QR code (OpenWA) or navigate to
|
||||||
|
// the provider's hosted flow (Kapso). The UI handles both without knowing which
|
||||||
|
// provider is behind.
|
||||||
|
export const WhatsappConnectionStartSchema = z.discriminatedUnion('type', [
|
||||||
|
// `qrCode` is null while the gateway is still generating it; the status
|
||||||
|
// endpoint delivers it (and every refresh) as soon as it exists.
|
||||||
|
z.object({ type: z.literal('qr'), qrCode: z.string().nullable() }),
|
||||||
|
z.object({ type: z.literal('redirect'), url: z.string() }),
|
||||||
|
]);
|
||||||
|
export type WhatsappConnectionStart = z.output<typeof WhatsappConnectionStartSchema>;
|
||||||
|
|
||||||
|
export const WhatsappConnectResultDtoSchema = z.object({
|
||||||
|
start: WhatsappConnectionStartSchema,
|
||||||
|
});
|
||||||
|
export type WhatsappConnectResultDto = z.output<typeof WhatsappConnectResultDtoSchema>;
|
||||||
|
|
||||||
|
export const WhatsappStatusDtoSchema = z.object({
|
||||||
|
status: whatsappAccountStatusSchema,
|
||||||
|
provider: whatsappProviderSchema,
|
||||||
|
displayPhoneNumber: z.string().nullable(),
|
||||||
|
connectedAt: z.string().nullable(),
|
||||||
|
// Fresh QR code (data URL) while a QR linking is pending; null otherwise.
|
||||||
|
qrCode: z.string().nullable(),
|
||||||
|
readiness: z.object({
|
||||||
|
PAYMENT_REMINDER: whatsappReadinessSchema,
|
||||||
|
REENGAGEMENT: whatsappReadinessSchema,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
export type WhatsappStatusDto = z.output<typeof WhatsappStatusDtoSchema>;
|
||||||
|
|
||||||
|
export const WhatsappDisconnectResultDtoSchema = z.object({
|
||||||
|
disconnected: z.boolean(),
|
||||||
|
});
|
||||||
|
export type WhatsappDisconnectResultDto = z.output<typeof WhatsappDisconnectResultDtoSchema>;
|
||||||
|
|
||||||
|
// Why a redirect-based linking (Kapso) failed. Codes only, never messages.
|
||||||
|
export const whatsappCallbackReasonSchema = z.enum([
|
||||||
|
// The setup link is unknown, belongs to someone else or was already used.
|
||||||
|
'invalid_setup',
|
||||||
|
// The teacher could not finish at Meta (login, verification, limits).
|
||||||
|
'setup_failed',
|
||||||
|
// The provider refused the request or could not be reached.
|
||||||
|
'provider_error',
|
||||||
|
// That number is already linked to another teacher.
|
||||||
|
'number_in_use',
|
||||||
|
]);
|
||||||
|
export type WhatsappCallbackReason = z.output<typeof whatsappCallbackReasonSchema>;
|
||||||
|
|
||||||
|
// Deliberately not `strictObject`: the provider writes this query (Kapso adds
|
||||||
|
// `business_account_id`, `display_phone_number` and others), and a strict schema
|
||||||
|
// would answer extra keys with a 400 in the browser instead of the redirect.
|
||||||
|
export const WhatsappCallbackQuerySchema = z.object({
|
||||||
|
// `catch` and not `default`: a mangled value still lands the teacher in Settings.
|
||||||
|
returnTo: whatsappReturnToSchema.catch('settings'),
|
||||||
|
setup_link_id: z.string().min(1).optional(),
|
||||||
|
status: z.string().optional(),
|
||||||
|
phone_number_id: z.string().min(1).optional(),
|
||||||
|
error_code: z.string().optional(),
|
||||||
|
});
|
||||||
|
export type WhatsappCallbackQuery = z.output<typeof WhatsappCallbackQuerySchema>;
|
||||||
|
|
||||||
|
export const UpdateGroupAutomationsSchema = z
|
||||||
|
.strictObject({
|
||||||
|
autoPaymentReminders: z.boolean().optional(),
|
||||||
|
autoReengagement: z.boolean().optional(),
|
||||||
|
})
|
||||||
|
.refine((value) => value.autoPaymentReminders !== undefined || value.autoReengagement !== undefined, {
|
||||||
|
message: 'Indicá al menos una automatización',
|
||||||
|
});
|
||||||
|
export type UpdateGroupAutomations = z.output<typeof UpdateGroupAutomationsSchema>;
|
||||||
|
|
||||||
|
export const GroupAutomationsDtoSchema = z.object({
|
||||||
|
autoPaymentReminders: z.boolean(),
|
||||||
|
autoReengagement: z.boolean(),
|
||||||
|
});
|
||||||
|
export type GroupAutomationsDto = z.output<typeof GroupAutomationsDtoSchema>;
|
||||||
4
stack.md
4
stack.md
@@ -41,7 +41,7 @@ gruperly/
|
|||||||
│ │ ├── src/
|
│ │ ├── src/
|
||||||
│ │ │ ├── http/ # Infraestructura HTTP (validate, problem-details, session-auth, ...)
|
│ │ │ ├── http/ # Infraestructura HTTP (validate, problem-details, session-auth, ...)
|
||||||
│ │ │ ├── lib/ # Prisma (cliente + UnitOfWork), pagination, email, helpers
|
│ │ │ ├── lib/ # Prisma (cliente + UnitOfWork), pagination, email, helpers
|
||||||
│ │ │ ├── modules/ # Módulos: health-check, auth, groups, attendees, payments, waitlist
|
│ │ │ ├── modules/ # Módulos: health-check, auth, mp, groups, attendees, payments, waitlist, whatsapp, …
|
||||||
│ │ │ │ └── <módulo>/
|
│ │ │ │ └── <módulo>/
|
||||||
│ │ │ │ ├── routes.ts
|
│ │ │ │ ├── routes.ts
|
||||||
│ │ │ │ └── features/<accion>/{route,use-case}.ts
|
│ │ │ │ └── features/<accion>/{route,use-case}.ts
|
||||||
@@ -50,7 +50,7 @@ gruperly/
|
|||||||
│ │ │ └── logger.ts # pino + pino-pretty
|
│ │ │ └── logger.ts # pino + pino-pretty
|
||||||
│ │ ├── prisma/
|
│ │ ├── prisma/
|
||||||
│ │ │ ├── schema.prisma # Generator + datasource simple
|
│ │ │ ├── schema.prisma # Generator + datasource simple
|
||||||
│ │ │ ├── models/ # Modelos multi-archivo (auth.prisma, domain.prisma)
|
│ │ │ ├── models/ # Modelos multi-archivo (auth, domain, attendance, whatsapp)
|
||||||
│ │ │ └── migrations/
|
│ │ │ └── migrations/
|
||||||
│ │ ├── generated/ # Cliente generado de Prisma (gitignoreado, alias @generated/*)
|
│ │ ├── generated/ # Cliente generado de Prisma (gitignoreado, alias @generated/*)
|
||||||
│ │ ├── prisma.config.ts # Config de Prisma CLI (datasource URL, migrations)
|
│ │ ├── prisma.config.ts # Config de Prisma CLI (datasource URL, migrations)
|
||||||
|
|||||||
Reference in New Issue
Block a user