Compare commits
6 Commits
4211d5cf39
...
developmen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac98495a6e | ||
|
|
5b3a035dcf | ||
|
|
9383841513 | ||
|
|
58c776e18c | ||
|
|
aac142d324 | ||
|
|
abb18f1815 |
23
.env.example
23
.env.example
@@ -3,7 +3,9 @@
|
|||||||
# Local: copy this file to `.env` at the root and fill in the values.
|
# Local: copy this file to `.env` at the root and fill in the values.
|
||||||
# Dokploy: no file needed; define the same variables in the Environment tab of
|
# Dokploy: no file needed; define the same variables in the Environment tab of
|
||||||
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
||||||
# file, which is where the `${...}` come from).
|
# file). The api container receives this whole file through `env_file`, so any
|
||||||
|
# variable the backend reads (docs/environment.md) works without touching the
|
||||||
|
# compose.
|
||||||
|
|
||||||
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
||||||
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
||||||
@@ -46,17 +48,28 @@ BETTER_AUTH_SECRET=""
|
|||||||
# MP_CLIENT_ID=""
|
# MP_CLIENT_ID=""
|
||||||
# MP_CLIENT_SECRET=""
|
# MP_CLIENT_SECRET=""
|
||||||
|
|
||||||
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md).
|
# Suscripción a Gruperly Pro (ver docs/billing.md y docs/environment.md).
|
||||||
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra
|
# Argentina la cobra con Suscripciones de Mercado Pago; el resto, con Stripe.
|
||||||
# entre países). No son las del OAuth del profesor. Un país sin las dos queda
|
# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina. No
|
||||||
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY.
|
# son las del OAuth del profesor. Sin las dos, Pro queda "no disponible" (503).
|
||||||
# MP_PLATFORM_ACCESS_TOKEN_AR=""
|
# MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||||
# MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
# MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||||
|
# Origen público de la API para la vuelta del checkout de Pro. Vacío =
|
||||||
|
# BETTER_AUTH_URL, que en este compose ya es el dominio público.
|
||||||
|
# API_PUBLIC_URL=""
|
||||||
|
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda de
|
||||||
|
# cada país. Secret key (sk_live_…) y signing secret del webhook (whsec_…) del
|
||||||
|
# endpoint https://<API>/api/v1/billing/webhooks/stripe. Sin las dos, 503 ahí.
|
||||||
|
# STRIPE_SECRET_KEY=""
|
||||||
|
# STRIPE_WEBHOOK_SECRET=""
|
||||||
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
||||||
# BILLING_ENFORCEMENT="off"
|
# BILLING_ENFORCEMENT="off"
|
||||||
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||||
# BILLING_GRACE_DAYS="7"
|
# BILLING_GRACE_DAYS="7"
|
||||||
|
|
||||||
|
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
|
||||||
|
# ADMIN_EMAILS=""
|
||||||
|
|
||||||
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
|
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
|
||||||
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
|
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
|
||||||
# whatsapp_not_configured y el paso del onboarding es salteable.
|
# whatsapp_not_configured y el paso del onboarding es salteable.
|
||||||
|
|||||||
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: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
|
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; límites y precio de Pro por país se leen con `PlanCatalog`/`planCatalog`, nunca con `PLAN_LIMITS`/`PRO_PRICE_BY_COUNTRY` directo, que son solo defaults; guía en `docs/billing.md`). `admin` (backoffice de las cuentas de profesores, de solo lectura salvo **Planes** (`/admin/plans`: límites y precio de Pro, con opción de aplicar el precio a las suscripciones vivas desde el próximo cobro): acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*` y `/admin/plans*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
|
||||||
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
|
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
|
||||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||||
@@ -39,10 +39,16 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
|
|
||||||
## Gotchas operativos
|
## Gotchas operativos
|
||||||
|
|
||||||
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
|
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). Como la cookie de sesión es de `localhost:4000`, el callback que entra por el túnel rebota a `BETTER_AUTH_URL` con la misma query (`mpCallbackOriginMiddleware`, antes del middleware de sesión; no se dispara si ambos hosts coinciden, como en prod). El callback además exige que la sesión sea la del dueño del `state`. El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
|
||||||
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||||
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
- **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`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, 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**.
|
||||||
|
- **Cobro automático (`modules/payments/features/auto-charge*`)**: el profe elige en Ajustes un día del mes (1–28, `auto_charge_settings`) y el cron horario `RunAutoCharges` (`7 * * * *` UTC) corre `GenerateMonthlyCharges` cuando es ese día en **su** zona (`teacherTimeZone`), desde las 9 y con 3 días de tolerancia; si se prendió después del día, arranca el mes siguiente (`enabledAt`). Ojo con esto:
|
||||||
|
1. Idempotencia: `payment_runs` con `@@unique([ownerId, periodKey])` (mes `"2026-12"`), y además un índice único **parcial** a mano `payments_attendee_period_key` (`attendee_id, period_key WHERE period_key IS NOT NULL`); las cuotas manuales no llevan `periodKey`.
|
||||||
|
2. Un link por **pagador** (`PaymentCheckout`): el adulto a cargo (`primaryGuardian`) junta a sus chicos y lo suyo; si no, la persona. La preferencia lleva un ítem por cuota y `external_reference = chk_<checkoutId>` (nunca un payment id); el webhook es `POST /payments/webhooks/mp/checkout/:checkoutId` y `confirmMpCheckout` marca `PAID` todas sus cuotas. Las cuotas copian el `checkoutUrl` del checkout pero **no** su `mpPreferenceId`.
|
||||||
|
3. `Person.payWithMercadoPago` (default `true`, se edita en la ficha del alumno): apagado, la cuota se crea igual pero sin link (paga por transferencia).
|
||||||
|
4. Si una cuota de un checkout `OPEN` se paga por otra vía (confirmar transferencia), `supersedeCheckoutsOf` lo pasa a `SUPERSEDED`, borra el link de sus cuotas y expira la preferencia en MP (best effort); renovar una de esas cuotas crea un link individual y la saca del checkout. La reconciliación sigue mirando los `SUPERSEDED` 7 días. Renovar una cuota de un checkout `OPEN` sin link regenera el link **combinado**.
|
||||||
|
5. Con `sendWhatsapp`, los links salen enseguida por WhatsApp (`SendPaymentLinks`, kind `PAYMENT_LINK`, mismo gate que las automatizaciones: Pro + cuenta activa + template aprobado); el recordatorio semanal manda uno por checkout, no uno por chico.
|
||||||
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
||||||
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
|
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.
|
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.
|
||||||
@@ -70,7 +76,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
|
2. Tokens de 32 bytes base64url; **en la base solo el SHA-256**. Invitación 72 h, recuperación 15 min, confirmación de mail 24 h. El **GET del link no consume** (vistas previas de WhatsApp); el POST consume con `updateMany` condicional (`used_at IS NULL AND revoked_at IS NULL AND expires_at > now`) y `count === 1` gana. Todo link inválido responde el mismo `{ status: 'invalid' }` / 410.
|
||||||
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
|
3. **Reinvitar reinicia el acceso**: revoca tokens pendientes y sesiones, **borra las passkeys** y resetea `welcomed_at`.
|
||||||
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
|
4. CSRF: `studentOriginGuard` exige `Origin === WEB_URL` (o `WEBAUTHN_ORIGIN`) en todo POST/PUT/DELETE, además de `SameSite=Lax`.
|
||||||
5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). Vincular tutores a varios hijos (N:N) es solo del lado profe y **todavía no tiene UI**.
|
5. Autorización: todo pasa por `findLinkedAttendee` (attendee cuya **persona** está vinculada a la cuenta y no `DROPPED`); lo ajeno es 404. Los alumnos nunca ven a otros miembros. La cuenta se vincula a la persona (`student_account_people`), no a la membresía: ve todos sus grupos, también los que se sumen después, y es **una cuenta por persona** (invitar desde cualquier grupo la reutiliza). En grupos de chicos la cuenta es del **adulto a cargo** (`person_guardians`): invitar a un chico vincula al adulto (y pasa al adulto una cuenta vieja del chico), y `linkedPersonWhere` le da acceso a todos sus chicos, también a los que se sumen después, sin reinvitar.
|
||||||
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
|
6. "Pedir un link a mi mail": respuesta idéntica exista o no el mail; rate limit en `rate_limit_events` (3 por mail y 10 por IP cada 15 min). La IP sale de `X-Forwarded-For` contando `TRUSTED_PROXY_HOPS` desde el final. El envío corre después de responder, para no filtrar por tiempo.
|
||||||
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
|
7. Avisar falta reutiliza `registerAbsence` (EXCUSED + liberación de cupo); `AbsenceNotice` tiene índice único **parcial** (`cancelled_at IS NULL`, escrito a mano en la migración: Prisma no lo modela). Solo antes del inicio de la clase y solo en ocurrencias reales del grupo, en la zona del profe (`COUNTRY_TIME_ZONES[user.country]`, default `APP_TIMEZONE` = Buenos Aires).
|
||||||
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.
|
8. Pago informado: `Payment.status` **no cambia** hasta que el profe confirma. "Requiere atención" y el recordatorio de WhatsApp excluyen cuotas con un `ReportedPayment` `REPORTED` (`reportedItems: { none: … }`); si se rechaza, vuelven. Confirmar marca `PAID` con `paid_at = reviewed_at`; "Deshacer" (10 min) revierte solo esas filas (sin `mp_payment_id`). El mail al alumno sale 60 s después, solo si la revisión sigue en pie y el mail está confirmado.
|
||||||
|
|||||||
@@ -38,6 +38,11 @@ TOKEN_ENCRYPTION_KEY=""
|
|||||||
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
|
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
|
||||||
MP_PLATFORM_ACCESS_TOKEN_AR=""
|
MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||||
MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||||
|
# Origen público de esta API, adonde MP y Stripe devuelven el navegador después
|
||||||
|
# del checkout de Pro (GET /api/v1/billing/return, que redirige a la web). MP
|
||||||
|
# rechaza localhost: en local poné el túnel (https://TU-DOMINIO.ngrok-free.app).
|
||||||
|
# Vacío = BETTER_AUTH_URL.
|
||||||
|
API_PUBLIC_URL=""
|
||||||
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
|
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
|
||||||
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
|
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
|
||||||
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
|
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PlanId" AS ENUM ('FREE', 'PRO');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "billing_subscriptions" ADD COLUMN "pending_amount" DECIMAL(12,2),
|
||||||
|
ADD COLUMN "price_change_attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN "price_change_error" TEXT,
|
||||||
|
ADD COLUMN "price_change_id" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "plan_configs" (
|
||||||
|
"plan" "PlanId" NOT NULL,
|
||||||
|
"max_groups" INTEGER,
|
||||||
|
"max_attendees" INTEGER,
|
||||||
|
"whatsapp_automations" BOOLEAN NOT NULL,
|
||||||
|
"mp_charges" BOOLEAN NOT NULL,
|
||||||
|
"updated_by_id" TEXT,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "plan_configs_pkey" PRIMARY KEY ("plan")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "plan_prices" (
|
||||||
|
"country_code" TEXT NOT NULL,
|
||||||
|
"amount" DECIMAL(12,2) NOT NULL,
|
||||||
|
"updated_by_id" TEXT,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "plan_prices_pkey" PRIMARY KEY ("country_code")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "plan_price_changes" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"country_code" TEXT NOT NULL,
|
||||||
|
"previous_amount" DECIMAL(12,2),
|
||||||
|
"new_amount" DECIMAL(12,2) NOT NULL,
|
||||||
|
"currency" TEXT NOT NULL,
|
||||||
|
"apply_to_existing" BOOLEAN NOT NULL,
|
||||||
|
"queued" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"created_by_id" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "plan_price_changes_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "plan_price_changes_country_created_at_idx" ON "plan_price_changes"("country_code", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "billing_subscriptions_pending_amount_idx" ON "billing_subscriptions"("pending_amount");
|
||||||
|
|
||||||
|
-- Seed with the defaults that lived in code (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`
|
||||||
|
-- in packages/shared), so nothing changes on deploy.
|
||||||
|
INSERT INTO "plan_configs" ("plan", "max_groups", "max_attendees", "whatsapp_automations", "mp_charges", "updated_at") VALUES
|
||||||
|
('FREE', 1, 15, false, false, CURRENT_TIMESTAMP),
|
||||||
|
('PRO', NULL, NULL, true, true, CURRENT_TIMESTAMP);
|
||||||
|
|
||||||
|
INSERT INTO "plan_prices" ("country_code", "amount", "updated_at") VALUES
|
||||||
|
('AR', 15000, CURRENT_TIMESTAMP),
|
||||||
|
('BR', 49, CURRENT_TIMESTAMP),
|
||||||
|
('CL', 9900, CURRENT_TIMESTAMP),
|
||||||
|
('CO', 39900, CURRENT_TIMESTAMP),
|
||||||
|
('MX', 199, CURRENT_TIMESTAMP),
|
||||||
|
('PE', 39, CURRENT_TIMESTAMP),
|
||||||
|
('UY', 390, CURRENT_TIMESTAMP);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "GroupAudience" AS ENUM ('ADULTS', 'KIDS');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "groups" ADD COLUMN "audience" "GroupAudience" NOT NULL DEFAULT 'ADULTS';
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "plan_configs" ADD COLUMN "kids_groups" BOOLEAN NOT NULL DEFAULT false;
|
||||||
|
|
||||||
|
-- Pro includes kids groups from the start; Free keeps the default (false).
|
||||||
|
UPDATE "plan_configs" SET "kids_groups" = true WHERE "plan" = 'PRO';
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "person_guardians" (
|
||||||
|
"child_id" TEXT NOT NULL,
|
||||||
|
"guardian_id" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "person_guardians_pkey" PRIMARY KEY ("child_id","guardian_id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "person_guardians_guardian_id_idx" ON "person_guardians"("guardian_id");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "person_guardians" ADD CONSTRAINT "person_guardians_child_id_fkey" FOREIGN KEY ("child_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "person_guardians" ADD CONSTRAINT "person_guardians_guardian_id_fkey" FOREIGN KEY ("guardian_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- The old guardian_name / guardian_phone become an adult of their own: an
|
||||||
|
-- existing person of the same teacher with that phone, or a new one (one per
|
||||||
|
-- teacher and phone, so siblings end up sharing it).
|
||||||
|
INSERT INTO "people" ("id", "created_by_id", "full_name", "phone", "created_at", "updated_at")
|
||||||
|
SELECT DISTINCT ON (k."created_by_id", k."guardian_phone")
|
||||||
|
gen_random_uuid()::text,
|
||||||
|
k."created_by_id",
|
||||||
|
COALESCE(NULLIF(TRIM(k."guardian_name"), ''), 'Adulto a cargo'),
|
||||||
|
k."guardian_phone",
|
||||||
|
CURRENT_TIMESTAMP,
|
||||||
|
CURRENT_TIMESTAMP
|
||||||
|
FROM (
|
||||||
|
SELECT "created_by_id", TRIM("guardian_phone") AS "guardian_phone", "guardian_name", "created_at"
|
||||||
|
FROM "people"
|
||||||
|
WHERE NULLIF(TRIM("guardian_phone"), '') IS NOT NULL
|
||||||
|
) k
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM "people" p
|
||||||
|
WHERE p."created_by_id" = k."created_by_id" AND p."phone" = k."guardian_phone"
|
||||||
|
)
|
||||||
|
ORDER BY k."created_by_id", k."guardian_phone", k."created_at";
|
||||||
|
|
||||||
|
INSERT INTO "person_guardians" ("child_id", "guardian_id")
|
||||||
|
SELECT c."id", g."id"
|
||||||
|
FROM "people" c
|
||||||
|
JOIN "people" g
|
||||||
|
ON g."created_by_id" = c."created_by_id"
|
||||||
|
AND g."phone" = TRIM(c."guardian_phone")
|
||||||
|
AND g."id" <> c."id"
|
||||||
|
WHERE NULLIF(TRIM(c."guardian_phone"), '') IS NOT NULL;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "people" DROP COLUMN "guardian_name",
|
||||||
|
DROP COLUMN "guardian_phone";
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PaymentRunStatus" AS ENUM ('RUNNING', 'DONE', 'SKIPPED');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PaymentCheckoutStatus" AS ENUM ('OPEN', 'PAID', 'SUPERSEDED');
|
||||||
|
|
||||||
|
-- AlterEnum
|
||||||
|
ALTER TYPE "WhatsappMessageKind" ADD VALUE 'PAYMENT_LINK';
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "outbound_messages" ADD COLUMN "checkout_id" TEXT;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "payments" ADD COLUMN "checkout_id" TEXT,
|
||||||
|
ADD COLUMN "period_key" TEXT;
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "people" ADD COLUMN "pay_with_mercado_pago" BOOLEAN NOT NULL DEFAULT true;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "auto_charge_settings" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"enabled" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"charge_day" INTEGER NOT NULL DEFAULT 1,
|
||||||
|
"due_in_days" INTEGER NOT NULL DEFAULT 10,
|
||||||
|
"send_whatsapp" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"enabled_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "auto_charge_settings_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "payment_runs" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"period_key" TEXT NOT NULL,
|
||||||
|
"status" "PaymentRunStatus" NOT NULL DEFAULT 'RUNNING',
|
||||||
|
"skip_reason" TEXT,
|
||||||
|
"fees" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"checkouts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"linked" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"failed" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"sent" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"finished_at" TIMESTAMP(3),
|
||||||
|
|
||||||
|
CONSTRAINT "payment_runs_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "payment_checkouts" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"payer_person_id" TEXT NOT NULL,
|
||||||
|
"run_id" TEXT,
|
||||||
|
"amount" DECIMAL(10,2) NOT NULL,
|
||||||
|
"currency" TEXT NOT NULL,
|
||||||
|
"due_date" TIMESTAMP(3) NOT NULL,
|
||||||
|
"checkout_url" TEXT,
|
||||||
|
"mp_preference_id" TEXT,
|
||||||
|
"mp_payment_id" TEXT,
|
||||||
|
"status" "PaymentCheckoutStatus" NOT NULL DEFAULT 'OPEN',
|
||||||
|
"paid_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "payment_checkouts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "auto_charge_settings_owner_id_key" ON "auto_charge_settings"("owner_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "payment_runs_owner_id_period_key_key" ON "payment_runs"("owner_id", "period_key");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "payment_checkouts_mp_preference_id_key" ON "payment_checkouts"("mp_preference_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "payment_checkouts_status_created_at_idx" ON "payment_checkouts"("status", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "payment_checkouts_owner_id_idx" ON "payment_checkouts"("owner_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "payments_checkout_id_idx" ON "payments"("checkout_id");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "payments" ADD CONSTRAINT "payments_checkout_id_fkey" FOREIGN KEY ("checkout_id") REFERENCES "payment_checkouts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "auto_charge_settings" ADD CONSTRAINT "auto_charge_settings_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "payment_runs" ADD CONSTRAINT "payment_runs_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_payer_person_id_fkey" FOREIGN KEY ("payer_person_id") REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "payment_checkouts" ADD CONSTRAINT "payment_checkouts_run_id_fkey" FOREIGN KEY ("run_id") REFERENCES "payment_runs"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "outbound_messages" ADD CONSTRAINT "outbound_messages_checkout_id_fkey" FOREIGN KEY ("checkout_id") REFERENCES "payment_checkouts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- One automatic fee per member and month (hand-written: Prisma does not model
|
||||||
|
-- partial indexes). Manual fees have no period and stay out of it.
|
||||||
|
CREATE UNIQUE INDEX "payments_attendee_period_key" ON "payments"("attendee_id", "period_key") WHERE "period_key" IS NOT NULL;
|
||||||
@@ -31,6 +31,9 @@ model User {
|
|||||||
subscription BillingSubscription?
|
subscription BillingSubscription?
|
||||||
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
|
studentAccounts StudentAccount[] @relation("StudentAccountsCreated")
|
||||||
people Person[] @relation("OwnerPeople")
|
people Person[] @relation("OwnerPeople")
|
||||||
|
autoCharge AutoChargeSettings?
|
||||||
|
paymentRuns PaymentRun[]
|
||||||
|
checkouts PaymentCheckout[]
|
||||||
|
|
||||||
@@map("users")
|
@@map("users")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -39,6 +39,12 @@ model BillingSubscription {
|
|||||||
// period, even after a cancellation or a failed renewal.
|
// period, even after a cancellation or a failed renewal.
|
||||||
paidThrough DateTime? @map("paid_through")
|
paidThrough DateTime? @map("paid_through")
|
||||||
lastSyncedAt DateTime? @map("last_synced_at")
|
lastSyncedAt DateTime? @map("last_synced_at")
|
||||||
|
// A new price queued by the backoffice for this live subscription: the job
|
||||||
|
// pushes it to the provider (from the next charge) and moves it to `amount`.
|
||||||
|
pendingAmount Decimal? @db.Decimal(12, 2) @map("pending_amount")
|
||||||
|
priceChangeId String? @map("price_change_id")
|
||||||
|
priceChangeAttempts Int @default(0) @map("price_change_attempts")
|
||||||
|
priceChangeError String? @map("price_change_error")
|
||||||
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")
|
||||||
|
|
||||||
@@ -47,6 +53,7 @@ model BillingSubscription {
|
|||||||
|
|
||||||
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
|
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
|
||||||
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
|
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
|
||||||
|
@@index([pendingAmount], map: "billing_subscriptions_pending_amount_idx")
|
||||||
@@map("billing_subscriptions")
|
@@map("billing_subscriptions")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,3 +87,53 @@ model BillingWebhookEvent {
|
|||||||
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
|
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
|
||||||
@@map("billing_webhook_events")
|
@@map("billing_webhook_events")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum PlanId {
|
||||||
|
FREE
|
||||||
|
PRO
|
||||||
|
}
|
||||||
|
|
||||||
|
// What each plan allows, edited from the backoffice. Seeded with the defaults
|
||||||
|
// of `PLAN_LIMITS` (shared); a missing row falls back to them. Applies at once.
|
||||||
|
model PlanConfig {
|
||||||
|
plan PlanId @id
|
||||||
|
// Null means no limit.
|
||||||
|
maxGroups Int? @map("max_groups")
|
||||||
|
maxAttendees Int? @map("max_attendees")
|
||||||
|
whatsappAutomations Boolean @map("whatsapp_automations")
|
||||||
|
mpCharges Boolean @map("mp_charges")
|
||||||
|
kidsGroups Boolean @default(false) @map("kids_groups")
|
||||||
|
updatedById String? @map("updated_by_id")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("plan_configs")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Monthly price of Pro per country, in the country's currency. Seeded with
|
||||||
|
// `PRO_PRICE_BY_COUNTRY` (shared). New subscriptions take it; live ones keep
|
||||||
|
// their own `amount` unless a price change is applied to them.
|
||||||
|
model PlanPrice {
|
||||||
|
country String @id @map("country_code")
|
||||||
|
amount Decimal @db.Decimal(12, 2)
|
||||||
|
updatedById String? @map("updated_by_id")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("plan_prices")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audit of every price edit from the backoffice.
|
||||||
|
model PlanPriceChange {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
country String @map("country_code")
|
||||||
|
previousAmount Decimal? @db.Decimal(12, 2) @map("previous_amount")
|
||||||
|
newAmount Decimal @db.Decimal(12, 2) @map("new_amount")
|
||||||
|
currency String
|
||||||
|
applyToExisting Boolean @map("apply_to_existing")
|
||||||
|
// Live subscriptions queued to move to the new price.
|
||||||
|
queued Int @default(0)
|
||||||
|
createdById String? @map("created_by_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
@@index([country, createdAt], map: "plan_price_changes_country_created_at_idx")
|
||||||
|
@@map("plan_price_changes")
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,22 +1,24 @@
|
|||||||
// 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")
|
||||||
// Weekly WhatsApp automations, off until the teacher turns them on.
|
// Weekly WhatsApp automations, off until the teacher turns them on.
|
||||||
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
|
autoPaymentReminders Boolean @default(false) @map("auto_payment_reminders")
|
||||||
autoReengagement Boolean @default(false) @map("auto_reengagement")
|
autoReengagement Boolean @default(false) @map("auto_reengagement")
|
||||||
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
|
// KIDS: each student is a kid and the contact is the adult in charge.
|
||||||
createdById String @map("created_by_id")
|
audience GroupAudience @default(ADULTS)
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
inviteToken String? @unique(map: "groups_inviteToken_key") @map("invite_token")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
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[]
|
||||||
@@ -31,6 +33,11 @@ model Group {
|
|||||||
@@map("groups")
|
@@map("groups")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum GroupAudience {
|
||||||
|
ADULTS
|
||||||
|
KIDS
|
||||||
|
}
|
||||||
|
|
||||||
enum WeekDay {
|
enum WeekDay {
|
||||||
MONDAY
|
MONDAY
|
||||||
TUESDAY
|
TUESDAY
|
||||||
@@ -78,25 +85,48 @@ enum AttendeeStatus {
|
|||||||
// teacher through a hand-written partial index (`people_owner_phone_key`,
|
// teacher through a hand-written partial index (`people_owner_phone_key`,
|
||||||
// `WHERE phone IS NOT NULL`): Prisma does not model it.
|
// `WHERE phone IS NOT NULL`): Prisma does not model it.
|
||||||
model Person {
|
model Person {
|
||||||
id String @id @default(cuid())
|
id String @id @default(cuid())
|
||||||
createdById String @map("created_by_id")
|
createdById String @map("created_by_id")
|
||||||
fullName String @map("full_name")
|
fullName String @map("full_name")
|
||||||
email String?
|
email String?
|
||||||
phone String?
|
phone String?
|
||||||
guardianName String? @map("guardian_name")
|
notes String?
|
||||||
guardianPhone String? @map("guardian_phone")
|
// Automatic monthly charges only build a Mercado Pago link for people with
|
||||||
notes String?
|
// this on. Off: they prefer to transfer (the fee is still created).
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
payWithMercadoPago Boolean @default(true) @map("pay_with_mercado_pago")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
|
owner User @relation("OwnerPeople", fields: [createdById], references: [id], onDelete: Cascade)
|
||||||
attendees Attendee[]
|
attendees Attendee[]
|
||||||
studentAccounts StudentAccountPerson[]
|
studentAccounts StudentAccountPerson[]
|
||||||
|
// As the payer of combined Mercado Pago links (themselves or their kids).
|
||||||
|
checkouts PaymentCheckout[]
|
||||||
|
// As a kid: the adult in charge (one in v1, enforced by the code).
|
||||||
|
guardians PersonGuardian[] @relation("GuardianChild")
|
||||||
|
// As the adult in charge: their kids. An adult has no memberships of their own.
|
||||||
|
children PersonGuardian[] @relation("GuardianAdult")
|
||||||
|
|
||||||
@@index([createdById])
|
@@index([createdById])
|
||||||
@@map("people")
|
@@map("people")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A kid (`child`) and the adult in charge (`guardian`), both people of the same
|
||||||
|
// teacher. The adult is who gets the messages and signs in to the student app;
|
||||||
|
// siblings share the same adult, so their phone is not duplicated on each kid.
|
||||||
|
model PersonGuardian {
|
||||||
|
childId String @map("child_id")
|
||||||
|
guardianId String @map("guardian_id")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
|
||||||
|
child Person @relation("GuardianChild", fields: [childId], references: [id], onDelete: Cascade)
|
||||||
|
guardian Person @relation("GuardianAdult", fields: [guardianId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([childId, guardianId])
|
||||||
|
@@index([guardianId])
|
||||||
|
@@map("person_guardians")
|
||||||
|
}
|
||||||
|
|
||||||
// Membership of a person in a group. Status, attendance, fees and the absence
|
// Membership of a person in a group. Status, attendance, fees and the absence
|
||||||
// link (`notifyToken`) are per group.
|
// link (`notifyToken`) are per group.
|
||||||
model Attendee {
|
model Attendee {
|
||||||
@@ -159,16 +189,25 @@ model Payment {
|
|||||||
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")
|
||||||
|
// Combined link (automatic monthly charges): the fee is paid through it and
|
||||||
|
// `checkoutUrl` is a copy of the checkout's link.
|
||||||
|
checkoutId String? @map("checkout_id")
|
||||||
|
// Month of an automatic charge ("2026-12"). Unique per attendee through a
|
||||||
|
// hand-written partial index (`payments_attendee_period_key`,
|
||||||
|
// `WHERE period_key IS NOT NULL`): Prisma does not model it.
|
||||||
|
periodKey String? @map("period_key")
|
||||||
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")
|
||||||
|
checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull)
|
||||||
outboundMessages OutboundMessage[]
|
outboundMessages OutboundMessage[]
|
||||||
reportedItems ReportedPaymentItem[]
|
reportedItems ReportedPaymentItem[]
|
||||||
|
|
||||||
@@index([groupId], map: "payments_groupId_idx")
|
@@index([groupId], map: "payments_groupId_idx")
|
||||||
@@index([attendeeId], map: "payments_attendeeId_idx")
|
@@index([attendeeId], map: "payments_attendeeId_idx")
|
||||||
|
@@index([checkoutId])
|
||||||
@@map("payments")
|
@@map("payments")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
91
apps/backend/prisma/models/payments.prisma
Normal file
91
apps/backend/prisma/models/payments.prisma
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
// Automatic monthly charges and combined Mercado Pago links.
|
||||||
|
//
|
||||||
|
// On the teacher's day of the month a run creates the fee of every active
|
||||||
|
// member of their monthly groups and one Checkout Pro link per payer: the adult
|
||||||
|
// in charge for kids, the person themselves otherwise. The link covers all the
|
||||||
|
// payer's fees (`PaymentCheckout` + `Payment.checkoutId`); its
|
||||||
|
// `external_reference` is `chk_<checkout id>`.
|
||||||
|
|
||||||
|
// One per teacher. Off until the teacher turns it on.
|
||||||
|
model AutoChargeSettings {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
ownerId String @unique @map("owner_id")
|
||||||
|
enabled Boolean @default(false)
|
||||||
|
// Day of the month (1-28) in the teacher's time zone.
|
||||||
|
chargeDay Int @default(1) @map("charge_day")
|
||||||
|
dueInDays Int @default(10) @map("due_in_days")
|
||||||
|
sendWhatsapp Boolean @default(false) @map("send_whatsapp")
|
||||||
|
// Last time `enabled` went on: a month whose day already passed is skipped.
|
||||||
|
enabledAt DateTime? @map("enabled_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@map("auto_charge_settings")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum PaymentRunStatus {
|
||||||
|
RUNNING
|
||||||
|
DONE
|
||||||
|
SKIPPED
|
||||||
|
}
|
||||||
|
|
||||||
|
// One automatic run per teacher and month: the unique key is what makes a
|
||||||
|
// second tick of the job (or a second server) a no-op.
|
||||||
|
model PaymentRun {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
ownerId String @map("owner_id")
|
||||||
|
periodKey String @map("period_key")
|
||||||
|
status PaymentRunStatus @default(RUNNING)
|
||||||
|
skipReason String? @map("skip_reason")
|
||||||
|
fees Int @default(0)
|
||||||
|
checkouts Int @default(0)
|
||||||
|
linked Int @default(0)
|
||||||
|
failed Int @default(0)
|
||||||
|
sent Int @default(0)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
finishedAt DateTime? @map("finished_at")
|
||||||
|
|
||||||
|
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||||
|
checkoutsList PaymentCheckout[]
|
||||||
|
|
||||||
|
@@unique([ownerId, periodKey])
|
||||||
|
@@map("payment_runs")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum PaymentCheckoutStatus {
|
||||||
|
OPEN
|
||||||
|
PAID
|
||||||
|
// A fee was paid some other way (e.g. a confirmed transfer): the link is
|
||||||
|
// expired and the remaining fees get links of their own.
|
||||||
|
SUPERSEDED
|
||||||
|
}
|
||||||
|
|
||||||
|
// One Mercado Pago link covering several fees of the same payer.
|
||||||
|
model PaymentCheckout {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
ownerId String @map("owner_id")
|
||||||
|
payerPersonId String @map("payer_person_id")
|
||||||
|
runId String? @map("run_id")
|
||||||
|
amount Decimal @db.Decimal(10, 2)
|
||||||
|
currency String
|
||||||
|
dueDate DateTime @map("due_date")
|
||||||
|
checkoutUrl String? @map("checkout_url")
|
||||||
|
mpPreferenceId String? @unique @map("mp_preference_id")
|
||||||
|
mpPaymentId String? @map("mp_payment_id")
|
||||||
|
status PaymentCheckoutStatus @default(OPEN)
|
||||||
|
paidAt DateTime? @map("paid_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
|
||||||
|
payer Person @relation(fields: [payerPersonId], references: [id], onDelete: Cascade)
|
||||||
|
run PaymentRun? @relation(fields: [runId], references: [id], onDelete: SetNull)
|
||||||
|
payments Payment[]
|
||||||
|
outboundMessages OutboundMessage[]
|
||||||
|
|
||||||
|
@@index([status, createdAt])
|
||||||
|
@@index([ownerId])
|
||||||
|
@@map("payment_checkouts")
|
||||||
|
}
|
||||||
@@ -19,6 +19,8 @@ enum WhatsappAccountStatus {
|
|||||||
enum WhatsappMessageKind {
|
enum WhatsappMessageKind {
|
||||||
PAYMENT_REMINDER
|
PAYMENT_REMINDER
|
||||||
REENGAGEMENT
|
REENGAGEMENT
|
||||||
|
// The monthly combined payment link, sent when it is generated.
|
||||||
|
PAYMENT_LINK
|
||||||
}
|
}
|
||||||
|
|
||||||
enum OutboundMessageStatus {
|
enum OutboundMessageStatus {
|
||||||
@@ -92,9 +94,10 @@ model OutboundMessage {
|
|||||||
groupId String @map("group_id")
|
groupId String @map("group_id")
|
||||||
attendeeId String @map("attendee_id")
|
attendeeId String @map("attendee_id")
|
||||||
paymentId String? @map("payment_id")
|
paymentId String? @map("payment_id")
|
||||||
|
checkoutId String? @map("checkout_id")
|
||||||
kind WhatsappMessageKind
|
kind WhatsappMessageKind
|
||||||
provider MessagingProviderId
|
provider MessagingProviderId
|
||||||
// ISO week the job ran for, e.g. "2026-W43".
|
// ISO week the job ran for, e.g. "2026-W43"; the month ("2026-12") for PAYMENT_LINK.
|
||||||
periodKey String @map("period_key")
|
periodKey String @map("period_key")
|
||||||
toPhone String @map("to_phone")
|
toPhone String @map("to_phone")
|
||||||
providerMessageId String? @map("provider_message_id")
|
providerMessageId String? @map("provider_message_id")
|
||||||
@@ -105,9 +108,10 @@ model OutboundMessage {
|
|||||||
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: "outbound_messages_groupId_fkey")
|
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")
|
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")
|
payment Payment? @relation(fields: [paymentId], references: [id], onDelete: SetNull, map: "outbound_messages_paymentId_fkey")
|
||||||
|
checkout PaymentCheckout? @relation(fields: [checkoutId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
|
@@unique([kind, attendeeId, periodKey], map: "outbound_messages_kind_attendeeId_periodKey_key")
|
||||||
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")
|
@@unique([provider, providerMessageId], map: "outbound_messages_provider_providerMessageId_key")
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import { healthCheckRoutes } from './modules/health-check';
|
|||||||
import { homeRoutes } from './modules/home';
|
import { homeRoutes } from './modules/home';
|
||||||
import { invitationsRoutes } from './modules/invitations';
|
import { invitationsRoutes } from './modules/invitations';
|
||||||
import { mpRoutes } from './modules/mp';
|
import { mpRoutes } from './modules/mp';
|
||||||
|
import { mpCallbackOriginMiddleware } from './modules/mp/lib';
|
||||||
import { onboardingRoutes } from './modules/onboarding';
|
import { onboardingRoutes } from './modules/onboarding';
|
||||||
import { paymentsRoutes } from './modules/payments';
|
import { paymentsRoutes } from './modules/payments';
|
||||||
import { peopleRoutes } from './modules/people';
|
import { peopleRoutes } from './modules/people';
|
||||||
@@ -43,6 +44,9 @@ app.get('/', (c) => c.json({ name: 'Gruperly API', status: 'ok' }));
|
|||||||
|
|
||||||
const api = app.basePath('/api/v1');
|
const api = app.basePath('/api/v1');
|
||||||
|
|
||||||
|
// Local development: the MP callback comes back through the tunnel, without the
|
||||||
|
// session cookie of localhost. Replay it there before asking for a session.
|
||||||
|
api.use('/mp/callback', mpCallbackOriginMiddleware);
|
||||||
api.use('*', sessionAuthMiddleware);
|
api.use('*', sessionAuthMiddleware);
|
||||||
|
|
||||||
// Read-only accounts (Free over its limits) cannot write domain data. Billing,
|
// Read-only accounts (Free over its limits) cannot write domain data. Billing,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ProblemDetails } from '@gruperly/shared';
|
import type { PlanFeature, ProblemDetails } from '@gruperly/shared';
|
||||||
import { notFoundProblem } from './problem-details';
|
import { notFoundProblem } from './problem-details';
|
||||||
import { PROBLEM_DOMAIN } from './problem-domain';
|
import { PROBLEM_DOMAIN } from './problem-domain';
|
||||||
|
|
||||||
@@ -248,13 +248,16 @@ export function planLimitReachedProblem(limit: PlanLimitKind, max: number): Prob
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A Pro-only feature: charging students with Mercado Pago or WhatsApp automations. */
|
const PLAN_FEATURE_DETAIL: Record<PlanFeature, string> = {
|
||||||
export function planFeatureRequiredProblem(feature: 'mpCharges' | 'whatsappAutomations'): ProblemDetails {
|
mpCharges: 'Cobrar con Mercado Pago está disponible en el plan Pro.',
|
||||||
|
whatsappAutomations: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
||||||
|
kidsGroups: 'Los grupos de chicos con adulto a cargo están disponibles en el plan Pro.',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A feature the owner's plan does not include (Mercado Pago, WhatsApp automations, kids groups). */
|
||||||
|
export function planFeatureRequiredProblem(feature: PlanFeature): ProblemDetails {
|
||||||
return paymentRequiredProblem({
|
return paymentRequiredProblem({
|
||||||
detail:
|
detail: PLAN_FEATURE_DETAIL[feature],
|
||||||
feature === 'mpCharges'
|
|
||||||
? 'Cobrar con Mercado Pago está disponible en el plan Pro.'
|
|
||||||
: 'Los mensajes automáticos de WhatsApp están disponibles en el plan Pro.',
|
|
||||||
code: 'plan_feature_required',
|
code: 'plan_feature_required',
|
||||||
params: { feature },
|
params: { feature },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -47,6 +47,15 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
|||||||
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
|
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
// Mercado Pago notifications about a Checkout Pro payment: no session; the
|
||||||
|
// owner's Mercado Pago account is asked before anything changes.
|
||||||
|
if (method === 'POST' && /^\/api\/v1\/payments\/webhooks\/mp\/(checkout\/)?[A-Za-z0-9_-]+$/.test(normalizedPath)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Back from the Pro checkout: only redirects to the web, which has the session.
|
||||||
|
if (method === 'GET' && normalizedPath === '/api/v1/billing/return') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
|
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
|
||||||
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
|
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -6,6 +6,15 @@ type PasswordResetEmailData = { email: string; url: string; name?: string }
|
|||||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||||
type StudentEmailConfirmationData = { email: string; url: string; name: string }
|
type StudentEmailConfirmationData = { email: string; url: string; name: string }
|
||||||
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
|
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
|
||||||
|
type ProPriceChangedData = {
|
||||||
|
email: string
|
||||||
|
name: string
|
||||||
|
/** Already formatted in the professor's currency. */
|
||||||
|
amount: string
|
||||||
|
/** Already formatted; `null` when the provider has not scheduled the next charge. */
|
||||||
|
nextPaymentDate: string | null
|
||||||
|
billingUrl: string
|
||||||
|
}
|
||||||
type StudentPaymentReviewedData = {
|
type StudentPaymentReviewedData = {
|
||||||
email: string
|
email: string
|
||||||
name: string
|
name: string
|
||||||
@@ -42,6 +51,7 @@ export interface EmailProvider {
|
|||||||
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
||||||
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
||||||
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
||||||
|
sendProPriceChanged(data: ProPriceChangedData): Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
// Names come from what teachers and students type: never raw into the HTML.
|
// Names come from what teachers and students type: never raw into the HTML.
|
||||||
@@ -176,6 +186,20 @@ class SMTPEmailProvider implements EmailProvider {
|
|||||||
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
|
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async sendProPriceChanged({ email, name, amount, nextPaymentDate, billingUrl }: ProPriceChangedData) {
|
||||||
|
const when = nextPaymentDate
|
||||||
|
? `desde tu próximo cobro, el ${escapeHtml(nextPaymentDate)}`
|
||||||
|
: 'desde tu próximo cobro'
|
||||||
|
await this.send(
|
||||||
|
email,
|
||||||
|
'Cambia el precio de Gruperly Pro',
|
||||||
|
this.layout(
|
||||||
|
'Nuevo precio de Gruperly Pro',
|
||||||
|
`Hola ${escapeHtml(name)}, te avisamos que el precio de tu suscripción a Gruperly Pro pasa a ser de ${escapeHtml(amount)} por mes ${when}. Lo que ya pagaste no cambia.<br/><br/>Si no querés seguir, podés cancelar la suscripción cuando quieras y vas a seguir con Pro hasta el final del período pago.<br/><br/>${button(billingUrl, 'Ver mi plan')}`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||||
|
|||||||
17
apps/backend/src/lib/public-origin.ts
Normal file
17
apps/backend/src/lib/public-origin.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
const DEFAULT_API_ORIGIN = 'http://localhost:4000';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public origin of this API, as the billing providers reach it. Mercado Pago
|
||||||
|
* refuses a non-public `back_url` and `notification_url` (localhost), so in local development it is the
|
||||||
|
* ngrok tunnel. Falls back to `BETTER_AUTH_URL`, which is the API's base URL
|
||||||
|
* (in production the same origin as the web, since nginx proxies `/api`).
|
||||||
|
*/
|
||||||
|
export function getApiPublicOrigin(env: Record<string, string | undefined> = process.env): string {
|
||||||
|
const configured = env.API_PUBLIC_URL?.trim() || env.BETTER_AUTH_URL?.trim();
|
||||||
|
if (!configured) return DEFAULT_API_ORIGIN;
|
||||||
|
try {
|
||||||
|
return new URL(configured).origin;
|
||||||
|
} catch {
|
||||||
|
return DEFAULT_API_ORIGIN;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
|
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib';
|
import {
|
||||||
|
exceedsLimits,
|
||||||
|
getGraceDays,
|
||||||
|
isBillingEnforced,
|
||||||
|
type PlanCatalogReader,
|
||||||
|
planCatalog,
|
||||||
|
toBillingChargeDto,
|
||||||
|
} from '@/modules/billing/lib';
|
||||||
import { accountPlan, toAccountListItem } from '../../lib';
|
import { accountPlan, toAccountListItem } from '../../lib';
|
||||||
|
|
||||||
const RECENT_CHARGES = 12;
|
const RECENT_CHARGES = 12;
|
||||||
@@ -13,6 +20,7 @@ type GetAccountDeps = {
|
|||||||
enforced?: boolean;
|
enforced?: boolean;
|
||||||
graceDays?: number;
|
graceDays?: number;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** One professor's account: plan, links, groups and the latest Pro charges. */
|
/** One professor's account: plan, links, groups and the latest Pro charges. */
|
||||||
@@ -65,18 +73,16 @@ export class GetAccount {
|
|||||||
const { graceUntil } = accountPlan(user, context);
|
const { graceUntil } = accountPlan(user, context);
|
||||||
const enforced = this.deps.enforced ?? isBillingEnforced();
|
const enforced = this.deps.enforced ?? isBillingEnforced();
|
||||||
const subscription = user.subscription;
|
const subscription = user.subscription;
|
||||||
|
// Same rule as the PlanGuard: an account without a plan is held to Free.
|
||||||
|
const limits = await (this.deps.catalog ?? planCatalog).getLimits(summary.plan ?? 'FREE');
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
...summary,
|
...summary,
|
||||||
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
|
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
|
||||||
graceUntil: graceUntil?.toISOString() ?? null,
|
graceUntil: graceUntil?.toISOString() ?? null,
|
||||||
// Same rule as the PlanGuard: an account without a plan is held to Free.
|
|
||||||
readOnly:
|
readOnly:
|
||||||
enforced
|
enforced && exceedsLimits(limits, { groups: usage.groupsCount, attendees: usage.attendeesCount }),
|
||||||
&& exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], {
|
limits,
|
||||||
groups: usage.groupsCount,
|
|
||||||
attendees: usage.attendeesCount,
|
|
||||||
}),
|
|
||||||
subscription:
|
subscription:
|
||||||
summary.subscription && subscription
|
summary.subscription && subscription
|
||||||
? {
|
? {
|
||||||
|
|||||||
12
apps/backend/src/modules/admin/features/get-plans/route.ts
Normal file
12
apps/backend/src/modules/admin/features/get-plans/route.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { GetPlans } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/plans', async (c) => {
|
||||||
|
const result = await new GetPlans().execute();
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { AdminPlansDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { billingProviderForCountry, COUNTRY_CURRENCY, countryCodeSchema, ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { MAX_PRICE_CHANGE_ATTEMPTS } from '@/modules/billing/jobs';
|
||||||
|
import { type PlanCatalogReader, planCatalog } from '@/modules/billing/lib';
|
||||||
|
|
||||||
|
/** The subscriptions "apply to existing" moves: live, with a provider subscription. */
|
||||||
|
export const LIVE_SUBSCRIPTION_STATUSES = ['AUTHORIZED', 'PAUSED'] as const;
|
||||||
|
|
||||||
|
type GetPlansDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'planPrice' | 'billingSubscription'>;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Limits of both plans and, per country, the price of Pro and how it reached live subscriptions. */
|
||||||
|
export class GetPlans {
|
||||||
|
constructor(private readonly deps: GetPlansDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(): Promise<Result<AdminPlansDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const catalog = await (this.deps.catalog ?? planCatalog).snapshot();
|
||||||
|
|
||||||
|
const [priceRows, live] = await Promise.all([
|
||||||
|
db.planPrice.findMany({ select: { country: true, updatedAt: true } }),
|
||||||
|
db.billingSubscription.findMany({
|
||||||
|
where: { status: { in: [...LIVE_SUBSCRIPTION_STATUSES] }, externalId: { not: null } },
|
||||||
|
select: { country: true, amount: true, pendingAmount: true, priceChangeAttempts: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const updatedAt = new Map(priceRows.map((row) => [row.country, row.updatedAt]));
|
||||||
|
|
||||||
|
const prices = countryCodeSchema.options.map((country) => {
|
||||||
|
const amount = catalog.proPrices[country];
|
||||||
|
const rows = live.filter((row) => row.country === country);
|
||||||
|
const queued = rows.filter((row) => row.pendingAmount !== null);
|
||||||
|
const failed = queued.filter((row) => row.priceChangeAttempts >= MAX_PRICE_CHANGE_ATTEMPTS);
|
||||||
|
return {
|
||||||
|
country,
|
||||||
|
amount,
|
||||||
|
currency: COUNTRY_CURRENCY[country],
|
||||||
|
provider: billingProviderForCountry(country),
|
||||||
|
updatedAt: updatedAt.get(country)?.toISOString() ?? null,
|
||||||
|
liveSubscriptions: rows.length,
|
||||||
|
atOtherPrice: rows.filter(
|
||||||
|
(row) => Number((row.pendingAmount ?? row.amount).toString()) !== amount,
|
||||||
|
).length,
|
||||||
|
pendingChanges: queued.length - failed.length,
|
||||||
|
failedChanges: failed.length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ limits: catalog.limits, prices });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import type { PlanLimitsImpactQuery } from '@gruperly/shared';
|
||||||
|
import { PlanLimitsImpactQuerySchema, planSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { PlanLimitsImpact } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/plans/:plan/impact',
|
||||||
|
validate.param(z.object({ plan: planSchema })),
|
||||||
|
validate.query(PlanLimitsImpactQuerySchema),
|
||||||
|
async (c) => {
|
||||||
|
const { plan } = c.req.valid('param');
|
||||||
|
const query = c.req.valid('query') as PlanLimitsImpactQuery;
|
||||||
|
const result = await new PlanLimitsImpact().execute(plan, query);
|
||||||
|
return resultJson(c, result);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { Plan, PlanLimitsImpactDto, PlanLimitsImpactQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { getGraceDays, proSubscriptionWhere } from '@/modules/billing/lib';
|
||||||
|
|
||||||
|
type PlanLimitsImpactDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'person' | 'user'>;
|
||||||
|
graceDays?: number;
|
||||||
|
now?: () => Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many accounts on a plan would exceed new limits, i.e. become read only
|
||||||
|
* as soon as they are saved (limits apply at once). Usage is the PlanGuard's:
|
||||||
|
* groups owned, and people with at least one ACTIVE membership.
|
||||||
|
*/
|
||||||
|
export class PlanLimitsImpact {
|
||||||
|
constructor(private readonly deps: PlanLimitsImpactDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(plan: Plan, query: PlanLimitsImpactQuery): Promise<Result<PlanLimitsImpactDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now?.() ?? new Date();
|
||||||
|
const graceDays = this.deps.graceDays ?? getGraceDays();
|
||||||
|
|
||||||
|
const [overGroups, overAttendees] = await Promise.all([
|
||||||
|
query.maxGroups === null
|
||||||
|
? []
|
||||||
|
: db.group.groupBy({
|
||||||
|
by: ['createdById'],
|
||||||
|
having: { id: { _count: { gt: query.maxGroups } } },
|
||||||
|
}),
|
||||||
|
query.maxAttendees === null
|
||||||
|
? []
|
||||||
|
: db.person.groupBy({
|
||||||
|
by: ['createdById'],
|
||||||
|
where: { attendees: { some: { status: 'ACTIVE' } } },
|
||||||
|
having: { id: { _count: { gt: query.maxAttendees } } },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const candidates = [...new Set([...overGroups, ...overAttendees].map((row) => row.createdById))];
|
||||||
|
if (candidates.length === 0) return ok({ affectedAccounts: 0 });
|
||||||
|
|
||||||
|
// Same split as the PlanGuard: anyone without a live Pro is held to Free.
|
||||||
|
const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } };
|
||||||
|
const affectedAccounts = await db.user.count({
|
||||||
|
where: { id: { in: candidates }, ...(plan === 'PRO' ? isPro : { NOT: isPro }) },
|
||||||
|
});
|
||||||
|
return ok({ affectedAccounts });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { UpdatePlanLimitsInput } from '@gruperly/shared';
|
||||||
|
import { planSchema, UpdatePlanLimitsInputSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { UpdatePlanLimits } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/plans/:plan/limits',
|
||||||
|
validate.param(z.object({ plan: planSchema })),
|
||||||
|
validate.json(UpdatePlanLimitsInputSchema),
|
||||||
|
async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const { plan } = c.req.valid('param');
|
||||||
|
const input = c.req.valid('json') as UpdatePlanLimitsInput;
|
||||||
|
const result = await new UpdatePlanLimits().execute(plan, input, user.id);
|
||||||
|
return resultJson(c, result);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { Plan, PlanLimits, ProblemDetails, Result, UpdatePlanLimitsInput } from '@gruperly/shared';
|
||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
|
||||||
|
|
||||||
|
type UpdatePlanLimitsDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'planConfig'>;
|
||||||
|
catalog?: Pick<PlanCatalog, 'invalidate'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** New limits for a plan. They apply at once to every account on it. */
|
||||||
|
export class UpdatePlanLimits {
|
||||||
|
constructor(private readonly deps: UpdatePlanLimitsDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
plan: Plan,
|
||||||
|
input: UpdatePlanLimitsInput,
|
||||||
|
adminId: string,
|
||||||
|
): Promise<Result<PlanLimits, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const data = { ...input, updatedById: adminId };
|
||||||
|
await db.planConfig.upsert({ where: { plan }, create: { plan, ...data }, update: data });
|
||||||
|
(this.deps.catalog ?? planCatalog).invalidate();
|
||||||
|
logger.info({ plan, adminId, limits: input }, 'Plan limits updated');
|
||||||
|
return ok(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { UpdatePlanPriceInput } from '@gruperly/shared';
|
||||||
|
import { countryCodeSchema, UpdatePlanPriceInputSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { runPriceChanges } from '@/modules/billing/jobs';
|
||||||
|
import { UpdatePlanPrice } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/plans/prices/:country',
|
||||||
|
validate.param(z.object({ country: countryCodeSchema })),
|
||||||
|
validate.json(UpdatePlanPriceInputSchema),
|
||||||
|
async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const { country } = c.req.valid('param');
|
||||||
|
const input = c.req.valid('json') as UpdatePlanPriceInput;
|
||||||
|
const result = await new UpdatePlanPrice({ applyQueued: runPriceChanges }).execute(country, input, user.id);
|
||||||
|
return resultJson(c, result);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { CountryCode, ProblemDetails, Result, UpdatePlanPriceInput, UpdatePlanPriceResultDto } from '@gruperly/shared';
|
||||||
|
import { COUNTRY_CURRENCY, ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
|
||||||
|
import { LIVE_SUBSCRIPTION_STATUSES } from '../get-plans/use-case';
|
||||||
|
|
||||||
|
type UpdatePlanPriceDeps = {
|
||||||
|
db?: Pick<PrismaClient, '$transaction'>;
|
||||||
|
catalog?: Pick<PlanCatalog, 'invalidate' | 'getProPrice'>;
|
||||||
|
/** Kicks the job that pushes queued prices to the providers. */
|
||||||
|
applyQueued?: () => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* New monthly price of Pro in a country. New subscriptions take it right away.
|
||||||
|
* With `applyToExisting`, the country's live subscriptions are queued to move
|
||||||
|
* to it (`pending_amount`); the job tells each provider to charge it from the
|
||||||
|
* next charge on, and emails the professor.
|
||||||
|
*
|
||||||
|
* PENDING subscriptions are left alone: a checkout half done keeps its amount,
|
||||||
|
* and trying again starts a new one at the new price.
|
||||||
|
*/
|
||||||
|
export class UpdatePlanPrice {
|
||||||
|
constructor(private readonly deps: UpdatePlanPriceDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
country: CountryCode,
|
||||||
|
input: UpdatePlanPriceInput,
|
||||||
|
adminId: string,
|
||||||
|
): Promise<Result<UpdatePlanPriceResultDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const catalog = this.deps.catalog ?? planCatalog;
|
||||||
|
catalog.invalidate();
|
||||||
|
const previousAmount = await catalog.getProPrice(country);
|
||||||
|
const currency = COUNTRY_CURRENCY[country];
|
||||||
|
|
||||||
|
const queued = await db.$transaction(async (tx) => {
|
||||||
|
await tx.planPrice.upsert({
|
||||||
|
where: { country },
|
||||||
|
create: { country, amount: input.amount, updatedById: adminId },
|
||||||
|
update: { amount: input.amount, updatedById: adminId },
|
||||||
|
});
|
||||||
|
const change = await tx.planPriceChange.create({
|
||||||
|
data: {
|
||||||
|
country,
|
||||||
|
previousAmount,
|
||||||
|
newAmount: input.amount,
|
||||||
|
currency,
|
||||||
|
applyToExisting: input.applyToExisting,
|
||||||
|
createdById: adminId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!input.applyToExisting) return 0;
|
||||||
|
|
||||||
|
// Rows already at the new price (or already moving to it) are not touched.
|
||||||
|
const moved = await tx.billingSubscription.updateMany({
|
||||||
|
where: {
|
||||||
|
country,
|
||||||
|
status: { in: [...LIVE_SUBSCRIPTION_STATUSES] },
|
||||||
|
externalId: { not: null },
|
||||||
|
OR: [
|
||||||
|
{ pendingAmount: null, amount: { not: input.amount } },
|
||||||
|
{ pendingAmount: { not: null, notIn: [input.amount] } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
pendingAmount: input.amount,
|
||||||
|
priceChangeId: change.id,
|
||||||
|
priceChangeAttempts: 0,
|
||||||
|
priceChangeError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.planPriceChange.update({ where: { id: change.id }, data: { queued: moved.count } });
|
||||||
|
return moved.count;
|
||||||
|
});
|
||||||
|
|
||||||
|
catalog.invalidate();
|
||||||
|
logger.info({ country, adminId, amount: input.amount, queued }, 'Pro price updated');
|
||||||
|
|
||||||
|
if (queued > 0 && this.deps.applyQueued) {
|
||||||
|
// In the background: the providers are slow, and the cron retries anyway.
|
||||||
|
void this.deps.applyQueued();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({ country, amount: input.amount, queued });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import getAccountRoute from './features/get-account/route';
|
import getAccountRoute from './features/get-account/route';
|
||||||
|
import getPlansRoute from './features/get-plans/route';
|
||||||
import listAccountsRoute from './features/list-accounts/route';
|
import listAccountsRoute from './features/list-accounts/route';
|
||||||
import meRoute from './features/me/route';
|
import meRoute from './features/me/route';
|
||||||
|
import planLimitsImpactRoute from './features/plan-limits-impact/route';
|
||||||
|
import updatePlanLimitsRoute from './features/update-plan-limits/route';
|
||||||
|
import updatePlanPriceRoute from './features/update-plan-price/route';
|
||||||
import { adminOnlyMiddleware } from './lib';
|
import { adminOnlyMiddleware } from './lib';
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
@@ -11,7 +15,13 @@ routes.route('/', meRoute);
|
|||||||
// Everything below `/me` is the backoffice itself.
|
// Everything below `/me` is the backoffice itself.
|
||||||
routes.use('/accounts', adminOnlyMiddleware());
|
routes.use('/accounts', adminOnlyMiddleware());
|
||||||
routes.use('/accounts/*', adminOnlyMiddleware());
|
routes.use('/accounts/*', adminOnlyMiddleware());
|
||||||
|
routes.use('/plans', adminOnlyMiddleware());
|
||||||
|
routes.use('/plans/*', adminOnlyMiddleware());
|
||||||
routes.route('/', listAccountsRoute);
|
routes.route('/', listAccountsRoute);
|
||||||
routes.route('/', getAccountRoute);
|
routes.route('/', getAccountRoute);
|
||||||
|
routes.route('/', getPlansRoute);
|
||||||
|
routes.route('/', planLimitsImpactRoute);
|
||||||
|
routes.route('/', updatePlanLimitsRoute);
|
||||||
|
routes.route('/', updatePlanPriceRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
import { ok, summarizeMemberAttendance } from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||||
|
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
||||||
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
import { type AnalyticsAccessDb, findGroupForUser } from '../../lib/access';
|
||||||
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
import { toMemberAttendance, toRiskLevel } from '../../lib/member-attendance';
|
||||||
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
import { lastAttendedAt, monthlyAttendanceRate } from '../../lib/risk';
|
||||||
@@ -74,7 +75,7 @@ export async function findStudentsAtRisk(
|
|||||||
}),
|
}),
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
where: { groupId, status: 'ACTIVE' },
|
where: { groupId, status: 'ACTIVE' },
|
||||||
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true } } },
|
select: { id: true, createdAt: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } },
|
||||||
}).then((rows) => rows.map(flattenPerson)),
|
}).then((rows) => rows.map(flattenPerson)),
|
||||||
db.attendance.findMany({
|
db.attendance.findMany({
|
||||||
where: { attendee: { groupId } },
|
where: { attendee: { groupId } },
|
||||||
@@ -111,7 +112,8 @@ export async function findStudentsAtRisk(
|
|||||||
atRisk.push({
|
atRisk.push({
|
||||||
attendeeId: attendee.id,
|
attendeeId: attendee.id,
|
||||||
fullName: attendee.fullName,
|
fullName: attendee.fullName,
|
||||||
phone: attendee.phone,
|
// The number to reach them on: the adult in charge for a kid.
|
||||||
|
phone: contactPhone(attendee),
|
||||||
riskLevel,
|
riskLevel,
|
||||||
consecutiveAbsences,
|
consecutiveAbsences,
|
||||||
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
|
lastAttendedAt: attendedAt ? attendedAt.toISOString() : null,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { CreateAttendee, CreateAttendeeResult, ProblemDetails, Result } from '@gruperly/shared';
|
import type { CreateAttendee, CreateAttendeeResult, GuardianInput, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
alreadyWaitlistedProblem,
|
alreadyWaitlistedProblem,
|
||||||
@@ -11,9 +11,13 @@ import prisma from '@/lib/prisma';
|
|||||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
import {
|
import {
|
||||||
alreadyInGroupProblem,
|
alreadyInGroupProblem,
|
||||||
|
contactPhone,
|
||||||
findPersonByPhone,
|
findPersonByPhone,
|
||||||
|
guardianRequiredProblem,
|
||||||
|
guardianSelect,
|
||||||
isUniqueViolation,
|
isUniqueViolation,
|
||||||
personExistsProblem,
|
personExistsProblem,
|
||||||
|
type WithGuardians,
|
||||||
} from '@/modules/people/lib/people';
|
} from '@/modules/people/lib/people';
|
||||||
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||||
|
|
||||||
@@ -54,27 +58,51 @@ export class CreateAttendeeUseCase {
|
|||||||
return err(noGroupAccessProblem());
|
return err(noGroupAccessProblem());
|
||||||
}
|
}
|
||||||
|
|
||||||
const phone = normalizePhone(payload.phone);
|
const isKidsGroup = group.audience === 'KIDS';
|
||||||
|
if (isKidsGroup && !payload.personId && !payload.guardian) {
|
||||||
|
return err(guardianRequiredProblem());
|
||||||
|
}
|
||||||
|
// A kid may have no phone of their own: the adult in charge is the contact.
|
||||||
|
const phone = payload.phone ? normalizePhone(payload.phone) : null;
|
||||||
|
|
||||||
/* The person: the one the form picked (`personId`, after the "ya existe"
|
/* The person: the one the form picked (`personId`, after the "ya existe"
|
||||||
hint) or a new one. A phone the teacher already has is never duplicated. */
|
hint) or a new one. A phone the teacher already has is never duplicated. */
|
||||||
let person: { id: string; fullName: string } | null = null;
|
let person: ({ id: string; fullName: string; phone: string | null } & WithGuardians) | null = null;
|
||||||
|
// Kids groups: the adult in charge, already one of the teacher's people or new.
|
||||||
|
let guardian: { id: string } | null = null;
|
||||||
if (payload.personId) {
|
if (payload.personId) {
|
||||||
person = await db.person.findFirst({
|
person = await db.person.findFirst({
|
||||||
where: { id: payload.personId, createdById: group.createdById },
|
where: { id: payload.personId, createdById: group.createdById },
|
||||||
select: { id: true, fullName: true },
|
select: { id: true, fullName: true, phone: true, ...guardianSelect },
|
||||||
});
|
});
|
||||||
if (!person) {
|
if (!person) {
|
||||||
return err(notFoundResourceProblem('Person', payload.personId));
|
return err(notFoundResourceProblem('Person', payload.personId));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
|
if (payload.phone) {
|
||||||
if (samePhone) {
|
// The raw phone: its variants also match older rows stored as typed.
|
||||||
return err(
|
const samePhone = await findPersonByPhone(db, group.createdById, payload.phone);
|
||||||
samePhone.attendees.some((membership) => membership.groupId === groupId)
|
if (samePhone) {
|
||||||
? alreadyInGroupProblem()
|
return err(
|
||||||
: personExistsProblem(),
|
samePhone.attendees.some((membership) => membership.groupId === groupId)
|
||||||
);
|
? alreadyInGroupProblem()
|
||||||
|
: personExistsProblem(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (payload.guardian) {
|
||||||
|
guardian = await findPersonByPhone(db, group.createdById, payload.guardian.phone);
|
||||||
|
// The same kid of the same adult (same name) is that kid, not a twin.
|
||||||
|
if (guardian) {
|
||||||
|
person = await db.person.findFirst({
|
||||||
|
where: {
|
||||||
|
createdById: group.createdById,
|
||||||
|
fullName: { equals: kidFullName(payload), mode: 'insensitive' },
|
||||||
|
guardians: { some: { guardianId: guardian.id } },
|
||||||
|
},
|
||||||
|
select: { id: true, fullName: true, phone: true, ...guardianSelect },
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,7 +114,12 @@ export class CreateAttendeeUseCase {
|
|||||||
return err(alreadyInGroupProblem());
|
return err(alreadyInGroupProblem());
|
||||||
}
|
}
|
||||||
|
|
||||||
const fullName = person?.fullName ?? `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
const fullName = person?.fullName ?? kidFullName(payload);
|
||||||
|
// Who the waitlist row (and later the messages) reaches.
|
||||||
|
const reachPhone =
|
||||||
|
(person ? contactPhone(person) : null) ??
|
||||||
|
phone ??
|
||||||
|
(payload.guardian ? normalizePhone(payload.guardian.phone) : null);
|
||||||
|
|
||||||
if (group.capacity !== null) {
|
if (group.capacity !== null) {
|
||||||
const currentCount = await db.attendee.count({
|
const currentCount = await db.attendee.count({
|
||||||
@@ -99,9 +132,9 @@ export class CreateAttendeeUseCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!isOwner) {
|
if (!isOwner) {
|
||||||
const existingWaitlistEntry = await db.groupWaitlistEntry.findFirst({
|
const existingWaitlistEntry = reachPhone
|
||||||
where: { groupId, phone },
|
? await db.groupWaitlistEntry.findFirst({ where: { groupId, phone: reachPhone } })
|
||||||
});
|
: null;
|
||||||
|
|
||||||
if (existingWaitlistEntry) {
|
if (existingWaitlistEntry) {
|
||||||
return err(alreadyWaitlistedProblem());
|
return err(alreadyWaitlistedProblem());
|
||||||
@@ -111,7 +144,7 @@ export class CreateAttendeeUseCase {
|
|||||||
data: {
|
data: {
|
||||||
groupId,
|
groupId,
|
||||||
fullName,
|
fullName,
|
||||||
phone,
|
phone: reachPhone ?? '',
|
||||||
email: payload.email?.trim() || null,
|
email: payload.email?.trim() || null,
|
||||||
notes: payload.notes?.trim() || null,
|
notes: payload.notes?.trim() || null,
|
||||||
},
|
},
|
||||||
@@ -157,6 +190,7 @@ export class CreateAttendeeUseCase {
|
|||||||
phone,
|
phone,
|
||||||
email: payload.email?.trim() || null,
|
email: payload.email?.trim() || null,
|
||||||
notes: payload.notes?.trim() || null,
|
notes: payload.notes?.trim() || null,
|
||||||
|
...(payload.guardian ? { guardians: { create: guardianLink(group.createdById, payload.guardian, guardian) } } : {}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -173,3 +207,24 @@ export class CreateAttendeeUseCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function kidFullName(payload: CreateAttendee): string {
|
||||||
|
return `${payload.firstName.trim()} ${payload.lastName.trim()}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Nested create of the kid's link to the adult in charge: the existing adult,
|
||||||
|
or a new person with the adult's data. */
|
||||||
|
function guardianLink(ownerId: string, input: GuardianInput, existing: { id: string } | null) {
|
||||||
|
return {
|
||||||
|
guardian: existing
|
||||||
|
? { connect: { id: existing.id } }
|
||||||
|
: {
|
||||||
|
create: {
|
||||||
|
createdById: ownerId,
|
||||||
|
fullName: input.fullName.trim(),
|
||||||
|
phone: normalizePhone(input.phone),
|
||||||
|
email: input.email?.trim() || null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,11 +4,11 @@ import { err, ok } from '@gruperly/shared';
|
|||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
import { personMembershipsSelect, toMemberships } from '@/modules/people/lib/people';
|
import { personMembershipsSelect, primaryGuardian, toMemberships } from '@/modules/people/lib/people';
|
||||||
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
|
import { personContactSelect, toAttendeeDetailDto } from '../../lib/helpers';
|
||||||
|
|
||||||
type GetAttendeeDeps = {
|
type GetAttendeeDeps = {
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'personGuardian'>;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -48,11 +48,21 @@ export class GetAttendee {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { attendees: memberships, ...person } = attendee.person;
|
const { attendees: memberships, ...person } = attendee.person;
|
||||||
|
// The other kids of the same adult in charge.
|
||||||
|
const guardian = primaryGuardian(person);
|
||||||
|
const siblings = guardian
|
||||||
|
? await db.personGuardian.findMany({
|
||||||
|
where: { guardianId: guardian.id, childId: { not: person.id } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { child: { select: { id: true, fullName: true } } },
|
||||||
|
})
|
||||||
|
: [];
|
||||||
return ok(
|
return ok(
|
||||||
toAttendeeDetailDto({
|
toAttendeeDetailDto({
|
||||||
...attendee,
|
...attendee,
|
||||||
person,
|
person,
|
||||||
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
|
otherGroups: toMemberships(memberships.filter((membership) => membership.id !== attendee.id)),
|
||||||
|
siblings: siblings.map(({ child }) => ({ personId: child.id, fullName: child.fullName })),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { GuardianInput } from '@gruperly/shared';
|
||||||
|
import { GuardianInputSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { UpdateAttendeeGuardian } from './use-case';
|
||||||
|
|
||||||
|
/** `PATCH /groups/:groupId/attendees/:attendeeId/guardian`. */
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.patch('/:groupId/attendees/:attendeeId/guardian', validate.json(GuardianInputSchema), async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
|
||||||
|
const result = await new UpdateAttendeeGuardian().execute({
|
||||||
|
groupId: c.req.param('groupId'),
|
||||||
|
attendeeId: c.req.param('attendeeId'),
|
||||||
|
userId: user.id,
|
||||||
|
input: c.req.valid('json') as GuardianInput,
|
||||||
|
});
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { AttendeeDto, GuardianInput, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
|
import {
|
||||||
|
findOrCreateGuardian,
|
||||||
|
guardianSelect,
|
||||||
|
isUniqueViolation,
|
||||||
|
personPhoneTakenProblem,
|
||||||
|
primaryGuardian,
|
||||||
|
} from '@/modules/people/lib/people';
|
||||||
|
import { attendeeWithPerson, normalizePhone, toAttendeeDto } from '../../lib/helpers';
|
||||||
|
|
||||||
|
type UpdateGuardianDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'person' | 'personGuardian'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type UpdateGuardianCommand = {
|
||||||
|
groupId: string;
|
||||||
|
attendeeId: string;
|
||||||
|
userId: string;
|
||||||
|
input: GuardianInput;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The adult in charge of a kid, from the kid's page. With an adult already
|
||||||
|
* linked it edits that adult (a person of their own, so it shows on every
|
||||||
|
* sibling); without one it links the adult with that phone, or a new one.
|
||||||
|
*/
|
||||||
|
export class UpdateAttendeeGuardian {
|
||||||
|
constructor(private readonly deps: UpdateGuardianDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(command: UpdateGuardianCommand): Promise<Result<AttendeeDto, ProblemDetails>> {
|
||||||
|
const { groupId, attendeeId, userId, input } = command;
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
|
if (!access.ok) return access;
|
||||||
|
|
||||||
|
const attendee = await db.attendee.findFirst({
|
||||||
|
where: { id: attendeeId, groupId },
|
||||||
|
select: { personId: true, person: { select: { id: true, phone: true, ...guardianSelect } } },
|
||||||
|
});
|
||||||
|
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
|
||||||
|
const current = primaryGuardian(attendee.person);
|
||||||
|
try {
|
||||||
|
if (current) {
|
||||||
|
await db.person.update({
|
||||||
|
where: { id: current.id },
|
||||||
|
data: {
|
||||||
|
fullName: input.fullName.trim(),
|
||||||
|
phone: normalizePhone(input.phone),
|
||||||
|
email: input.email?.trim() || null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const guardian = await findOrCreateGuardian(db, access.value.createdById, input);
|
||||||
|
// The kid's own phone is not an adult in charge of themselves.
|
||||||
|
if (guardian.id === attendee.personId) return err(personPhoneTakenProblem());
|
||||||
|
await db.personGuardian.create({ data: { childId: attendee.personId, guardianId: guardian.id } });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (isUniqueViolation(error)) return err(personPhoneTakenProblem());
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await db.attendee.findUniqueOrThrow({
|
||||||
|
where: { id: attendeeId },
|
||||||
|
include: attendeeWithPerson,
|
||||||
|
});
|
||||||
|
return ok(toAttendeeDto(updated));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
import type { AttendeeDetailDto, AttendeeDto, AttendeeListItem } from '@gruperly/shared';
|
||||||
|
import { type GuardianContact, guardianSelect, primaryGuardian } from '@/modules/people/lib/guardians';
|
||||||
|
|
||||||
/* Contact data of the person behind an attendee (shared by all their groups). */
|
/* Contact data of the person behind an attendee (shared by all their groups). */
|
||||||
export const personContactSelect = {
|
export const personContactSelect = {
|
||||||
@@ -6,9 +7,9 @@ export const personContactSelect = {
|
|||||||
fullName: true,
|
fullName: true,
|
||||||
email: true,
|
email: true,
|
||||||
phone: true,
|
phone: true,
|
||||||
guardianName: true,
|
|
||||||
guardianPhone: true,
|
|
||||||
notes: true,
|
notes: true,
|
||||||
|
payWithMercadoPago: true,
|
||||||
|
...guardianSelect,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
|
/* `include` for any attendee query that ends up in `toAttendeeDto`. */
|
||||||
@@ -19,9 +20,9 @@ export type PersonContactRecord = {
|
|||||||
fullName: string;
|
fullName: string;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
guardianName: string | null;
|
|
||||||
guardianPhone: string | null;
|
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
|
payWithMercadoPago?: boolean;
|
||||||
|
guardians?: { guardian: GuardianContact }[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AttendeeRecord = {
|
export type AttendeeRecord = {
|
||||||
@@ -46,8 +47,20 @@ export type AttendeeListItemRecord = AttendeeRecord & {
|
|||||||
export type AttendeeDetailRecord = AttendeeRecord & {
|
export type AttendeeDetailRecord = AttendeeRecord & {
|
||||||
payments: AttendeeListItemRecord['payments'];
|
payments: AttendeeListItemRecord['payments'];
|
||||||
otherGroups: AttendeeDetailDto['otherGroups'];
|
otherGroups: AttendeeDetailDto['otherGroups'];
|
||||||
|
siblings?: AttendeeDetailDto['siblings'];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* The adult in charge, flattened into the attendee DTO (all null when none). */
|
||||||
|
export function guardianFields(person: { guardians?: { guardian: GuardianContact }[] }) {
|
||||||
|
const guardian = primaryGuardian(person);
|
||||||
|
return {
|
||||||
|
guardianPersonId: guardian?.id ?? null,
|
||||||
|
guardianName: guardian?.fullName ?? null,
|
||||||
|
guardianPhone: guardian?.phone ?? null,
|
||||||
|
guardianEmail: guardian?.email ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
||||||
return {
|
return {
|
||||||
id: record.id,
|
id: record.id,
|
||||||
@@ -56,9 +69,9 @@ export function toAttendeeDto(record: AttendeeRecord): AttendeeDto {
|
|||||||
fullName: record.person.fullName,
|
fullName: record.person.fullName,
|
||||||
email: record.person.email,
|
email: record.person.email,
|
||||||
phone: record.person.phone,
|
phone: record.person.phone,
|
||||||
guardianName: record.person.guardianName,
|
...guardianFields(record.person),
|
||||||
guardianPhone: record.person.guardianPhone,
|
|
||||||
notes: record.person.notes,
|
notes: record.person.notes,
|
||||||
|
payWithMercadoPago: record.person.payWithMercadoPago ?? true,
|
||||||
notifyToken: record.notifyToken ?? null,
|
notifyToken: record.notifyToken ?? null,
|
||||||
createdAt: record.createdAt.toISOString(),
|
createdAt: record.createdAt.toISOString(),
|
||||||
updatedAt: record.updatedAt.toISOString(),
|
updatedAt: record.updatedAt.toISOString(),
|
||||||
@@ -91,6 +104,7 @@ export function toAttendeeDetailDto(record: AttendeeDetailRecord): AttendeeDetai
|
|||||||
...toAttendeeDto(record),
|
...toAttendeeDto(record),
|
||||||
payment: pickRelevantPayment(record.payments),
|
payment: pickRelevantPayment(record.payments),
|
||||||
otherGroups: record.otherGroups,
|
otherGroups: record.otherGroups,
|
||||||
|
siblings: record.siblings ?? [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import prisma from '@/lib/prisma';
|
|||||||
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
|
import { toMemberAttendance } from '@/modules/analytics/lib/member-attendance';
|
||||||
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
import { flattenPerson } from '@/modules/attendees/lib/helpers';
|
||||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||||
import { contactPhone } from '@/modules/people/lib/people';
|
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
||||||
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
import { ALERT_KIND_TO_TYPE } from '../../lib/alert-kind';
|
||||||
|
|
||||||
type GetAttentionOverviewDeps = {
|
type GetAttentionOverviewDeps = {
|
||||||
@@ -35,7 +35,7 @@ type AttendeeRow = {
|
|||||||
groupId: string;
|
groupId: string;
|
||||||
fullName: string;
|
fullName: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
guardianPhone: string | null;
|
guardians?: { guardian: { phone: string | null } }[];
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
};
|
};
|
||||||
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
type SessionRow = { id: string; groupId: string; startsAt: Date };
|
||||||
@@ -88,7 +88,7 @@ export class GetAttentionOverview {
|
|||||||
id: true,
|
id: true,
|
||||||
groupId: true,
|
groupId: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
person: { select: { fullName: true, phone: true, ...guardianSelect } },
|
||||||
},
|
},
|
||||||
orderBy: { createdAt: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
}).then((rows): AttendeeRow[] => rows.map(flattenPerson)),
|
||||||
|
|||||||
16
apps/backend/src/modules/billing/features/plans/route.ts
Normal file
16
apps/backend/src/modules/billing/features/plans/route.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { planCatalog, toPlanCatalogDto } from '../../lib';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What each plan allows and what Pro costs in every country. The onboarding
|
||||||
|
* asks before the professor's country is stored, so it gets all of them.
|
||||||
|
*/
|
||||||
|
route.get('/plans', async (c) => {
|
||||||
|
return resultJson(c, ok(toPlanCatalogDto(await planCatalog.snapshot())));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
19
apps/backend/src/modules/billing/features/return/route.ts
Normal file
19
apps/backend/src/modules/billing/features/return/route.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { billingReturnToSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { getWebOrigin } from '@/modules/mp/lib';
|
||||||
|
import { buildSubscriptionReturnUrl } from '../../lib';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `back_url` of the Pro checkout (Mercado Pago and Stripe). Public: the
|
||||||
|
* browser comes from the provider, maybe through a tunnel without the session
|
||||||
|
* cookie. It only redirects to a fixed page of the web, so whatever the
|
||||||
|
* provider appends to the query is dropped and nothing can steer the redirect.
|
||||||
|
*/
|
||||||
|
route.get('/return', (c) => {
|
||||||
|
const parsed = billingReturnToSchema.safeParse(c.req.query('to'));
|
||||||
|
return c.redirect(buildSubscriptionReturnUrl(getWebOrigin(), parsed.success ? parsed.data : 'billing'));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
|
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
|
||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { countryOf, PlanGuard, SyncSubscription } from '../../lib';
|
import { countryOf, type PlanCatalogReader, PlanGuard, planCatalog, SyncSubscription } from '../../lib';
|
||||||
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
|
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
|
||||||
|
|
||||||
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
|
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
|
||||||
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
|
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
|
||||||
|
|
||||||
type GetBillingStatusDeps = {
|
type GetBillingStatusDeps = {
|
||||||
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
db?: Pick<PrismaClient, 'user' | 'billingSubscription' | 'billingCharge'>;
|
||||||
guard?: PlanGuard;
|
guard?: PlanGuard;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
sync?: Pick<SyncSubscription, 'execute'>;
|
sync?: Pick<SyncSubscription, 'execute'>;
|
||||||
providers?: BillingProviderResolver;
|
providers?: BillingProviderResolver;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
@@ -54,6 +55,24 @@ export class GetBillingStatus {
|
|||||||
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
|
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const priceAmount = live
|
||||||
|
? Number(live.amount.toString())
|
||||||
|
: await (this.deps.catalog ?? planCatalog).getProPrice(country);
|
||||||
|
|
||||||
|
// A price change from the backoffice applies from the next charge: show it
|
||||||
|
// while it is queued, and after it reached the provider until it is charged.
|
||||||
|
let nextPriceAmount: number | null = null;
|
||||||
|
if (live?.pendingAmount) {
|
||||||
|
nextPriceAmount = Number(live.pendingAmount.toString());
|
||||||
|
} else if (live?.status === 'AUTHORIZED') {
|
||||||
|
const lastCharge = await db.billingCharge.findFirst({
|
||||||
|
where: { subscriptionId: live.id, status: 'approved' },
|
||||||
|
orderBy: { paidAt: 'desc' },
|
||||||
|
select: { amount: true },
|
||||||
|
});
|
||||||
|
if (lastCharge && Number(lastCharge.amount.toString()) !== priceAmount) nextPriceAmount = priceAmount;
|
||||||
|
}
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
plan: entitlements.plan,
|
plan: entitlements.plan,
|
||||||
status: subscription?.status ?? null,
|
status: subscription?.status ?? null,
|
||||||
@@ -65,7 +84,8 @@ export class GetBillingStatus {
|
|||||||
? (subscription.nextPaymentDate?.toISOString() ?? null)
|
? (subscription.nextPaymentDate?.toISOString() ?? null)
|
||||||
: null,
|
: null,
|
||||||
payerEmail: subscription?.payerEmail ?? null,
|
payerEmail: subscription?.payerEmail ?? null,
|
||||||
priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country],
|
priceAmount,
|
||||||
|
nextPriceAmount,
|
||||||
currency: live ? live.currency : COUNTRY_CURRENCY[country],
|
currency: live ? live.currency : COUNTRY_CURRENCY[country],
|
||||||
country,
|
country,
|
||||||
provider: provider.id,
|
provider: provider.id,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
|
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
|
||||||
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
|
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
billingNotAvailableProblem,
|
billingNotAvailableProblem,
|
||||||
notFoundResourceProblem,
|
notFoundResourceProblem,
|
||||||
@@ -9,15 +9,20 @@ import {
|
|||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { getWebOrigin } from '@/modules/mp/lib';
|
import {
|
||||||
import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
|
buildSubscriptionBackUrl,
|
||||||
|
countryOf,
|
||||||
|
getApiPublicOrigin,
|
||||||
|
type PlanCatalogReader, planCatalog, subscriptionRefOf } from '../../lib';
|
||||||
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
|
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
|
||||||
|
|
||||||
type SubscribeDeps = {
|
type SubscribeDeps = {
|
||||||
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
||||||
providers?: BillingProviderResolver;
|
providers?: BillingProviderResolver;
|
||||||
webOrigin?: string;
|
/** Public origin of the API, where the provider sends the browser back. */
|
||||||
|
apiOrigin?: string;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,7 +65,7 @@ export class Subscribe {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const amount = PRO_PRICE_BY_COUNTRY[country];
|
const amount = await (this.deps.catalog ?? planCatalog).getProPrice(country);
|
||||||
const currency = COUNTRY_CURRENCY[country];
|
const currency = COUNTRY_CURRENCY[country];
|
||||||
const fields = {
|
const fields = {
|
||||||
country,
|
country,
|
||||||
@@ -82,6 +87,10 @@ export class Subscribe {
|
|||||||
checkoutRef: null,
|
checkoutRef: null,
|
||||||
authorizedAt: null,
|
authorizedAt: null,
|
||||||
nextPaymentDate: null,
|
nextPaymentDate: null,
|
||||||
|
pendingAmount: null,
|
||||||
|
priceChangeId: null,
|
||||||
|
priceChangeAttempts: 0,
|
||||||
|
priceChangeError: null,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -97,7 +106,7 @@ export class Subscribe {
|
|||||||
amount,
|
amount,
|
||||||
currency,
|
currency,
|
||||||
payerEmail: input.payerEmail ?? null,
|
payerEmail: input.payerEmail ?? null,
|
||||||
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
|
backUrl: buildSubscriptionBackUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), input.returnTo),
|
||||||
startDate,
|
startDate,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
117
apps/backend/src/modules/billing/jobs/apply-price-changes.ts
Normal file
117
apps/backend/src/modules/billing/jobs/apply-price-changes.ts
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { COUNTRY_TIME_ZONES } from '@gruperly/shared';
|
||||||
|
import type { EmailProvider } from '@/lib/email';
|
||||||
|
import { emailProvider } from '@/lib/email';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { getWebOrigin } from '@/modules/mp/lib';
|
||||||
|
import { formatAmount } from '@/modules/whatsapp/lib/format';
|
||||||
|
import { countryOf } from '../lib';
|
||||||
|
import {
|
||||||
|
BillingProviderNotConfigured,
|
||||||
|
type BillingProviderResolver,
|
||||||
|
getBillingProvider,
|
||||||
|
} from '../providers';
|
||||||
|
|
||||||
|
const BATCH_SIZE = 20;
|
||||||
|
/** After this many refusals the change stays visible as failed in the backoffice. */
|
||||||
|
export const MAX_PRICE_CHANGE_ATTEMPTS = 5;
|
||||||
|
|
||||||
|
type ApplyPriceChangesDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'billingSubscription'>;
|
||||||
|
providers?: BillingProviderResolver;
|
||||||
|
email?: Pick<EmailProvider, 'sendProPriceChanged'>;
|
||||||
|
webOrigin?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ApplyPriceChangesTotals = { applied: number; failed: number; dropped: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pushes the prices the backoffice queued (`pending_amount`) to each live
|
||||||
|
* subscription's provider, from its next charge on, and tells the professor.
|
||||||
|
*
|
||||||
|
* The provider call is idempotent (it sets an amount), so two instances racing
|
||||||
|
* over a row are harmless: only the one whose conditional update moves
|
||||||
|
* `pending_amount` into `amount` sends the email.
|
||||||
|
*/
|
||||||
|
export class ApplyPriceChanges {
|
||||||
|
constructor(private readonly deps: ApplyPriceChangesDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(): Promise<ApplyPriceChangesTotals> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const providers = this.deps.providers ?? getBillingProvider;
|
||||||
|
const totals: ApplyPriceChangesTotals = { applied: 0, failed: 0, dropped: 0 };
|
||||||
|
|
||||||
|
const rows = await db.billingSubscription.findMany({
|
||||||
|
where: { pendingAmount: { not: null }, priceChangeAttempts: { lt: MAX_PRICE_CHANGE_ATTEMPTS } },
|
||||||
|
include: { user: { select: { name: true, email: true, country: true } } },
|
||||||
|
orderBy: { updatedAt: 'asc' },
|
||||||
|
take: BATCH_SIZE,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const pendingAmount = row.pendingAmount;
|
||||||
|
if (!pendingAmount) continue;
|
||||||
|
const unchanged = { id: row.id, pendingAmount };
|
||||||
|
|
||||||
|
// Cancelled (or never completed) meanwhile: nothing left to reprice.
|
||||||
|
if (row.status === 'CANCELLED' || row.status === 'PENDING' || !row.externalId) {
|
||||||
|
await db.billingSubscription.updateMany({
|
||||||
|
where: unchanged,
|
||||||
|
data: { pendingAmount: null, priceChangeId: null, priceChangeAttempts: 0, priceChangeError: null },
|
||||||
|
});
|
||||||
|
totals.dropped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const amount = Number(pendingAmount.toString());
|
||||||
|
const country = countryOf({ country: row.country });
|
||||||
|
try {
|
||||||
|
await providers(row.provider).updateAmount(
|
||||||
|
{ country, externalId: row.externalId, checkoutRef: row.checkoutRef },
|
||||||
|
amount,
|
||||||
|
row.currency,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
// Never the provider's message: it can echo what we sent.
|
||||||
|
const reason = error instanceof BillingProviderNotConfigured ? 'not_configured' : 'provider_error';
|
||||||
|
logger.warn({ subscriptionId: row.id, provider: row.provider, reason }, 'Could not apply a Pro price change');
|
||||||
|
await db.billingSubscription.updateMany({
|
||||||
|
where: unchanged,
|
||||||
|
data: { priceChangeAttempts: { increment: 1 }, priceChangeError: reason },
|
||||||
|
});
|
||||||
|
totals.failed += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const moved = await db.billingSubscription.updateMany({
|
||||||
|
where: unchanged,
|
||||||
|
data: { amount: pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null },
|
||||||
|
});
|
||||||
|
if (moved.count !== 1) continue;
|
||||||
|
totals.applied += 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await (this.deps.email ?? emailProvider).sendProPriceChanged({
|
||||||
|
email: row.user.email,
|
||||||
|
name: row.user.name,
|
||||||
|
amount: formatAmount(amount, row.currency, country),
|
||||||
|
nextPaymentDate: row.nextPaymentDate
|
||||||
|
? new Intl.DateTimeFormat('es-AR', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
year: 'numeric',
|
||||||
|
timeZone: COUNTRY_TIME_ZONES[country],
|
||||||
|
}).format(row.nextPaymentDate)
|
||||||
|
: null,
|
||||||
|
billingUrl: `${this.deps.webOrigin ?? getWebOrigin()}/billing`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// The price already changed; a lost email is not worth a retry loop.
|
||||||
|
logger.warn({ err: error, subscriptionId: row.id }, 'Could not email a Pro price change');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return totals;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
|
export { ApplyPriceChanges, type ApplyPriceChangesTotals, MAX_PRICE_CHANGE_ATTEMPTS } from './apply-price-changes';
|
||||||
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
|
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
|
||||||
export { startBillingJobs } from './schedule';
|
export { runPriceChanges, startBillingJobs } from './schedule';
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
|
import { ApplyPriceChanges } from './apply-price-changes';
|
||||||
import { ReconcileSubscriptions } from './reconcile-subscriptions';
|
import { ReconcileSubscriptions } from './reconcile-subscriptions';
|
||||||
|
|
||||||
const RECONCILE_CRON = '*/30 * * * *';
|
const RECONCILE_CRON = '*/30 * * * *';
|
||||||
|
const PRICE_CHANGES_CRON = '*/5 * * * *';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Registers the billing background jobs. Called once from `server.ts`, with the
|
* Registers the billing background jobs. Called once from `server.ts`, with the
|
||||||
@@ -21,4 +23,27 @@ export function startBillingJobs(): void {
|
|||||||
},
|
},
|
||||||
{ tz: 'UTC' },
|
{ tz: 'UTC' },
|
||||||
).unref();
|
).unref();
|
||||||
|
|
||||||
|
Bun.cron(
|
||||||
|
PRICE_CHANGES_CRON,
|
||||||
|
async () => {
|
||||||
|
await runPriceChanges();
|
||||||
|
},
|
||||||
|
{ tz: 'UTC' },
|
||||||
|
).unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies the Pro price changes queued by the backoffice. Also called right
|
||||||
|
* after a save, so the change does not wait for the next tick. Never throws.
|
||||||
|
*/
|
||||||
|
export async function runPriceChanges(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const totals = await new ApplyPriceChanges().execute();
|
||||||
|
if (totals.applied + totals.failed + totals.dropped > 0) {
|
||||||
|
logger.info(totals, 'Pro price changes applied');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error }, 'Applying Pro price changes failed');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
109
apps/backend/src/modules/billing/lib/catalog.ts
Normal file
109
apps/backend/src/modules/billing/lib/catalog.ts
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { CountryCode, Plan, PlanCatalogDto, PlanLimits } from '@gruperly/shared';
|
||||||
|
import { COUNTRY_CURRENCY, countryCodeSchema, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
|
||||||
|
/** Limits and prices are read often (every plan guard) and edited rarely. */
|
||||||
|
const CACHE_TTL_MS = 30 * 1000;
|
||||||
|
|
||||||
|
export type PlanCatalogSnapshot = {
|
||||||
|
limits: Record<Plan, PlanLimits>;
|
||||||
|
/** Monthly price of Pro, in the currency of each country. */
|
||||||
|
proPrices: Record<CountryCode, number>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function defaultPlanCatalog(): PlanCatalogSnapshot {
|
||||||
|
return {
|
||||||
|
limits: { FREE: { ...PLAN_LIMITS.FREE }, PRO: { ...PLAN_LIMITS.PRO } },
|
||||||
|
proPrices: { ...PRO_PRICE_BY_COUNTRY },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type PlanCatalogDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'planConfig' | 'planPrice'>;
|
||||||
|
ttlMs?: number;
|
||||||
|
now?: () => number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What each plan allows and what Pro costs, as edited from the backoffice
|
||||||
|
* (`plan_configs`, `plan_prices`). A missing row falls back to the defaults in
|
||||||
|
* shared (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`), which also seed the tables.
|
||||||
|
*
|
||||||
|
* Cached in memory for a few seconds; the backoffice invalidates it on save, so
|
||||||
|
* the instance that saved sees the change at once and the others within the TTL.
|
||||||
|
*/
|
||||||
|
export class PlanCatalog {
|
||||||
|
private cached: { snapshot: PlanCatalogSnapshot; at: number } | null = null;
|
||||||
|
|
||||||
|
constructor(private readonly deps: PlanCatalogDeps = {}) {}
|
||||||
|
|
||||||
|
invalidate(): void {
|
||||||
|
this.cached = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async snapshot(): Promise<PlanCatalogSnapshot> {
|
||||||
|
const now = this.deps.now?.() ?? Date.now();
|
||||||
|
const ttl = this.deps.ttlMs ?? CACHE_TTL_MS;
|
||||||
|
if (this.cached && now - this.cached.at < ttl) return this.cached.snapshot;
|
||||||
|
|
||||||
|
const snapshot = defaultPlanCatalog();
|
||||||
|
try {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const [configs, prices] = await Promise.all([db.planConfig.findMany(), db.planPrice.findMany()]);
|
||||||
|
for (const config of configs) {
|
||||||
|
snapshot.limits[config.plan] = {
|
||||||
|
maxGroups: config.maxGroups,
|
||||||
|
maxAttendees: config.maxAttendees,
|
||||||
|
whatsappAutomations: config.whatsappAutomations,
|
||||||
|
mpCharges: config.mpCharges,
|
||||||
|
kidsGroups: config.kidsGroups,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for (const price of prices) {
|
||||||
|
const country = countryCodeSchema.safeParse(price.country);
|
||||||
|
if (country.success) snapshot.proPrices[country.data] = Number(price.amount.toString());
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// The defaults keep the guards working; not cached, so the next call retries.
|
||||||
|
logger.warn({ err: error }, 'Could not read the plan catalog, using the defaults');
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cached = { snapshot, at: now };
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLimits(plan: Plan): Promise<PlanLimits> {
|
||||||
|
return (await this.snapshot()).limits[plan];
|
||||||
|
}
|
||||||
|
|
||||||
|
async getProPrice(country: CountryCode): Promise<number> {
|
||||||
|
return (await this.snapshot()).proPrices[country];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The catalog every use-case shares, so an invalidation reaches all of them. */
|
||||||
|
export const planCatalog = new PlanCatalog();
|
||||||
|
|
||||||
|
/** A fixed catalog, for tests and callers that already hold a snapshot. */
|
||||||
|
export function staticPlanCatalog(snapshot: PlanCatalogSnapshot = defaultPlanCatalog()): PlanCatalogReader {
|
||||||
|
return {
|
||||||
|
snapshot: async () => snapshot,
|
||||||
|
getLimits: async (plan) => snapshot.limits[plan],
|
||||||
|
getProPrice: async (country) => snapshot.proPrices[country],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PlanCatalogReader = Pick<PlanCatalog, 'snapshot' | 'getLimits' | 'getProPrice'>;
|
||||||
|
|
||||||
|
export function toPlanCatalogDto(snapshot: PlanCatalogSnapshot): PlanCatalogDto {
|
||||||
|
const proPrices = Object.fromEntries(
|
||||||
|
countryCodeSchema.options.map((country) => [
|
||||||
|
country,
|
||||||
|
{ amount: snapshot.proPrices[country], currency: COUNTRY_CURRENCY[country] },
|
||||||
|
]),
|
||||||
|
) as PlanCatalogDto['proPrices'];
|
||||||
|
return { limits: snapshot.limits, proPrices };
|
||||||
|
}
|
||||||
@@ -14,3 +14,5 @@ export function getGraceDays(env: Record<string, string | undefined> = process.e
|
|||||||
const value = Number(env.BILLING_GRACE_DAYS);
|
const value = Number(env.BILLING_GRACE_DAYS);
|
||||||
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
|
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export { getApiPublicOrigin } from '@/lib/public-origin';
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
||||||
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
|
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
planFeatureRequiredProblem,
|
planFeatureRequiredProblem,
|
||||||
planLimitReachedProblem,
|
planLimitReachedProblem,
|
||||||
planReadOnlyProblem,
|
planReadOnlyProblem,
|
||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { type PlanCatalogReader, planCatalog } from './catalog';
|
||||||
import { getGraceDays, isBillingEnforced } from './config';
|
import { getGraceDays, isBillingEnforced } from './config';
|
||||||
|
|
||||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
@@ -90,6 +91,7 @@ type PlanGuardDeps = {
|
|||||||
enforced?: boolean;
|
enforced?: boolean;
|
||||||
graceDays?: number;
|
graceDays?: number;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -123,7 +125,7 @@ export class PlanGuard {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
||||||
const limits = PLAN_LIMITS[resolution.plan];
|
const limits = await (this.deps.catalog ?? planCatalog).getLimits(resolution.plan);
|
||||||
const usage = { groups, attendees };
|
const usage = { groups, attendees };
|
||||||
const enforced = this.enforced;
|
const enforced = this.enforced;
|
||||||
|
|
||||||
|
|||||||
@@ -19,8 +19,18 @@ export function countryOf(user: { country: string | null } | null): CountryCode
|
|||||||
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
|
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Where the billing provider sends the professor after authorizing (or abandoning). */
|
/**
|
||||||
export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string {
|
* Where the billing provider sends the professor after authorizing (or
|
||||||
|
* abandoning): a public API route that bounces to the web
|
||||||
|
* (`GET /billing/return`), because Mercado Pago refuses a `back_url` on
|
||||||
|
* localhost and the web is not tunneled in local development.
|
||||||
|
*/
|
||||||
|
export function buildSubscriptionBackUrl(apiOrigin: string, returnTo: BillingReturnTo): string {
|
||||||
|
return `${apiOrigin}/api/v1/billing/return?to=${returnTo}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The web page the professor lands on after the provider's checkout. */
|
||||||
|
export function buildSubscriptionReturnUrl(webOrigin: string, returnTo: BillingReturnTo): string {
|
||||||
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
|
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
export { getGraceDays, isBillingEnforced } from './config';
|
export {
|
||||||
|
defaultPlanCatalog,
|
||||||
|
PlanCatalog,
|
||||||
|
type PlanCatalogReader,
|
||||||
|
type PlanCatalogSnapshot,
|
||||||
|
planCatalog,
|
||||||
|
staticPlanCatalog,
|
||||||
|
toPlanCatalogDto,
|
||||||
|
} from './catalog';
|
||||||
|
export { getApiPublicOrigin, getGraceDays, isBillingEnforced } from './config';
|
||||||
export {
|
export {
|
||||||
type Entitlements,
|
type Entitlements,
|
||||||
exceedsLimits,
|
exceedsLimits,
|
||||||
@@ -9,5 +18,5 @@ export {
|
|||||||
resolvePlan,
|
resolvePlan,
|
||||||
type SubscriptionSnapshot,
|
type SubscriptionSnapshot,
|
||||||
} from './entitlements';
|
} from './entitlements';
|
||||||
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
|
export { buildSubscriptionBackUrl, buildSubscriptionReturnUrl, countryOf, toBillingChargeDto } from './helpers';
|
||||||
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';
|
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';
|
||||||
|
|||||||
@@ -105,6 +105,8 @@ export interface BillingProvider {
|
|||||||
/** `null` while the professor has not completed the checkout. */
|
/** `null` while the professor has not completed the checkout. */
|
||||||
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
|
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
|
||||||
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
|
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
|
||||||
|
/** New monthly amount from the next charge on; what was already charged stays. */
|
||||||
|
updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void>;
|
||||||
/** Stops the monthly charge, or voids a checkout never completed. */
|
/** Stops the monthly charge, or voids a checkout never completed. */
|
||||||
cancel(ref: SubscriptionRef): Promise<void>;
|
cancel(ref: SubscriptionRef): Promise<void>;
|
||||||
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;
|
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;
|
||||||
|
|||||||
@@ -137,6 +137,13 @@ export class MercadoPagoBillingProvider implements BillingProvider {
|
|||||||
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
|
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
|
||||||
|
await this.client.updatePreapprovalAmount(this.tokenFor(ref.country), ref.externalId, {
|
||||||
|
amount,
|
||||||
|
currencyId: currency,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One URL per country, because each country is a different Gruperly account
|
* One URL per country, because each country is a different Gruperly account
|
||||||
* with its own secret. Mercado Pago signs a manifest of the notified id, the
|
* with its own secret. Mercado Pago signs a manifest of the notified id, the
|
||||||
|
|||||||
@@ -129,6 +129,23 @@ export async function cancelPreapproval(accessToken: string, id: string): Promis
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Changes the monthly amount of a live preapproval. Mercado Pago applies it to
|
||||||
|
* the debits that follow; the ones already made are untouched.
|
||||||
|
*/
|
||||||
|
export async function updatePreapprovalAmount(
|
||||||
|
accessToken: string,
|
||||||
|
id: string,
|
||||||
|
input: { amount: number; currencyId: string },
|
||||||
|
): Promise<MpPreapproval> {
|
||||||
|
return toPreapproval(
|
||||||
|
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: { auto_recurring: { transaction_amount: input.amount, currency_id: input.currencyId } },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
|
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
|
||||||
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
|
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
|
||||||
return {
|
return {
|
||||||
@@ -181,6 +198,7 @@ export type PreapprovalClient = {
|
|||||||
createPreapproval: typeof createPreapproval;
|
createPreapproval: typeof createPreapproval;
|
||||||
getPreapproval: typeof getPreapproval;
|
getPreapproval: typeof getPreapproval;
|
||||||
cancelPreapproval: typeof cancelPreapproval;
|
cancelPreapproval: typeof cancelPreapproval;
|
||||||
|
updatePreapprovalAmount: typeof updatePreapprovalAmount;
|
||||||
getAuthorizedPayment: typeof getAuthorizedPayment;
|
getAuthorizedPayment: typeof getAuthorizedPayment;
|
||||||
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
||||||
};
|
};
|
||||||
@@ -189,6 +207,7 @@ export const mpPreapprovalClient: PreapprovalClient = {
|
|||||||
createPreapproval,
|
createPreapproval,
|
||||||
getPreapproval,
|
getPreapproval,
|
||||||
cancelPreapproval,
|
cancelPreapproval,
|
||||||
|
updatePreapprovalAmount,
|
||||||
getAuthorizedPayment,
|
getAuthorizedPayment,
|
||||||
searchAuthorizedPayments,
|
searchAuthorizedPayments,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -214,6 +214,39 @@ export class StripeBillingProvider implements BillingProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the subscription to a new monthly amount from its next invoice on:
|
||||||
|
* the item gets a new inline price on the same product, without proration,
|
||||||
|
* so the period already paid is not touched.
|
||||||
|
*/
|
||||||
|
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
|
||||||
|
const request = this.request;
|
||||||
|
const path = `/subscriptions/${encodeURIComponent(ref.externalId)}`;
|
||||||
|
const subscription = await request(path);
|
||||||
|
const item = objectOf((objectOf(subscription.items)?.data as unknown[] | undefined)?.[0]);
|
||||||
|
const itemId = idOf(item?.id);
|
||||||
|
const product = idOf(objectOf(item?.price)?.product);
|
||||||
|
if (!itemId || !product) throw new Error('Stripe subscription came back without its item');
|
||||||
|
|
||||||
|
await request(path, {
|
||||||
|
method: 'POST',
|
||||||
|
form: {
|
||||||
|
proration_behavior: 'none',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: itemId,
|
||||||
|
price_data: {
|
||||||
|
currency: currency.toLowerCase(),
|
||||||
|
unit_amount: toStripeUnitAmount(amount, currency),
|
||||||
|
recurring: { interval: 'month' },
|
||||||
|
product,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** A single endpoint for the whole account; the event id is the dedupe key. */
|
/** A single endpoint for the whole account; the event id is the dedupe key. */
|
||||||
async parseWebhook(
|
async parseWebhook(
|
||||||
request: BillingWebhookRequest,
|
request: BillingWebhookRequest,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import cancelRoute from './features/cancel/route';
|
import cancelRoute from './features/cancel/route';
|
||||||
import chargesRoute from './features/charges/route';
|
import chargesRoute from './features/charges/route';
|
||||||
|
import plansRoute from './features/plans/route';
|
||||||
|
import returnRoute from './features/return/route';
|
||||||
import statusRoute from './features/status/route';
|
import statusRoute from './features/status/route';
|
||||||
import subscribeRoute from './features/subscribe/route';
|
import subscribeRoute from './features/subscribe/route';
|
||||||
import webhookRoute from './features/webhook/route';
|
import webhookRoute from './features/webhook/route';
|
||||||
@@ -11,6 +13,8 @@ routes.route('/', statusRoute);
|
|||||||
routes.route('/', subscribeRoute);
|
routes.route('/', subscribeRoute);
|
||||||
routes.route('/', cancelRoute);
|
routes.route('/', cancelRoute);
|
||||||
routes.route('/', chargesRoute);
|
routes.route('/', chargesRoute);
|
||||||
|
routes.route('/', plansRoute);
|
||||||
|
routes.route('/', returnRoute);
|
||||||
routes.route('/', webhookRoute);
|
routes.route('/', webhookRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { type GroupRecord, toGroupDto } from '../../lib';
|
|||||||
|
|
||||||
type CreateGroupDeps = {
|
type CreateGroupDeps = {
|
||||||
unitOfWork?: UnitOfWork;
|
unitOfWork?: UnitOfWork;
|
||||||
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class CreateGroup {
|
export class CreateGroup {
|
||||||
@@ -25,10 +25,15 @@ export class CreateGroup {
|
|||||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||||
|
|
||||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
|
const planGuard = this.deps.planGuard ?? new PlanGuard();
|
||||||
|
const allowed = await planGuard.canCreateGroup(userId);
|
||||||
if (!allowed.ok) {
|
if (!allowed.ok) {
|
||||||
return allowed;
|
return allowed;
|
||||||
}
|
}
|
||||||
|
if (data.audience === 'KIDS') {
|
||||||
|
const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups');
|
||||||
|
if (!kidsAllowed.ok) return kidsAllowed;
|
||||||
|
}
|
||||||
|
|
||||||
const transaction = unitOfWork.executeResult(
|
const transaction = unitOfWork.executeResult(
|
||||||
async (tx: Prisma.TransactionClient) => {
|
async (tx: Prisma.TransactionClient) => {
|
||||||
@@ -42,6 +47,7 @@ export class CreateGroup {
|
|||||||
price: data.price,
|
price: data.price,
|
||||||
billingType: data.billingType,
|
billingType: data.billingType,
|
||||||
dueDay: data.dueDay,
|
dueDay: data.dueDay,
|
||||||
|
audience: data.audience,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
20
apps/backend/src/modules/groups/features/update/route.ts
Normal file
20
apps/backend/src/modules/groups/features/update/route.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import type { UpdateGroup } from '@gruperly/shared';
|
||||||
|
import { UpdateGroupSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { UpdateGroupUseCase } from './use-case';
|
||||||
|
|
||||||
|
/** `PATCH /groups/:groupId` ("Editar grupo"). */
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.patch('/:groupId', validate.json(UpdateGroupSchema), async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
|
||||||
|
const input = c.req.valid('json') as UpdateGroup;
|
||||||
|
const result = await new UpdateGroupUseCase().execute(c.req.param('groupId'), user.id, input);
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
66
apps/backend/src/modules/groups/features/update/use-case.ts
Normal file
66
apps/backend/src/modules/groups/features/update/use-case.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { GroupDto, ProblemDetails, Result, UpdateGroup } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { conflictProblem, forbiddenProblem, notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
|
import { type GroupRecord, toGroupDto } from '../../lib';
|
||||||
|
|
||||||
|
type UpdateGroupDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'attendee'>;
|
||||||
|
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Editar grupo": name, schedule, capacity, billing and who it is for. Only
|
||||||
|
* the owner can. A lower capacity than the current members is allowed: it only
|
||||||
|
* stops new additions.
|
||||||
|
*
|
||||||
|
* Who it is for: turning it into a kids group needs the `kidsGroups` plan
|
||||||
|
* feature (a kids group that already exists keeps working after a downgrade);
|
||||||
|
* going back to adults is blocked while a member has no phone of their own,
|
||||||
|
* since without the adult in charge nobody could be reached.
|
||||||
|
*/
|
||||||
|
export class UpdateGroupUseCase {
|
||||||
|
constructor(private readonly deps: UpdateGroupDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(groupId: string, userId: string, input: UpdateGroup): Promise<Result<GroupDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
|
||||||
|
const group = await db.group.findUnique({
|
||||||
|
where: { id: groupId },
|
||||||
|
select: { id: true, createdById: true, audience: true },
|
||||||
|
});
|
||||||
|
if (!group) return err(notFoundResourceProblem('Group', groupId));
|
||||||
|
if (group.createdById !== userId) {
|
||||||
|
return err(
|
||||||
|
forbiddenProblem({
|
||||||
|
detail: 'Solo quien creó el grupo puede editarlo.',
|
||||||
|
code: 'group_owner_required',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.audience === 'KIDS' && group.audience !== 'KIDS') {
|
||||||
|
const allowed = await (this.deps.planGuard ?? new PlanGuard()).requireFeature(userId, 'kidsGroups');
|
||||||
|
if (!allowed.ok) return allowed;
|
||||||
|
}
|
||||||
|
if (input.audience === 'ADULTS' && group.audience === 'KIDS') {
|
||||||
|
const withoutPhone = await db.attendee.count({
|
||||||
|
where: { groupId, status: { not: 'DROPPED' }, person: { phone: null } },
|
||||||
|
});
|
||||||
|
if (withoutPhone > 0) {
|
||||||
|
return err(
|
||||||
|
conflictProblem({
|
||||||
|
detail: 'Hay chicos sin teléfono propio: cargales uno antes de pasar el grupo a adultos.',
|
||||||
|
code: 'group_has_kids_without_phone',
|
||||||
|
params: { count: withoutPhone },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await db.group.update({ where: { id: groupId }, data: input });
|
||||||
|
return ok(toGroupDto(updated as GroupRecord));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { BillingType, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
|
import type { BillingType, GroupAudience, GroupDto, GroupListItem, WeekDay } from '@gruperly/shared';
|
||||||
|
|
||||||
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
|
export type GroupDb = Pick<PrismaClient, 'group' | 'groupMember'>;
|
||||||
|
|
||||||
@@ -21,6 +21,7 @@ export type GroupRecord = {
|
|||||||
inviteToken?: string | null;
|
inviteToken?: string | null;
|
||||||
autoPaymentReminders?: boolean;
|
autoPaymentReminders?: boolean;
|
||||||
autoReengagement?: boolean;
|
autoReengagement?: boolean;
|
||||||
|
audience?: GroupAudience;
|
||||||
};
|
};
|
||||||
|
|
||||||
/* 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
|
||||||
@@ -49,6 +50,7 @@ export function toGroupDto(record: GroupRecord): GroupDto {
|
|||||||
inviteToken: record.inviteToken ?? null,
|
inviteToken: record.inviteToken ?? null,
|
||||||
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
||||||
autoReengagement: record.autoReengagement ?? false,
|
autoReengagement: record.autoReengagement ?? false,
|
||||||
|
audience: record.audience ?? 'ADULTS',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import getAttendeeStatsRoute from '../attendees/features/get-stats/route';
|
|||||||
import moveAttendeeRoute from '../attendees/features/move/route';
|
import moveAttendeeRoute from '../attendees/features/move/route';
|
||||||
import removeAttendeeRoute from '../attendees/features/remove/route';
|
import removeAttendeeRoute from '../attendees/features/remove/route';
|
||||||
import updateAttendeeRoute from '../attendees/features/update/route';
|
import updateAttendeeRoute from '../attendees/features/update/route';
|
||||||
|
import updateAttendeeGuardianRoute from '../attendees/features/update-guardian/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';
|
||||||
@@ -19,6 +20,7 @@ import getAllRoute from './features/get-all/route';
|
|||||||
import getByIdRoute from './features/get-by-id/route';
|
import getByIdRoute from './features/get-by-id/route';
|
||||||
import inviteTokenRoute from './features/invite-token/route';
|
import inviteTokenRoute from './features/invite-token/route';
|
||||||
import listAttendeesRoute from './features/list-attendees/route';
|
import listAttendeesRoute from './features/list-attendees/route';
|
||||||
|
import updateGroupRoute from './features/update/route';
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
|
|
||||||
@@ -31,12 +33,14 @@ routes.route('/', bulkCreateAttendeesRoute);
|
|||||||
routes.route('/', getByIdRoute);
|
routes.route('/', getByIdRoute);
|
||||||
routes.route('/', createPaymentsBatchRoute);
|
routes.route('/', createPaymentsBatchRoute);
|
||||||
routes.route('/', updateGroupAutomationsRoute);
|
routes.route('/', updateGroupAutomationsRoute);
|
||||||
|
routes.route('/', updateGroupRoute);
|
||||||
routes.route('/', addToGroupWaitlistRoute);
|
routes.route('/', addToGroupWaitlistRoute);
|
||||||
routes.route('/', groupWaitlistRoutes);
|
routes.route('/', groupWaitlistRoutes);
|
||||||
routes.route('/', groupPreRegistrationRoutes);
|
routes.route('/', groupPreRegistrationRoutes);
|
||||||
routes.route('/', analyticsRoutes);
|
routes.route('/', analyticsRoutes);
|
||||||
routes.route('/', getAttendeeRoute);
|
routes.route('/', getAttendeeRoute);
|
||||||
routes.route('/', updateAttendeeRoute);
|
routes.route('/', updateAttendeeRoute);
|
||||||
|
routes.route('/', updateAttendeeGuardianRoute);
|
||||||
routes.route('/', getAttendeeStatsRoute);
|
routes.route('/', getAttendeeStatsRoute);
|
||||||
routes.route('/', removeAttendeeRoute);
|
routes.route('/', removeAttendeeRoute);
|
||||||
routes.route('/', moveAttendeeRoute);
|
routes.route('/', moveAttendeeRoute);
|
||||||
|
|||||||
@@ -25,8 +25,14 @@ route.get('/', validate.query(MpCallbackQuerySchema), async (c) => {
|
|||||||
return c.redirect(new URL('/login', getWebOrigin()).toString());
|
return c.redirect(new URL('/login', getWebOrigin()).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
const useCase = new CompleteMpAuthorization();
|
let result: Awaited<ReturnType<CompleteMpAuthorization['execute']>>;
|
||||||
const result = await useCase.execute({ code, state, error });
|
try {
|
||||||
|
result = await new CompleteMpAuthorization().execute({ code, state, error, userId: user.id });
|
||||||
|
} catch (unexpected) {
|
||||||
|
// A broken deployment (e.g. TOKEN_ENCRYPTION_KEY) still lands back in the app.
|
||||||
|
logger.error({ err: unexpected }, 'Mercado Pago callback crashed');
|
||||||
|
return c.redirect(buildMpReturnUrl(getWebOrigin(), 'settings', { kind: 'error', reason: 'mp_error' }));
|
||||||
|
}
|
||||||
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ export class CompleteMpAuthorization {
|
|||||||
code?: string;
|
code?: string;
|
||||||
state?: string;
|
state?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
|
/** The signed-in teacher; has to be the one who started the flow. */
|
||||||
|
userId: string;
|
||||||
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
|
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
|
||||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||||
try {
|
try {
|
||||||
@@ -70,6 +72,14 @@ export class CompleteMpAuthorization {
|
|||||||
|
|
||||||
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
|
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
|
||||||
|
|
||||||
|
// A state started by someone else (a link sent to this teacher) would attach
|
||||||
|
// this teacher's Mercado Pago account to the other account. Not burned: it
|
||||||
|
// is not this session's to spend.
|
||||||
|
if (stored.ownerId !== input.userId) {
|
||||||
|
logger.warn('Mercado Pago callback with a state from another account');
|
||||||
|
return failure('invalid_state', returnTo);
|
||||||
|
}
|
||||||
|
|
||||||
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
|
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
|
||||||
// means someone replayed a state we already consumed.
|
// means someone replayed a state we already consumed.
|
||||||
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
||||||
|
|||||||
39
apps/backend/src/modules/mp/lib/callback-origin.ts
Normal file
39
apps/backend/src/modules/mp/lib/callback-origin.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import type { MiddlewareHandler } from 'hono';
|
||||||
|
|
||||||
|
type Env = Record<string, string | undefined>;
|
||||||
|
|
||||||
|
function hostOf(value: string | undefined): string | null {
|
||||||
|
if (!value?.trim()) return null;
|
||||||
|
try {
|
||||||
|
return new URL(value.trim()).host;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a callback that arrived through the public tunnel has to be replayed,
|
||||||
|
* or `null` when it is already on the origin that holds the session.
|
||||||
|
*
|
||||||
|
* In local development Mercado Pago only accepts an HTTPS Redirect URL, so it
|
||||||
|
* comes back through ngrok, while the session cookie belongs to the API on
|
||||||
|
* localhost (`BETTER_AUTH_URL`). In production both are the same host and this
|
||||||
|
* never fires, so it cannot loop behind the proxy.
|
||||||
|
*/
|
||||||
|
export function mpCallbackBounceUrl(requestUrl: string, requestHost: string | undefined, env: Env = process.env): string | null {
|
||||||
|
const tunnelHost = hostOf(env.MP_REDIRECT_URI);
|
||||||
|
const sessionOrigin = env.BETTER_AUTH_URL?.trim();
|
||||||
|
const sessionHost = hostOf(sessionOrigin);
|
||||||
|
if (!tunnelHost || !sessionOrigin || !sessionHost || tunnelHost === sessionHost) return null;
|
||||||
|
if (requestHost !== tunnelHost) return null;
|
||||||
|
|
||||||
|
const url = new URL(requestUrl);
|
||||||
|
return `${new URL(sessionOrigin).origin}${url.pathname}${url.search}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs before the session middleware, which would answer 401 on the tunnel. */
|
||||||
|
export const mpCallbackOriginMiddleware: MiddlewareHandler = async (c, next) => {
|
||||||
|
const target = mpCallbackBounceUrl(c.req.url, c.req.header('x-forwarded-host') ?? c.req.header('host'));
|
||||||
|
if (target) return c.redirect(target);
|
||||||
|
await next();
|
||||||
|
};
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
export { mpCallbackBounceUrl, mpCallbackOriginMiddleware } from './callback-origin';
|
||||||
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
|
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
|
||||||
export {
|
export {
|
||||||
codeChallengeFromVerifier,
|
codeChallengeFromVerifier,
|
||||||
@@ -8,9 +9,11 @@ export {
|
|||||||
} from './crypto';
|
} from './crypto';
|
||||||
export {
|
export {
|
||||||
createCheckoutPreference,
|
createCheckoutPreference,
|
||||||
|
expireCheckoutPreference,
|
||||||
MP_API_URL,
|
MP_API_URL,
|
||||||
type MpCreatePreferenceInput,
|
type MpCreatePreferenceInput,
|
||||||
type MpPreference,
|
type MpPreference,
|
||||||
|
type MpPreferenceItem,
|
||||||
type MpSearchedPayment,
|
type MpSearchedPayment,
|
||||||
searchMpPaymentByExternalReference,
|
searchMpPaymentByExternalReference,
|
||||||
} from './mp-http';
|
} from './mp-http';
|
||||||
|
|||||||
@@ -6,13 +6,22 @@ export const MP_API_URL = 'https://api.mercadopago.com';
|
|||||||
// Mercado Pago runs the seller's money straight into the professor's own
|
// Mercado Pago runs the seller's money straight into the professor's own
|
||||||
// account: no platform_id of ours and no fee split.
|
// account: no platform_id of ours and no fee split.
|
||||||
|
|
||||||
|
export type MpPreferenceItem = { title: string; unitPrice: number };
|
||||||
|
|
||||||
export type MpCreatePreferenceInput = {
|
export type MpCreatePreferenceInput = {
|
||||||
title: string;
|
title: string;
|
||||||
unitPrice: number;
|
unitPrice: number;
|
||||||
|
/**
|
||||||
|
* Several lines in one link (a combined monthly charge). Without it the
|
||||||
|
* preference has the single `title` / `unitPrice` line.
|
||||||
|
*/
|
||||||
|
items?: MpPreferenceItem[];
|
||||||
currencyId: string;
|
currencyId: string;
|
||||||
externalReference: string;
|
externalReference: string;
|
||||||
/** Where the buyer lands after paying (pending/success/failure). */
|
/** Where the buyer lands after paying (pending/success/failure). */
|
||||||
backUrl: string;
|
backUrl: string;
|
||||||
|
/** Where Mercado Pago notifies the payment (`POST /payments/webhooks/mp/:id`). */
|
||||||
|
notificationUrl?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type MpPreference = {
|
export type MpPreference = {
|
||||||
@@ -21,6 +30,21 @@ export type MpPreference = {
|
|||||||
sandboxInitPoint: string | null;
|
sandboxInitPoint: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mercado Pago refuses `auto_return` (`invalid_auto_return`) and notification
|
||||||
|
* URLs unless they are public HTTPS. In local development the web is on
|
||||||
|
* localhost: the buyer then gets MP's "back to the site" button instead of the
|
||||||
|
* automatic redirect, and without a tunnel only the polling confirms payments.
|
||||||
|
*/
|
||||||
|
export function isPublicHttpsUrl(value: string): boolean {
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
return url.protocol === 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a Checkout Pro preference in the seller's account. This is a payment
|
* Creates a Checkout Pro preference in the seller's account. This is a payment
|
||||||
* *link*: nothing is charged, and creating it again after a lost connection is
|
* *link*: nothing is charged, and creating it again after a lost connection is
|
||||||
@@ -41,16 +65,19 @@ export async function createCheckoutPreference(
|
|||||||
Authorization: `Bearer ${accessToken}`,
|
Authorization: `Bearer ${accessToken}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
items: [
|
items: (input.items?.length ? input.items : [{ title: input.title, unitPrice: input.unitPrice }]).map(
|
||||||
{
|
(item) => ({
|
||||||
title: input.title,
|
title: item.title,
|
||||||
currency_id: input.currencyId,
|
currency_id: input.currencyId,
|
||||||
quantity: 1,
|
quantity: 1,
|
||||||
unit_price: input.unitPrice,
|
unit_price: item.unitPrice,
|
||||||
},
|
}),
|
||||||
],
|
),
|
||||||
external_reference: input.externalReference,
|
external_reference: input.externalReference,
|
||||||
auto_return: 'approved',
|
...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}),
|
||||||
|
...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl)
|
||||||
|
? { notification_url: input.notificationUrl }
|
||||||
|
: {}),
|
||||||
back_urls: {
|
back_urls: {
|
||||||
success: input.backUrl,
|
success: input.backUrl,
|
||||||
pending: input.backUrl,
|
pending: input.backUrl,
|
||||||
@@ -81,6 +108,38 @@ export async function createCheckoutPreference(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Expires a preference so its link stops accepting payments (a combined link
|
||||||
|
* one of whose fees was paid some other way). Best effort: the caller decides
|
||||||
|
* what to do when Mercado Pago does not answer.
|
||||||
|
*/
|
||||||
|
export async function expireCheckoutPreference(
|
||||||
|
accessToken: string,
|
||||||
|
preferenceId: string,
|
||||||
|
now: Date = new Date(),
|
||||||
|
): Promise<void> {
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetch(`${MP_API_URL}/checkout/preferences/${encodeURIComponent(preferenceId)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Accept: 'application/json',
|
||||||
|
Authorization: `Bearer ${accessToken}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ expires: true, expiration_date_to: now.toISOString() }),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error }, 'Mercado Pago preferences endpoint unreachable');
|
||||||
|
throw new MpApiError(0, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
logger.error({ status: response.status }, 'Mercado Pago preference expiration failed');
|
||||||
|
throw new MpApiError(response.status, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export type MpSearchedPayment = {
|
export type MpSearchedPayment = {
|
||||||
id: string;
|
id: string;
|
||||||
status: string;
|
status: string;
|
||||||
@@ -120,9 +179,10 @@ export async function searchMpPaymentByExternalReference(
|
|||||||
|
|
||||||
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
|
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
|
||||||
const results = payload?.results ?? [];
|
const results = payload?.results ?? [];
|
||||||
const match = results.find(
|
// A rejected attempt and a later approved one share the reference: the
|
||||||
(payment) => payment.external_reference === externalReference,
|
// approved one wins, whatever order Mercado Pago lists them in.
|
||||||
);
|
const ours = results.filter((payment) => payment.external_reference === externalReference);
|
||||||
|
const match = ours.find((payment) => payment.status === 'approved') ?? ours[0];
|
||||||
if (!match) {
|
if (!match) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import { toOnboardingGroupDto } from '../../lib';
|
|||||||
type CreateFirstGroupDeps = {
|
type CreateFirstGroupDeps = {
|
||||||
db?: Pick<PrismaClient, 'user'>;
|
db?: Pick<PrismaClient, 'user'>;
|
||||||
unitOfWork?: UnitOfWork;
|
unitOfWork?: UnitOfWork;
|
||||||
planGuard?: Pick<PlanGuard, 'canCreateGroup'>;
|
planGuard?: Pick<PlanGuard, 'canCreateGroup' | 'requireFeature'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class CreateFirstGroup {
|
export class CreateFirstGroup {
|
||||||
@@ -41,10 +41,15 @@ export class CreateFirstGroup {
|
|||||||
return err(planNotSelectedProblem());
|
return err(planNotSelectedProblem());
|
||||||
}
|
}
|
||||||
|
|
||||||
const allowed = await (this.deps.planGuard ?? new PlanGuard()).canCreateGroup(userId);
|
const planGuard = this.deps.planGuard ?? new PlanGuard();
|
||||||
|
const allowed = await planGuard.canCreateGroup(userId);
|
||||||
if (!allowed.ok) {
|
if (!allowed.ok) {
|
||||||
return allowed;
|
return allowed;
|
||||||
}
|
}
|
||||||
|
if (data.audience === 'KIDS') {
|
||||||
|
const kidsAllowed = await planGuard.requireFeature(userId, 'kidsGroups');
|
||||||
|
if (!kidsAllowed.ok) return kidsAllowed;
|
||||||
|
}
|
||||||
|
|
||||||
const transaction = unitOfWork.executeResult(
|
const transaction = unitOfWork.executeResult(
|
||||||
async (tx: Prisma.TransactionClient) => {
|
async (tx: Prisma.TransactionClient) => {
|
||||||
@@ -58,6 +63,7 @@ export class CreateFirstGroup {
|
|||||||
price: data.price,
|
price: data.price,
|
||||||
billingType: data.billingType,
|
billingType: data.billingType,
|
||||||
dueDay: data.dueDay,
|
dueDay: data.dueDay,
|
||||||
|
audience: data.audience,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { BillingType, OnboardingGroupDto, WeekDay } from '@gruperly/shared';
|
import type { BillingType, GroupAudience, OnboardingGroupDto, WeekDay } from '@gruperly/shared';
|
||||||
|
|
||||||
type PriceLike = { toString(): string };
|
type PriceLike = { toString(): string };
|
||||||
|
|
||||||
@@ -17,6 +17,7 @@ export type OnboardingGroupRecord = {
|
|||||||
dueDay: number | null;
|
dueDay: number | null;
|
||||||
autoPaymentReminders?: boolean;
|
autoPaymentReminders?: boolean;
|
||||||
autoReengagement?: boolean;
|
autoReengagement?: boolean;
|
||||||
|
audience?: GroupAudience;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
|
export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingGroupDto {
|
||||||
@@ -35,5 +36,6 @@ export function toOnboardingGroupDto(record: OnboardingGroupRecord): OnboardingG
|
|||||||
dueDay: record.dueDay,
|
dueDay: record.dueDay,
|
||||||
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
autoPaymentReminders: record.autoPaymentReminders ?? false,
|
||||||
autoReengagement: record.autoReengagement ?? false,
|
autoReengagement: record.autoReengagement ?? false,
|
||||||
|
audience: record.audience ?? 'ADULTS',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import type { UpdateAutoChargeSettings } from '@gruperly/shared';
|
||||||
|
import { UpdateAutoChargeSettingsSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { AutoChargeSettingsUseCase } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/auto-charge', async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
return resultJson(c, await new AutoChargeSettingsUseCase().get(user.id));
|
||||||
|
});
|
||||||
|
|
||||||
|
route.put('/auto-charge', validate.json(UpdateAutoChargeSettingsSchema), async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const input = c.req.valid('json') as UpdateAutoChargeSettings;
|
||||||
|
return resultJson(c, await new AutoChargeSettingsUseCase().update(user.id, input));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { AutoChargeSettingsDto, ProblemDetails, Result, UpdateAutoChargeSettings } from '@gruperly/shared';
|
||||||
|
import { AUTO_CHARGE_DEFAULT_DUE_IN_DAYS, ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
|
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
|
||||||
|
import { localDateIn, monthKey, nextAutoChargeDate } from '../../lib/auto-charge-schedule';
|
||||||
|
|
||||||
|
type AutoChargeSettingsDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'autoChargeSettings' | 'paymentRun' | 'user'>;
|
||||||
|
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULTS = { enabled: false, chargeDay: 1, dueInDays: AUTO_CHARGE_DEFAULT_DUE_IN_DAYS, sendWhatsapp: false, enabledAt: null };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings → "Cobro automático": the teacher's day of the month, due days and
|
||||||
|
* whether the links go out by WhatsApp. Turning something on goes through the
|
||||||
|
* plan (Mercado Pago charges; WhatsApp automations for the sending); turning it
|
||||||
|
* off always works.
|
||||||
|
*/
|
||||||
|
export class AutoChargeSettingsUseCase {
|
||||||
|
constructor(private readonly deps: AutoChargeSettingsDeps = {}) {}
|
||||||
|
|
||||||
|
private get db() {
|
||||||
|
return this.deps.db ?? prisma;
|
||||||
|
}
|
||||||
|
|
||||||
|
async get(ownerId: string): Promise<Result<AutoChargeSettingsDto, ProblemDetails>> {
|
||||||
|
return ok(await this.load(ownerId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(ownerId: string, input: UpdateAutoChargeSettings): Promise<Result<AutoChargeSettingsDto, ProblemDetails>> {
|
||||||
|
const planGuard = this.deps.planGuard ?? new PlanGuard();
|
||||||
|
if (input.enabled === true) {
|
||||||
|
const allowed = await planGuard.requireFeature(ownerId, 'mpCharges');
|
||||||
|
if (!allowed.ok) return allowed;
|
||||||
|
}
|
||||||
|
if (input.sendWhatsapp === true) {
|
||||||
|
const allowed = await planGuard.requireFeature(ownerId, 'whatsappAutomations');
|
||||||
|
if (!allowed.ok) return allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = await this.db.autoChargeSettings.findUnique({ where: { ownerId } });
|
||||||
|
const turningOn = input.enabled === true && !current?.enabled;
|
||||||
|
const data = {
|
||||||
|
...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
|
||||||
|
...(input.chargeDay !== undefined ? { chargeDay: input.chargeDay } : {}),
|
||||||
|
...(input.dueInDays !== undefined ? { dueInDays: input.dueInDays } : {}),
|
||||||
|
...(input.sendWhatsapp !== undefined ? { sendWhatsapp: input.sendWhatsapp } : {}),
|
||||||
|
...(turningOn ? { enabledAt: this.deps.now ?? new Date() } : {}),
|
||||||
|
};
|
||||||
|
await this.db.autoChargeSettings.upsert({ where: { ownerId }, create: { ownerId, ...data }, update: data });
|
||||||
|
return ok(await this.load(ownerId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async load(ownerId: string): Promise<AutoChargeSettingsDto> {
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
const [settings, owner, lastRun] = await Promise.all([
|
||||||
|
this.db.autoChargeSettings.findUnique({ where: { ownerId } }),
|
||||||
|
this.db.user.findUnique({ where: { id: ownerId }, select: { country: true } }),
|
||||||
|
this.db.paymentRun.findFirst({ where: { ownerId }, orderBy: { createdAt: 'desc' } }),
|
||||||
|
]);
|
||||||
|
const current = settings ?? DEFAULTS;
|
||||||
|
const timeZone = teacherTimeZone(owner?.country);
|
||||||
|
const ranThisMonth = lastRun?.periodKey === monthKey(localDateIn(now, timeZone));
|
||||||
|
|
||||||
|
return {
|
||||||
|
enabled: current.enabled,
|
||||||
|
chargeDay: current.chargeDay,
|
||||||
|
dueInDays: current.dueInDays,
|
||||||
|
sendWhatsapp: current.sendWhatsapp,
|
||||||
|
nextRunDate: current.enabled ? nextAutoChargeDate(current, now, timeZone, ranThisMonth) : null,
|
||||||
|
lastRun: lastRun
|
||||||
|
? {
|
||||||
|
periodKey: lastRun.periodKey,
|
||||||
|
status: lastRun.status,
|
||||||
|
skipReason: lastRun.skipReason,
|
||||||
|
fees: lastRun.fees,
|
||||||
|
checkouts: lastRun.checkouts,
|
||||||
|
linked: lastRun.linked,
|
||||||
|
failed: lastRun.failed,
|
||||||
|
sent: lastRun.sent,
|
||||||
|
createdAt: lastRun.createdAt.toISOString(),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { type CountryCode, currencyForCountry } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { getApiPublicOrigin } from '@/lib/public-origin';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
|
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
||||||
|
import { guardianSelect, primaryGuardian } from '@/modules/people/lib/people';
|
||||||
|
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
|
||||||
|
import { SendPaymentLinks } from '@/modules/whatsapp/jobs/send-payment-links';
|
||||||
|
import { autoChargeDueDate, localDateIn, monthKey } from '../../lib/auto-charge-schedule';
|
||||||
|
import { buildCheckoutLink } from '../../lib/checkouts';
|
||||||
|
|
||||||
|
const UNIQUE_VIOLATION = 'P2002';
|
||||||
|
|
||||||
|
export type GenerateMonthlyChargesDeps = {
|
||||||
|
db?: PrismaClient;
|
||||||
|
getToken?: typeof getMpAccessToken;
|
||||||
|
createPreference?: typeof createCheckoutPreference;
|
||||||
|
planGuard?: Pick<PlanGuard, 'hasFeature'>;
|
||||||
|
/** Sends the generated links by WhatsApp; returns how many went out. */
|
||||||
|
sendLinks?: (ownerId: string, checkoutIds: string[]) => Promise<number>;
|
||||||
|
webOrigin?: string;
|
||||||
|
apiOrigin?: string;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type GenerateMonthlyChargesResult =
|
||||||
|
| { outcome: 'already_ran' }
|
||||||
|
| { outcome: 'skipped'; reason: string }
|
||||||
|
| { outcome: 'done'; fees: number; checkouts: number; linked: number; failed: number; sent: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The automatic monthly charge of one teacher.
|
||||||
|
*
|
||||||
|
* Every ACTIVE member of their monthly groups with a price gets this month's
|
||||||
|
* fee. Fees are bundled by payer (the adult in charge for kids, the person
|
||||||
|
* otherwise) into one Mercado Pago link with one line per fee; people who pay
|
||||||
|
* by transfer (`payWithMercadoPago` off) get the fee without a link.
|
||||||
|
*
|
||||||
|
* Rows first, links after, as in the manual batch: a link that fails leaves its
|
||||||
|
* checkout OPEN without a link and the teacher retries it with "Generar" from
|
||||||
|
* Cobros. The unique run per teacher and month makes a second call a no-op.
|
||||||
|
*/
|
||||||
|
export class GenerateMonthlyCharges {
|
||||||
|
constructor(private readonly deps: GenerateMonthlyChargesDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(ownerId: string): Promise<GenerateMonthlyChargesResult> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
|
||||||
|
const owner = await db.user.findUnique({
|
||||||
|
where: { id: ownerId },
|
||||||
|
select: { country: true, autoCharge: true },
|
||||||
|
});
|
||||||
|
if (!owner?.autoCharge) return { outcome: 'skipped', reason: 'not_configured' };
|
||||||
|
const settings = owner.autoCharge;
|
||||||
|
|
||||||
|
const local = localDateIn(now, teacherTimeZone(owner.country));
|
||||||
|
const periodKey = monthKey(local);
|
||||||
|
|
||||||
|
let runId: string;
|
||||||
|
try {
|
||||||
|
const run = await db.paymentRun.create({ data: { ownerId, periodKey }, select: { id: true } });
|
||||||
|
runId = run.id;
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as { code?: string }).code === UNIQUE_VIOLATION) return { outcome: 'already_ran' };
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const skip = async (reason: string): Promise<GenerateMonthlyChargesResult> => {
|
||||||
|
await db.paymentRun.update({
|
||||||
|
where: { id: runId },
|
||||||
|
data: { status: 'SKIPPED', skipReason: reason, finishedAt: new Date() },
|
||||||
|
});
|
||||||
|
return { outcome: 'skipped', reason };
|
||||||
|
};
|
||||||
|
|
||||||
|
const planGuard = this.deps.planGuard ?? new PlanGuard();
|
||||||
|
if (!(await planGuard.hasFeature(ownerId, 'mpCharges'))) return skip('plan_feature_required');
|
||||||
|
|
||||||
|
const token = await (this.deps.getToken ?? getMpAccessToken)(ownerId);
|
||||||
|
if (!token.ok) return skip('mp_not_connected');
|
||||||
|
|
||||||
|
const groups = await db.group.findMany({
|
||||||
|
where: {
|
||||||
|
createdById: ownerId,
|
||||||
|
price: { not: null },
|
||||||
|
OR: [{ billingType: null }, { billingType: 'MONTHLY' }],
|
||||||
|
},
|
||||||
|
select: { id: true, price: true },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
});
|
||||||
|
if (groups.length === 0) return skip('no_groups');
|
||||||
|
const priceOf = new Map(groups.map((group) => [group.id, group.price]));
|
||||||
|
|
||||||
|
const attendees = await db.attendee.findMany({
|
||||||
|
where: {
|
||||||
|
groupId: { in: groups.map((group) => group.id) },
|
||||||
|
status: 'ACTIVE',
|
||||||
|
// Already billed this month (a fee created by hand counts only if it has the period).
|
||||||
|
payments: { none: { periodKey } },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
groupId: true,
|
||||||
|
person: { select: { id: true, payWithMercadoPago: true, ...guardianSelect } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const currency = currencyForCountry((owner.country as CountryCode | null) ?? null);
|
||||||
|
const dueDate = autoChargeDueDate(local, settings.dueInDays);
|
||||||
|
|
||||||
|
// Payer → their fees. Map keeps the first-seen order.
|
||||||
|
const byPayer = new Map<string, typeof attendees>();
|
||||||
|
for (const attendee of attendees) {
|
||||||
|
const payerId = primaryGuardian(attendee.person)?.id ?? attendee.person.id;
|
||||||
|
const list = byPayer.get(payerId) ?? [];
|
||||||
|
list.push(attendee);
|
||||||
|
byPayer.set(payerId, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
let fees = 0;
|
||||||
|
const checkoutIds: string[] = [];
|
||||||
|
for (const [payerId, payerAttendees] of byPayer) {
|
||||||
|
const created = await db.$transaction(async (tx) => {
|
||||||
|
const viaMp = payerAttendees.filter((attendee) => attendee.person.payWithMercadoPago);
|
||||||
|
const total = viaMp.reduce((sum, attendee) => sum + Number(priceOf.get(attendee.groupId)?.toString() ?? 0), 0);
|
||||||
|
const checkout = viaMp.length
|
||||||
|
? await tx.paymentCheckout.create({
|
||||||
|
data: { ownerId, payerPersonId: payerId, runId, amount: total, currency, dueDate },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
|
for (const attendee of payerAttendees) {
|
||||||
|
const price = priceOf.get(attendee.groupId);
|
||||||
|
if (price == null) continue;
|
||||||
|
await tx.payment.create({
|
||||||
|
data: {
|
||||||
|
groupId: attendee.groupId,
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
amount: price,
|
||||||
|
currency,
|
||||||
|
dueDate,
|
||||||
|
periodKey,
|
||||||
|
status: 'PENDING',
|
||||||
|
checkoutId: attendee.person.payWithMercadoPago ? (checkout?.id ?? null) : null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { checkoutId: checkout?.id ?? null, fees: payerAttendees.length };
|
||||||
|
});
|
||||||
|
fees += created.fees;
|
||||||
|
if (created.checkoutId) checkoutIds.push(created.checkoutId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const context = {
|
||||||
|
webOrigin: this.deps.webOrigin ?? getWebOrigin(),
|
||||||
|
apiOrigin: this.deps.apiOrigin ?? getApiPublicOrigin(),
|
||||||
|
accessToken: token.value.accessToken,
|
||||||
|
};
|
||||||
|
const linkedIds: string[] = [];
|
||||||
|
let failed = 0;
|
||||||
|
for (const checkoutId of checkoutIds) {
|
||||||
|
const link = await buildCheckoutLink(db, checkoutId, context, { createPreference: this.deps.createPreference });
|
||||||
|
if (link.ok) linkedIds.push(checkoutId);
|
||||||
|
else failed += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let sent = 0;
|
||||||
|
if (settings.sendWhatsapp && linkedIds.length > 0) {
|
||||||
|
try {
|
||||||
|
sent = await (this.deps.sendLinks ?? defaultSendLinks)(ownerId, linkedIds);
|
||||||
|
} catch (error) {
|
||||||
|
// The fees and links are there: a WhatsApp failure must not undo the run.
|
||||||
|
logger.error({ err: error }, 'Sending the monthly payment links by WhatsApp failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = { fees, checkouts: checkoutIds.length, linked: linkedIds.length, failed, sent };
|
||||||
|
await db.paymentRun.update({
|
||||||
|
where: { id: runId },
|
||||||
|
data: { status: 'DONE', ...result, finishedAt: new Date() },
|
||||||
|
});
|
||||||
|
return { outcome: 'done', ...result };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function defaultSendLinks(ownerId: string, checkoutIds: string[]): Promise<number> {
|
||||||
|
const totals = await new SendPaymentLinks().execute(ownerId, checkoutIds);
|
||||||
|
return totals.sent;
|
||||||
|
}
|
||||||
@@ -15,17 +15,20 @@ import {
|
|||||||
notFoundResourceProblem,
|
notFoundResourceProblem,
|
||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { getApiPublicOrigin } from '@/lib/public-origin';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
import { getMpAccessToken } from '@/modules/mp';
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
||||||
import { CHECKOUT_BACK_PATH } from '../../lib';
|
import { CHECKOUT_BACK_PATH, paymentNotificationUrl } from '../../lib';
|
||||||
|
|
||||||
type BatchDeps = {
|
type BatchDeps = {
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
|
||||||
createPreference?: typeof createCheckoutPreference;
|
createPreference?: typeof createCheckoutPreference;
|
||||||
getToken?: typeof getMpAccessToken;
|
getToken?: typeof getMpAccessToken;
|
||||||
webOrigin?: string;
|
webOrigin?: string;
|
||||||
|
/** Public origin of the API, where Mercado Pago notifies the payment. */
|
||||||
|
apiOrigin?: string;
|
||||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -128,6 +131,7 @@ export class CreatePaymentBatch {
|
|||||||
currencyId: currency,
|
currencyId: currency,
|
||||||
externalReference: payment.id,
|
externalReference: payment.id,
|
||||||
backUrl,
|
backUrl,
|
||||||
|
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
|
||||||
});
|
});
|
||||||
link = preference;
|
link = preference;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ export class ListPayments {
|
|||||||
include: {
|
include: {
|
||||||
group: { select: { name: true, price: true } },
|
group: { select: { name: true, price: true } },
|
||||||
attendee: { select: { person: { select: { fullName: true } } } },
|
attendee: { select: { person: { select: { fullName: true } } } },
|
||||||
|
checkout: { select: { _count: { select: { payments: true } } } },
|
||||||
},
|
},
|
||||||
skip: getPaginationOffset(query),
|
skip: getPaginationOffset(query),
|
||||||
take: query.pageSize,
|
take: query.pageSize,
|
||||||
|
|||||||
@@ -8,17 +8,27 @@ import {
|
|||||||
notFoundResourceProblem,
|
notFoundResourceProblem,
|
||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { getApiPublicOrigin } from '@/lib/public-origin';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
import { getMpAccessToken } from '@/modules/mp';
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
||||||
import { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib';
|
import {
|
||||||
|
buildCheckoutLink,
|
||||||
|
CHECKOUT_BACK_PATH,
|
||||||
|
type PaymentRecord,
|
||||||
|
paymentDtoInclude,
|
||||||
|
paymentNotificationUrl,
|
||||||
|
toPaymentDto,
|
||||||
|
} from '../../lib';
|
||||||
|
|
||||||
type RenewDeps = {
|
type RenewDeps = {
|
||||||
db?: Pick<PrismaClient, 'payment' | 'user'>;
|
db?: Pick<PrismaClient, 'payment' | 'user' | 'paymentCheckout'>;
|
||||||
createPreference?: typeof createCheckoutPreference;
|
createPreference?: typeof createCheckoutPreference;
|
||||||
getToken?: typeof getMpAccessToken;
|
getToken?: typeof getMpAccessToken;
|
||||||
webOrigin?: string;
|
webOrigin?: string;
|
||||||
|
/** Public origin of the API, where Mercado Pago notifies the payment. */
|
||||||
|
apiOrigin?: string;
|
||||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -36,6 +46,7 @@ export class RenewPaymentLink {
|
|||||||
where: { id: paymentId },
|
where: { id: paymentId },
|
||||||
include: {
|
include: {
|
||||||
attendee: { select: { person: { select: { fullName: true } } } },
|
attendee: { select: { person: { select: { fullName: true } } } },
|
||||||
|
checkout: { select: { status: true, _count: { select: { payments: true } } } },
|
||||||
group: {
|
group: {
|
||||||
select: {
|
select: {
|
||||||
name: true,
|
name: true,
|
||||||
@@ -83,7 +94,23 @@ export class RenewPaymentLink {
|
|||||||
return token;
|
return token;
|
||||||
}
|
}
|
||||||
|
|
||||||
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}${CHECKOUT_BACK_PATH}`;
|
const webOrigin = this.deps.webOrigin ?? getWebOrigin();
|
||||||
|
const apiOrigin = this.deps.apiOrigin ?? getApiPublicOrigin();
|
||||||
|
|
||||||
|
// A fee of an open combined link gets that link back, covering all the
|
||||||
|
// payer's unpaid fees, instead of a single one.
|
||||||
|
if (payment.checkoutId && payment.checkout?.status === 'OPEN') {
|
||||||
|
const link = await buildCheckoutLink(
|
||||||
|
db,
|
||||||
|
payment.checkoutId,
|
||||||
|
{ webOrigin, apiOrigin, accessToken: token.value.accessToken },
|
||||||
|
{ createPreference: this.deps.createPreference },
|
||||||
|
);
|
||||||
|
if (!link.ok) return err(mpProviderErrorProblem());
|
||||||
|
return this.reload(payment.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const backUrl = `${webOrigin}${CHECKOUT_BACK_PATH}`;
|
||||||
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
|
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
|
||||||
|
|
||||||
let preference: { initPoint: string; id: string };
|
let preference: { initPoint: string; id: string };
|
||||||
@@ -94,6 +121,7 @@ export class RenewPaymentLink {
|
|||||||
currencyId: currency,
|
currencyId: currency,
|
||||||
externalReference: payment.id,
|
externalReference: payment.id,
|
||||||
backUrl,
|
backUrl,
|
||||||
|
notificationUrl: paymentNotificationUrl(apiOrigin, payment.id),
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
@@ -104,13 +132,17 @@ export class RenewPaymentLink {
|
|||||||
|
|
||||||
const updated = await db.payment.update({
|
const updated = await db.payment.update({
|
||||||
where: { id: payment.id },
|
where: { id: payment.id },
|
||||||
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id },
|
// Out of a superseded combined link: from now on it is a single fee.
|
||||||
include: {
|
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id, checkoutId: null },
|
||||||
attendee: { select: { person: { select: { fullName: true } } } },
|
include: paymentDtoInclude,
|
||||||
group: { select: { name: true, price: true } },
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return ok(toPaymentDto(updated as unknown as PaymentRecord));
|
return ok(toPaymentDto(updated as unknown as PaymentRecord));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async reload(paymentId: string): Promise<Result<PaymentDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const row = await db.payment.findUniqueOrThrow({ where: { id: paymentId }, include: paymentDtoInclude });
|
||||||
|
return ok(toPaymentDto(row as unknown as PaymentRecord));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,6 +7,12 @@ import { type FileStorage, getFileStorage } from '@/lib/storage';
|
|||||||
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
import { buildGroupWhereForUser } from '@/modules/groups/lib';
|
||||||
import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems';
|
import { storageNotAvailableProblem } from '@/modules/student-portal/lib/problems';
|
||||||
import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments';
|
import { OVERDUE_GRACE_MS } from '../../jobs/mark-overdue-payments';
|
||||||
|
import {
|
||||||
|
type ExpirePreferencesDeps,
|
||||||
|
expireSupersededPreferences,
|
||||||
|
type SupersededPreference,
|
||||||
|
supersedeCheckoutsOf,
|
||||||
|
} from '../../lib/checkouts';
|
||||||
import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications';
|
import { type ReviewNotifier, scheduleReviewNotification } from '../../lib/review-notifications';
|
||||||
|
|
||||||
export const RECEIPT_URL_TTL_SECONDS = 5 * 60;
|
export const RECEIPT_URL_TTL_SECONDS = 5 * 60;
|
||||||
@@ -18,6 +24,7 @@ type ReportedDeps = {
|
|||||||
storage?: FileStorage | null;
|
storage?: FileStorage | null;
|
||||||
notify?: ReviewNotifier;
|
notify?: ReviewNotifier;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
|
expirePreferences?: (preferences: SupersededPreference[], deps?: ExpirePreferencesDeps) => Promise<void>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const reportSelect = {
|
const reportSelect = {
|
||||||
@@ -155,6 +162,7 @@ export class ReportedPayments {
|
|||||||
const now = this.now;
|
const now = this.now;
|
||||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
|
||||||
|
let superseded: SupersededPreference[] = [];
|
||||||
const reviewed = await unitOfWork.executeResult(async (tx) => {
|
const reviewed = await unitOfWork.executeResult(async (tx) => {
|
||||||
const claimed = await tx.reportedPayment.updateMany({
|
const claimed = await tx.reportedPayment.updateMany({
|
||||||
where: { id: reportId, ...accessible(userId), status: 'REPORTED' },
|
where: { id: reportId, ...accessible(userId), status: 'REPORTED' },
|
||||||
@@ -179,11 +187,17 @@ export class ReportedPayments {
|
|||||||
where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } },
|
where: { id: { in: items.map((item) => item.paymentId) }, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||||
data: { status: 'PAID', paidAt: now },
|
data: { status: 'PAID', paidAt: now },
|
||||||
});
|
});
|
||||||
|
// A combined link would charge these fees again.
|
||||||
|
superseded = await supersedeCheckoutsOf(tx, items.map((item) => item.paymentId));
|
||||||
}
|
}
|
||||||
return ok(null);
|
return ok(null);
|
||||||
});
|
});
|
||||||
if (!reviewed.ok) return reviewed;
|
if (!reviewed.ok) return reviewed;
|
||||||
|
|
||||||
|
if (superseded.length > 0) {
|
||||||
|
void (this.deps.expirePreferences ?? expireSupersededPreferences)(superseded);
|
||||||
|
}
|
||||||
|
|
||||||
(this.deps.notify ?? scheduleReviewNotification)(reportId, now);
|
(this.deps.notify ?? scheduleReviewNotification)(reportId, now);
|
||||||
return this.load(reportId);
|
return this.load(reportId);
|
||||||
}
|
}
|
||||||
|
|||||||
24
apps/backend/src/modules/payments/features/webhook/route.ts
Normal file
24
apps/backend/src/modules/payments/features/webhook/route.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { problemJson } from '@/http/problem-details';
|
||||||
|
import { HandleMpCheckoutNotification, HandleMpPaymentNotification } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public (`isPublicApiRequest`): Mercado Pago calls it with the URL each
|
||||||
|
* Checkout Pro link carries as `notification_url`.
|
||||||
|
*/
|
||||||
|
route.post('/webhooks/mp/:paymentId', async (c) => {
|
||||||
|
const result = await new HandleMpPaymentNotification().execute(c.req.param('paymentId'));
|
||||||
|
if (!result.ok) return problemJson(c, result.error);
|
||||||
|
return c.json({ received: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Same, for a combined link (`chk_<id>`): every fee of the payer at once. */
|
||||||
|
route.post('/webhooks/mp/checkout/:checkoutId', async (c) => {
|
||||||
|
const result = await new HandleMpCheckoutNotification().execute(c.req.param('checkoutId'));
|
||||||
|
if (!result.ok) return problemJson(c, result.error);
|
||||||
|
return c.json({ received: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { err, ok } from '@gruperly/shared';
|
||||||
|
import { mpProviderErrorProblem } from '@/http/problem-builders';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { MpApiError } from '@/modules/mp/lib';
|
||||||
|
import {
|
||||||
|
type ConfirmMpCheckoutDeps,
|
||||||
|
type ConfirmMpPaymentDeps,
|
||||||
|
type ConfirmMpPaymentOutcome,
|
||||||
|
confirmMpCheckout,
|
||||||
|
confirmMpPayment,
|
||||||
|
} from '../../lib';
|
||||||
|
|
||||||
|
type HandleMpPaymentNotificationDeps = ConfirmMpPaymentDeps & {
|
||||||
|
db?: Pick<PrismaClient, 'payment'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MpPaymentNotificationOutcome = ConfirmMpPaymentOutcome | 'ignored';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mercado Pago says something happened to the payment of one of our links. The
|
||||||
|
* body is not read: the payment id in the URL picks the row, and the owner's
|
||||||
|
* account says whether it was approved (`confirmMpPayment`), so a forged or
|
||||||
|
* repeated notification costs one lookup and changes nothing.
|
||||||
|
*/
|
||||||
|
export class HandleMpPaymentNotification {
|
||||||
|
constructor(private readonly deps: HandleMpPaymentNotificationDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(paymentId: string): Promise<Result<{ outcome: MpPaymentNotificationOutcome }, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
|
||||||
|
// OVERDUE too: a student can still pay a link after its due date.
|
||||||
|
const payment = await db.payment.findFirst({
|
||||||
|
where: { id: paymentId, status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
|
||||||
|
select: { id: true, group: { select: { createdById: true } } },
|
||||||
|
});
|
||||||
|
if (!payment) return ok({ outcome: 'ignored' });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const outcome = await confirmMpPayment(db, { id: payment.id, ownerId: payment.group.createdById }, this.deps);
|
||||||
|
return ok({ outcome });
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof MpApiError)) throw error;
|
||||||
|
// Not a 2xx, so Mercado Pago retries; the polling job is the fallback anyway.
|
||||||
|
logger.warn({ paymentId: payment.id, status: error.status }, 'Could not confirm a notified Mercado Pago payment');
|
||||||
|
return err(mpProviderErrorProblem());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type HandleMpCheckoutNotificationDeps = ConfirmMpCheckoutDeps & {
|
||||||
|
db?: Pick<PrismaClient, 'paymentCheckout' | '$transaction'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** `HandleMpPaymentNotification` for a combined link. */
|
||||||
|
export class HandleMpCheckoutNotification {
|
||||||
|
constructor(private readonly deps: HandleMpCheckoutNotificationDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(checkoutId: string): Promise<Result<{ outcome: MpPaymentNotificationOutcome }, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
|
||||||
|
// SUPERSEDED too: it may have been paid right before it was invalidated.
|
||||||
|
const checkout = await db.paymentCheckout.findFirst({
|
||||||
|
where: { id: checkoutId, status: { in: ['OPEN', 'SUPERSEDED'] }, mpPreferenceId: { not: null } },
|
||||||
|
select: { id: true, ownerId: true },
|
||||||
|
});
|
||||||
|
if (!checkout) return ok({ outcome: 'ignored' });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const outcome = await confirmMpCheckout(db, checkout, this.deps);
|
||||||
|
return ok({ outcome });
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof MpApiError)) throw error;
|
||||||
|
logger.warn({ checkoutId: checkout.id, status: error.status }, 'Could not confirm a notified Mercado Pago payment');
|
||||||
|
return err(mpProviderErrorProblem());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,4 +6,5 @@ export {
|
|||||||
ReconcilePayments,
|
ReconcilePayments,
|
||||||
type ReconcilePaymentsResult,
|
type ReconcilePaymentsResult,
|
||||||
} from './reconcile-payments';
|
} from './reconcile-payments';
|
||||||
|
export { RunAutoCharges, type RunAutoChargesResult } from './run-auto-charges';
|
||||||
export { startPaymentJobs } from './schedule';
|
export { startPaymentJobs } from './schedule';
|
||||||
@@ -3,18 +3,18 @@ import prisma from '@/lib/prisma';
|
|||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { getMpAccessToken } from '@/modules/mp';
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
||||||
|
import { confirmMpCheckout, confirmMpPayment } from '../lib';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pulls payments from Mercado Pago instead of trusting a webhook. A payment
|
* Pulls payments from Mercado Pago. The notification
|
||||||
* link is just a preference until someone pays it; this job asks the seller's
|
* (`POST /payments/webhooks/mp/:id`) confirms them right away; this job is the
|
||||||
* account for our `external_reference` and marks approved payments as PAID.
|
* fallback for links created before it existed and for lost notifications.
|
||||||
*
|
* Both go through `confirmMpPayment`.
|
||||||
* This is the stopgap and the source of truth: if a webhook is ever added it
|
|
||||||
* gives you the confirmation, but this job is what keeps the Cobros screen
|
|
||||||
* correct even when a notification is lost.
|
|
||||||
*/
|
*/
|
||||||
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
|
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
|
||||||
const BATCH_LIMIT = 50;
|
const BATCH_LIMIT = 50;
|
||||||
|
/** A superseded combined link is still checked for a while: it may have been paid right before. */
|
||||||
|
const SUPERSEDED_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
export type ReconcilePaymentsResult = {
|
export type ReconcilePaymentsResult = {
|
||||||
paid: number;
|
paid: number;
|
||||||
@@ -42,6 +42,8 @@ export class ReconcilePayments {
|
|||||||
where: {
|
where: {
|
||||||
status: 'PENDING',
|
status: 'PENDING',
|
||||||
checkoutUrl: { not: null },
|
checkoutUrl: { not: null },
|
||||||
|
// Fees of a combined link are confirmed through their checkout below.
|
||||||
|
checkoutId: null,
|
||||||
createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) },
|
createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) },
|
||||||
},
|
},
|
||||||
include: { group: { select: { createdById: true } } },
|
include: { group: { select: { createdById: true } } },
|
||||||
@@ -51,34 +53,48 @@ export class ReconcilePayments {
|
|||||||
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
|
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
|
||||||
|
|
||||||
for (const payment of awaiting) {
|
for (const payment of awaiting) {
|
||||||
const token = await getToken(payment.group.createdById);
|
|
||||||
if (!token.ok) {
|
|
||||||
// No usable token (not linked, or needs re-auth). Not a payment problem:
|
|
||||||
// the row stays PENDING and the account notice tells the professor what to do.
|
|
||||||
totals.skipped += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const found = await search(token.value.accessToken, payment.id);
|
const outcome = await confirmMpPayment(
|
||||||
if (found && found.status === 'approved' && found.externalReference === payment.id) {
|
db,
|
||||||
await db.payment.update({
|
{ id: payment.id, ownerId: payment.group.createdById },
|
||||||
where: { id: payment.id },
|
{ getToken, search },
|
||||||
data: {
|
);
|
||||||
status: 'PAID',
|
// No usable token is not a payment problem: the row stays PENDING and
|
||||||
mpPaymentId: found.id,
|
// the account notice tells the professor what to do.
|
||||||
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
|
if (outcome === 'no_token') totals.skipped += 1;
|
||||||
},
|
if (outcome === 'paid') totals.paid += 1;
|
||||||
});
|
|
||||||
totals.paid += 1;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof MpApiError) {
|
if (!(error instanceof MpApiError)) {
|
||||||
totals.failed += 1;
|
|
||||||
} else {
|
|
||||||
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
|
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
|
||||||
totals.failed += 1;
|
|
||||||
}
|
}
|
||||||
|
totals.failed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkouts = await db.paymentCheckout.findMany({
|
||||||
|
where: {
|
||||||
|
mpPreferenceId: { not: null },
|
||||||
|
createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) },
|
||||||
|
OR: [
|
||||||
|
{ status: 'OPEN' },
|
||||||
|
{ status: 'SUPERSEDED', updatedAt: { gt: new Date(now.getTime() - SUPERSEDED_WINDOW_MS) } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
select: { id: true, ownerId: true },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
take: BATCH_LIMIT,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const checkout of checkouts) {
|
||||||
|
try {
|
||||||
|
const outcome = await confirmMpCheckout(db, checkout, { getToken, search });
|
||||||
|
if (outcome === 'no_token') totals.skipped += 1;
|
||||||
|
if (outcome === 'paid') totals.paid += 1;
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof MpApiError)) {
|
||||||
|
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
|
||||||
|
}
|
||||||
|
totals.failed += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
50
apps/backend/src/modules/payments/jobs/run-auto-charges.ts
Normal file
50
apps/backend/src/modules/payments/jobs/run-auto-charges.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { teacherTimeZone } from '@/modules/student-portal/lib/schedule';
|
||||||
|
import { GenerateMonthlyCharges } from '../features/auto-charge/generate-monthly-charges';
|
||||||
|
import { isAutoChargeDue } from '../lib/auto-charge-schedule';
|
||||||
|
|
||||||
|
export type RunAutoChargesResult = { due: number; done: number; skipped: number; failed: number };
|
||||||
|
|
||||||
|
type RunAutoChargesDeps = {
|
||||||
|
db?: PrismaClient;
|
||||||
|
generator?: Pick<GenerateMonthlyCharges, 'execute'>;
|
||||||
|
now?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hourly: runs the monthly charge of every teacher whose day it is on their
|
||||||
|
* own clock. Running every hour (and for a few days after the day) is what
|
||||||
|
* makes a restart or a failed tick harmless; the unique run per month keeps it
|
||||||
|
* to one.
|
||||||
|
*/
|
||||||
|
export class RunAutoCharges {
|
||||||
|
constructor(private readonly deps: RunAutoChargesDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(): Promise<RunAutoChargesResult> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now ?? new Date();
|
||||||
|
const generator = this.deps.generator ?? new GenerateMonthlyCharges({ db, now });
|
||||||
|
|
||||||
|
const settings = await db.autoChargeSettings.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
select: { ownerId: true, chargeDay: true, enabledAt: true, owner: { select: { country: true } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
const totals: RunAutoChargesResult = { due: 0, done: 0, skipped: 0, failed: 0 };
|
||||||
|
for (const entry of settings) {
|
||||||
|
if (!isAutoChargeDue(entry, now, teacherTimeZone(entry.owner.country))) continue;
|
||||||
|
totals.due += 1;
|
||||||
|
try {
|
||||||
|
const result = await generator.execute(entry.ownerId);
|
||||||
|
if (result.outcome === 'done') totals.done += 1;
|
||||||
|
if (result.outcome === 'skipped') totals.skipped += 1;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error, ownerId: entry.ownerId }, 'Automatic monthly charge failed');
|
||||||
|
totals.failed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return totals;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { MarkOverduePayments } from './mark-overdue-payments';
|
import { MarkOverduePayments } from './mark-overdue-payments';
|
||||||
import { ReconcilePayments } from './reconcile-payments';
|
import { ReconcilePayments } from './reconcile-payments';
|
||||||
|
import { RunAutoCharges } from './run-auto-charges';
|
||||||
|
|
||||||
const RECONCILE_CRON = '*/15 * * * *';
|
const RECONCILE_CRON = '*/15 * * * *';
|
||||||
const OVERDUE_CRON = '4 4 * * *';
|
const OVERDUE_CRON = '4 4 * * *';
|
||||||
|
// Hourly: each teacher's day of the month is on their own clock.
|
||||||
|
const AUTO_CHARGE_CRON = '7 * * * *';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Registers the payment background jobs. Called once from `server.ts`, following
|
* Registers the payment background jobs. Called once from `server.ts`, following
|
||||||
@@ -37,4 +40,17 @@ export function startPaymentJobs(): void {
|
|||||||
},
|
},
|
||||||
{ tz: 'UTC' },
|
{ tz: 'UTC' },
|
||||||
).unref();
|
).unref();
|
||||||
|
|
||||||
|
Bun.cron(
|
||||||
|
AUTO_CHARGE_CRON,
|
||||||
|
async () => {
|
||||||
|
try {
|
||||||
|
const totals = await new RunAutoCharges().execute();
|
||||||
|
if (totals.due > 0) logger.info(totals, 'Automatic monthly charges finished');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error }, 'Automatic monthly charges failed');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ tz: 'UTC' },
|
||||||
|
).unref();
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
* When the automatic monthly charge runs. Everything is on the teacher's clock
|
||||||
|
* (their country's time zone): the run of "December" is the one whose local
|
||||||
|
* date is in December.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** From `chargeDay` on, the run is tried for this many extra days (a server down that day). */
|
||||||
|
export const AUTO_CHARGE_CATCH_UP_DAYS = 3;
|
||||||
|
/** Local hour from which the run of the day goes out (nobody wants a link at 3 a.m.). */
|
||||||
|
export const AUTO_CHARGE_LOCAL_HOUR = 9;
|
||||||
|
|
||||||
|
export type LocalDate = { year: number; month: number; day: number; hour: number };
|
||||||
|
|
||||||
|
export function localDateIn(date: Date, timeZone: string): LocalDate {
|
||||||
|
const parts = new Intl.DateTimeFormat('en-US', {
|
||||||
|
timeZone,
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'numeric',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
hourCycle: 'h23',
|
||||||
|
}).formatToParts(date);
|
||||||
|
const value = (type: string) => Number(parts.find((part) => part.type === type)?.value ?? 0);
|
||||||
|
return { year: value('year'), month: value('month'), day: value('day'), hour: value('hour') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "2026-12": the month a run (and its fees) belongs to. */
|
||||||
|
export function monthKey(local: Pick<LocalDate, 'year' | 'month'>): string {
|
||||||
|
return `${local.year}-${String(local.month).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isoDay(year: number, month: number, day: number): string {
|
||||||
|
return new Date(Date.UTC(year, month - 1, day)).toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Due date of a fee created on `local`: `dueInDays` later, at noon UTC (a day, not an instant). */
|
||||||
|
export function autoChargeDueDate(local: LocalDate, dueInDays: number): Date {
|
||||||
|
return new Date(Date.UTC(local.year, local.month - 1, local.day + dueInDays, 12));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AutoChargeTiming = {
|
||||||
|
chargeDay: number;
|
||||||
|
/** When it was last turned on: a month whose day already passed by then is skipped. */
|
||||||
|
enabledAt: Date | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this month's run is due right now (the caller still checks that it
|
||||||
|
* did not run yet: the unique run per month does that).
|
||||||
|
*/
|
||||||
|
export function isAutoChargeDue(settings: AutoChargeTiming, now: Date, timeZone: string): boolean {
|
||||||
|
const local = localDateIn(now, timeZone);
|
||||||
|
const { chargeDay } = settings;
|
||||||
|
if (local.day < chargeDay || local.day > chargeDay + AUTO_CHARGE_CATCH_UP_DAYS) return false;
|
||||||
|
if (local.day === chargeDay && local.hour < AUTO_CHARGE_LOCAL_HOUR) return false;
|
||||||
|
return !enabledAfterChargeDay(settings, local, timeZone);
|
||||||
|
}
|
||||||
|
|
||||||
|
function enabledAfterChargeDay(settings: AutoChargeTiming, local: LocalDate, timeZone: string): boolean {
|
||||||
|
if (!settings.enabledAt) return false;
|
||||||
|
const enabled = localDateIn(settings.enabledAt, timeZone);
|
||||||
|
return monthKey(enabled) === monthKey(local) && enabled.day > settings.chargeDay;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Local date (YYYY-MM-DD) of the next run: this month's day if it is still
|
||||||
|
* ahead (or due and not run yet), next month's otherwise.
|
||||||
|
*/
|
||||||
|
export function nextAutoChargeDate(
|
||||||
|
settings: AutoChargeTiming,
|
||||||
|
now: Date,
|
||||||
|
timeZone: string,
|
||||||
|
ranThisMonth: boolean,
|
||||||
|
): string {
|
||||||
|
const local = localDateIn(now, timeZone);
|
||||||
|
const thisMonthStillAhead =
|
||||||
|
!ranThisMonth
|
||||||
|
&& !enabledAfterChargeDay(settings, local, timeZone)
|
||||||
|
&& local.day <= settings.chargeDay + AUTO_CHARGE_CATCH_UP_DAYS;
|
||||||
|
if (thisMonthStillAhead) {
|
||||||
|
return isoDay(local.year, local.month, Math.max(settings.chargeDay, local.day));
|
||||||
|
}
|
||||||
|
return isoDay(local.year, local.month + 1, settings.chargeDay);
|
||||||
|
}
|
||||||
217
apps/backend/src/modules/payments/lib/checkouts.ts
Normal file
217
apps/backend/src/modules/payments/lib/checkouts.ts
Normal file
@@ -0,0 +1,217 @@
|
|||||||
|
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { PrismaTransaction } from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
|
import {
|
||||||
|
createCheckoutPreference,
|
||||||
|
expireCheckoutPreference,
|
||||||
|
MpApiError,
|
||||||
|
searchMpPaymentByExternalReference,
|
||||||
|
} from '@/modules/mp/lib';
|
||||||
|
import { CHECKOUT_BACK_PATH } from './helpers';
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Combined Mercado Pago links (`PaymentCheckout`): one Checkout Pro preference
|
||||||
|
* that pays every fee of the same payer. Its `external_reference` is
|
||||||
|
* `chk_<checkout id>`, never a payment id, so a combined payment can't be
|
||||||
|
* mistaken for a single fee's.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const CHECKOUT_REFERENCE_PREFIX = 'chk_';
|
||||||
|
|
||||||
|
export function checkoutExternalReference(checkoutId: string): string {
|
||||||
|
return `${CHECKOUT_REFERENCE_PREFIX}${checkoutId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where Mercado Pago notifies a payment of a combined link (public: see `isPublicApiRequest`). */
|
||||||
|
export function checkoutNotificationUrl(apiOrigin: string, checkoutId: string): string {
|
||||||
|
return `${apiOrigin}/api/v1/payments/webhooks/mp/checkout/${encodeURIComponent(checkoutId)}?source_news=webhooks`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One line per fee in the checkout page: "Yoga · Juan". */
|
||||||
|
export function checkoutItemTitle(groupName: string, studentName: string): string {
|
||||||
|
return `${groupName} · ${studentName}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CheckoutLinkDeps = {
|
||||||
|
getToken?: typeof getMpAccessToken;
|
||||||
|
createPreference?: typeof createCheckoutPreference;
|
||||||
|
};
|
||||||
|
|
||||||
|
type CheckoutDb = Pick<PrismaClient, 'paymentCheckout' | 'payment'>;
|
||||||
|
|
||||||
|
export type CheckoutLinkOutcome =
|
||||||
|
| { ok: true; checkoutUrl: string }
|
||||||
|
| { ok: false; reason: 'no_token' | 'empty' | 'mp_provider_error' | 'unknown_error' };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates (or recreates) the Mercado Pago link of an OPEN checkout, from the
|
||||||
|
* fees it still has unpaid, and copies it to those fees. Creating a link never
|
||||||
|
* charges anyone, so retrying it is safe.
|
||||||
|
*/
|
||||||
|
export async function buildCheckoutLink(
|
||||||
|
db: CheckoutDb,
|
||||||
|
checkoutId: string,
|
||||||
|
context: { webOrigin: string; apiOrigin: string; accessToken?: string },
|
||||||
|
deps: CheckoutLinkDeps = {},
|
||||||
|
): Promise<CheckoutLinkOutcome> {
|
||||||
|
const checkout = await db.paymentCheckout.findUnique({
|
||||||
|
where: { id: checkoutId },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
ownerId: true,
|
||||||
|
currency: true,
|
||||||
|
status: true,
|
||||||
|
payments: {
|
||||||
|
where: { status: { in: ['PENDING', 'OVERDUE'] } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
amount: true,
|
||||||
|
group: { select: { name: true } },
|
||||||
|
attendee: { select: { person: { select: { fullName: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (checkout?.status !== 'OPEN' || checkout.payments.length === 0) {
|
||||||
|
return { ok: false, reason: 'empty' };
|
||||||
|
}
|
||||||
|
|
||||||
|
let accessToken = context.accessToken;
|
||||||
|
if (!accessToken) {
|
||||||
|
const token = await (deps.getToken ?? getMpAccessToken)(checkout.ownerId);
|
||||||
|
if (!token.ok) return { ok: false, reason: 'no_token' };
|
||||||
|
accessToken = token.value.accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = checkout.payments.map((payment) => ({
|
||||||
|
title: checkoutItemTitle(payment.group.name, payment.attendee.person.fullName),
|
||||||
|
unitPrice: Number(payment.amount.toString()),
|
||||||
|
}));
|
||||||
|
const total = items.reduce((sum, item) => sum + item.unitPrice, 0);
|
||||||
|
|
||||||
|
let preference: { id: string; initPoint: string };
|
||||||
|
try {
|
||||||
|
preference = await (deps.createPreference ?? createCheckoutPreference)(accessToken, {
|
||||||
|
title: items[0]?.title ?? '',
|
||||||
|
unitPrice: total,
|
||||||
|
items,
|
||||||
|
currencyId: checkout.currency,
|
||||||
|
externalReference: checkoutExternalReference(checkout.id),
|
||||||
|
backUrl: `${context.webOrigin}${CHECKOUT_BACK_PATH}`,
|
||||||
|
notificationUrl: checkoutNotificationUrl(context.apiOrigin, checkout.id),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof MpApiError) return { ok: false, reason: 'mp_provider_error' };
|
||||||
|
logger.error({ err: error }, 'Unexpected Mercado Pago combined preference failure');
|
||||||
|
return { ok: false, reason: 'unknown_error' };
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.paymentCheckout.update({
|
||||||
|
where: { id: checkout.id },
|
||||||
|
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id, amount: total },
|
||||||
|
});
|
||||||
|
await db.payment.updateMany({
|
||||||
|
where: { id: { in: checkout.payments.map((payment) => payment.id) } },
|
||||||
|
data: { checkoutUrl: preference.initPoint },
|
||||||
|
});
|
||||||
|
return { ok: true, checkoutUrl: preference.initPoint };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ConfirmMpCheckoutDeps = {
|
||||||
|
getToken?: typeof getMpAccessToken;
|
||||||
|
search?: typeof searchMpPaymentByExternalReference;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ConfirmMpCheckoutOutcome = 'paid' | 'unpaid' | 'no_token';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same rule as `confirmMpPayment`, for a combined link: whatever triggered it
|
||||||
|
* is never trusted, the owner's account is. An approved payment marks the
|
||||||
|
* checkout and every fee of it still unpaid as PAID. A SUPERSEDED checkout is
|
||||||
|
* still checked (it may have been paid right before it was invalidated).
|
||||||
|
* Throws `MpApiError` when Mercado Pago cannot answer.
|
||||||
|
*/
|
||||||
|
export async function confirmMpCheckout(
|
||||||
|
db: Pick<PrismaClient, '$transaction'>,
|
||||||
|
checkout: { id: string; ownerId: string },
|
||||||
|
deps: ConfirmMpCheckoutDeps = {},
|
||||||
|
): Promise<ConfirmMpCheckoutOutcome> {
|
||||||
|
const token = await (deps.getToken ?? getMpAccessToken)(checkout.ownerId);
|
||||||
|
if (!token.ok) return 'no_token';
|
||||||
|
|
||||||
|
const reference = checkoutExternalReference(checkout.id);
|
||||||
|
const found = await (deps.search ?? searchMpPaymentByExternalReference)(token.value.accessToken, reference);
|
||||||
|
if (found?.status !== 'approved' || found.externalReference !== reference) return 'unpaid';
|
||||||
|
|
||||||
|
const paidAt = found.dateApproved ? new Date(found.dateApproved) : new Date();
|
||||||
|
await db.$transaction(async (tx) => {
|
||||||
|
await tx.paymentCheckout.update({
|
||||||
|
where: { id: checkout.id },
|
||||||
|
data: { status: 'PAID', mpPaymentId: found.id, paidAt },
|
||||||
|
});
|
||||||
|
await tx.payment.updateMany({
|
||||||
|
where: { checkoutId: checkout.id, status: { in: ['PENDING', 'OVERDUE'] } },
|
||||||
|
data: { status: 'PAID', mpPaymentId: found.id, paidAt },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return 'paid';
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SupersededPreference = { ownerId: string; mpPreferenceId: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Some fees were paid outside their combined link (a confirmed transfer): the
|
||||||
|
* link would charge them again, so the checkout becomes SUPERSEDED and its fees
|
||||||
|
* lose the shared link (the teacher generates single ones from Cobros). Runs in
|
||||||
|
* the caller's transaction; the Mercado Pago preferences to expire are returned
|
||||||
|
* for `expireSupersededPreferences`, after the commit.
|
||||||
|
*/
|
||||||
|
export async function supersedeCheckoutsOf(
|
||||||
|
tx: Pick<PrismaTransaction, 'payment' | 'paymentCheckout'>,
|
||||||
|
paymentIds: string[],
|
||||||
|
): Promise<SupersededPreference[]> {
|
||||||
|
if (paymentIds.length === 0) return [];
|
||||||
|
const checkouts = await tx.paymentCheckout.findMany({
|
||||||
|
where: { status: 'OPEN', payments: { some: { id: { in: paymentIds } } } },
|
||||||
|
select: { id: true, ownerId: true, mpPreferenceId: true },
|
||||||
|
});
|
||||||
|
if (checkouts.length === 0) return [];
|
||||||
|
|
||||||
|
const ids = checkouts.map((checkout) => checkout.id);
|
||||||
|
await tx.paymentCheckout.updateMany({ where: { id: { in: ids }, status: 'OPEN' }, data: { status: 'SUPERSEDED' } });
|
||||||
|
await tx.payment.updateMany({ where: { checkoutId: { in: ids } }, data: { checkoutUrl: null } });
|
||||||
|
|
||||||
|
return checkouts.flatMap((checkout) =>
|
||||||
|
checkout.mpPreferenceId ? [{ ownerId: checkout.ownerId, mpPreferenceId: checkout.mpPreferenceId }] : [],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ExpirePreferencesDeps = {
|
||||||
|
getToken?: typeof getMpAccessToken;
|
||||||
|
expire?: typeof expireCheckoutPreference;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Best effort: a link that could not be expired is still caught by the reconciliation. */
|
||||||
|
export async function expireSupersededPreferences(
|
||||||
|
preferences: SupersededPreference[],
|
||||||
|
deps: ExpirePreferencesDeps = {},
|
||||||
|
): Promise<void> {
|
||||||
|
for (const preference of preferences) {
|
||||||
|
try {
|
||||||
|
const token = await (deps.getToken ?? getMpAccessToken)(preference.ownerId);
|
||||||
|
if (!token.ok) continue;
|
||||||
|
await (deps.expire ?? expireCheckoutPreference)(token.value.accessToken, preference.mpPreferenceId);
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn({ err: error }, 'Could not expire a superseded Mercado Pago link');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const checkoutSummarySelect = {
|
||||||
|
id: true,
|
||||||
|
amount: true,
|
||||||
|
status: true,
|
||||||
|
_count: { select: { payments: true } },
|
||||||
|
} satisfies Prisma.PaymentCheckoutSelect;
|
||||||
45
apps/backend/src/modules/payments/lib/confirm-mp-payment.ts
Normal file
45
apps/backend/src/modules/payments/lib/confirm-mp-payment.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
|
import { searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
||||||
|
|
||||||
|
export type ConfirmMpPaymentDeps = {
|
||||||
|
getToken?: typeof getMpAccessToken;
|
||||||
|
search?: typeof searchMpPaymentByExternalReference;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** `no_token`: the owner has no usable Mercado Pago link (not linked, or needs re-auth). */
|
||||||
|
export type ConfirmMpPaymentOutcome = 'paid' | 'unpaid' | 'no_token';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asks the owner's Mercado Pago account whether this payment was approved and,
|
||||||
|
* if so, marks it PAID. The only rule for a Checkout Pro payment, shared by the
|
||||||
|
* polling job and the notification: whatever triggered it is never trusted, the
|
||||||
|
* owner's account is. Throws `MpApiError` when Mercado Pago cannot answer.
|
||||||
|
*/
|
||||||
|
export async function confirmMpPayment(
|
||||||
|
db: Pick<PrismaClient, 'payment'>,
|
||||||
|
payment: { id: string; ownerId: string },
|
||||||
|
deps: ConfirmMpPaymentDeps = {},
|
||||||
|
): Promise<ConfirmMpPaymentOutcome> {
|
||||||
|
const token = await (deps.getToken ?? getMpAccessToken)(payment.ownerId);
|
||||||
|
if (!token.ok) return 'no_token';
|
||||||
|
|
||||||
|
const found = await (deps.search ?? searchMpPaymentByExternalReference)(token.value.accessToken, payment.id);
|
||||||
|
if (found?.status !== 'approved' || found.externalReference !== payment.id) return 'unpaid';
|
||||||
|
|
||||||
|
await db.payment.update({
|
||||||
|
where: { id: payment.id },
|
||||||
|
data: {
|
||||||
|
status: 'PAID',
|
||||||
|
mpPaymentId: found.id,
|
||||||
|
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return 'paid';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where Mercado Pago notifies a payment of this link (public: see `isPublicApiRequest`). */
|
||||||
|
export function paymentNotificationUrl(apiOrigin: string, paymentId: string): string {
|
||||||
|
// `source_news=webhooks`: only the webhook format, not the legacy IPN copy.
|
||||||
|
return `${apiOrigin}/api/v1/payments/webhooks/mp/${encodeURIComponent(paymentId)}?source_news=webhooks`;
|
||||||
|
}
|
||||||
@@ -1,9 +1,17 @@
|
|||||||
|
import type { Prisma } from '@generated/prisma/client';
|
||||||
import type { PaymentDto } from '@gruperly/shared';
|
import type { PaymentDto } from '@gruperly/shared';
|
||||||
|
|
||||||
/* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app
|
/* Where Mercado Pago sends whoever paid a Checkout Pro link: the student app
|
||||||
(without a student session it falls through to /access). */
|
(without a student session it falls through to /access). */
|
||||||
export const CHECKOUT_BACK_PATH = '/student/payments';
|
export const CHECKOUT_BACK_PATH = '/student/payments';
|
||||||
|
|
||||||
|
/** What `toPaymentDto` reads besides the payment's own columns. */
|
||||||
|
export const paymentDtoInclude = {
|
||||||
|
attendee: { select: { person: { select: { fullName: true } } } },
|
||||||
|
group: { select: { name: true, price: true } },
|
||||||
|
checkout: { select: { _count: { select: { payments: true } } } },
|
||||||
|
} satisfies Prisma.PaymentInclude;
|
||||||
|
|
||||||
export type PaymentRecord = {
|
export type PaymentRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
groupId: string;
|
groupId: string;
|
||||||
@@ -13,6 +21,9 @@ export type PaymentRecord = {
|
|||||||
status: PaymentDto['status'];
|
status: PaymentDto['status'];
|
||||||
description: string | null;
|
description: string | null;
|
||||||
checkoutUrl: string | null;
|
checkoutUrl: string | null;
|
||||||
|
checkoutId?: string | null;
|
||||||
|
periodKey?: string | null;
|
||||||
|
checkout?: { _count: { payments: number } } | null;
|
||||||
dueDate: Date;
|
dueDate: Date;
|
||||||
paidAt: Date | null;
|
paidAt: Date | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
@@ -33,6 +44,9 @@ export function toPaymentDto(record: PaymentRecord): PaymentDto {
|
|||||||
status: record.status,
|
status: record.status,
|
||||||
description: record.description,
|
description: record.description,
|
||||||
checkoutUrl: record.checkoutUrl,
|
checkoutUrl: record.checkoutUrl,
|
||||||
|
checkoutId: record.checkoutId ?? null,
|
||||||
|
checkoutItemCount: record.checkout?._count.payments ?? null,
|
||||||
|
periodKey: record.periodKey ?? null,
|
||||||
dueDate: record.dueDate.toISOString(),
|
dueDate: record.dueDate.toISOString(),
|
||||||
paidAt: record.paidAt ? record.paidAt.toISOString() : null,
|
paidAt: record.paidAt ? record.paidAt.toISOString() : null,
|
||||||
createdAt: record.createdAt.toISOString(),
|
createdAt: record.createdAt.toISOString(),
|
||||||
|
|||||||
@@ -1 +1,22 @@
|
|||||||
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';
|
export {
|
||||||
|
buildCheckoutLink,
|
||||||
|
type CheckoutLinkDeps,
|
||||||
|
type CheckoutLinkOutcome,
|
||||||
|
type ConfirmMpCheckoutDeps,
|
||||||
|
type ConfirmMpCheckoutOutcome,
|
||||||
|
checkoutExternalReference,
|
||||||
|
checkoutItemTitle,
|
||||||
|
checkoutNotificationUrl,
|
||||||
|
confirmMpCheckout,
|
||||||
|
type ExpirePreferencesDeps,
|
||||||
|
expireSupersededPreferences,
|
||||||
|
type SupersededPreference,
|
||||||
|
supersedeCheckoutsOf,
|
||||||
|
} from './checkouts';
|
||||||
|
export {
|
||||||
|
type ConfirmMpPaymentDeps,
|
||||||
|
type ConfirmMpPaymentOutcome,
|
||||||
|
confirmMpPayment,
|
||||||
|
paymentNotificationUrl,
|
||||||
|
} from './confirm-mp-payment';
|
||||||
|
export { CHECKOUT_BACK_PATH, type PaymentRecord, paymentDtoInclude, toPaymentDto } from './helpers';
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
|
import autoChargeSettingsRoute from './features/auto-charge-settings/route';
|
||||||
import getAllRoute from './features/get-all/route';
|
import getAllRoute from './features/get-all/route';
|
||||||
import renewRoute from './features/renew/route';
|
import renewRoute from './features/renew/route';
|
||||||
import reportedRoute from './features/reported/route';
|
import reportedRoute from './features/reported/route';
|
||||||
import transferDetailsRoute from './features/transfer-details/route';
|
import transferDetailsRoute from './features/transfer-details/route';
|
||||||
|
import webhookRoute from './features/webhook/route';
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
|
|
||||||
routes.route('/', getAllRoute);
|
routes.route('/', getAllRoute);
|
||||||
|
routes.route('/', autoChargeSettingsRoute);
|
||||||
routes.route('/', reportedRoute);
|
routes.route('/', reportedRoute);
|
||||||
routes.route('/', transferDetailsRoute);
|
routes.route('/', transferDetailsRoute);
|
||||||
routes.route('/', renewRoute);
|
routes.route('/', renewRoute);
|
||||||
|
routes.route('/', webhookRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
21
apps/backend/src/modules/people/lib/guardians.ts
Normal file
21
apps/backend/src/modules/people/lib/guardians.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
/* Kept apart from `people.ts` (no imports): `attendees/lib/helpers.ts` spreads
|
||||||
|
`guardianSelect` at load time and `people.ts` imports from it. */
|
||||||
|
|
||||||
|
/* The adult in charge of a kid (`PersonGuardian`). One per kid in v1: the
|
||||||
|
oldest link wins if there were ever more. */
|
||||||
|
export const guardianSelect = {
|
||||||
|
guardians: {
|
||||||
|
take: 1,
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { guardian: { select: { id: true, fullName: true, phone: true, email: true } } },
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type GuardianContact = { id: string; fullName: string; phone: string | null; email: string | null };
|
||||||
|
export type WithGuardians = { guardians?: { guardian: Partial<GuardianContact> & { phone: string | null } }[] };
|
||||||
|
|
||||||
|
export function primaryGuardian<T extends { phone: string | null }>(person: {
|
||||||
|
guardians?: { guardian: T }[];
|
||||||
|
}): T | null {
|
||||||
|
return person.guardians?.[0]?.guardian ?? null;
|
||||||
|
}
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
import { Prisma, type PrismaClient } from '@generated/prisma/client';
|
||||||
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
|
import type { PersonMembership, PersonSummary, ProblemDetails } from '@gruperly/shared';
|
||||||
import { conflictProblem } from '@/http/problem-builders';
|
import { conflictProblem } from '@/http/problem-builders';
|
||||||
|
import { problemDetails } from '@/http/problem-details';
|
||||||
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
import { normalizePhone } from '@/modules/attendees/lib/helpers';
|
||||||
|
import { primaryGuardian, type WithGuardians } from './guardians';
|
||||||
|
|
||||||
|
export { type GuardianContact, guardianSelect, primaryGuardian, type WithGuardians } from './guardians';
|
||||||
|
|
||||||
/* A person is the teacher's contact (student, or a guardian's child); their
|
/* A person is the teacher's contact (student, or a guardian's child); their
|
||||||
`attendees` are the memberships in each group. The phone is unique per
|
`attendees` are the memberships in each group. The phone is unique per
|
||||||
@@ -60,12 +64,27 @@ export async function findPersonSummaryByPhone(
|
|||||||
): Promise<PersonSummary | null> {
|
): Promise<PersonSummary | null> {
|
||||||
const person = await findPersonByPhone(db, ownerId, rawPhone);
|
const person = await findPersonByPhone(db, ownerId, rawPhone);
|
||||||
if (!person) return null;
|
if (!person) return null;
|
||||||
|
// When the phone is an adult in charge, the add form offers their kids.
|
||||||
|
const links = await db.person.findUnique({
|
||||||
|
where: { id: person.id },
|
||||||
|
select: {
|
||||||
|
children: {
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { child: { select: { id: true, fullName: true, ...personMembershipsSelect } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
id: person.id,
|
id: person.id,
|
||||||
fullName: person.fullName,
|
fullName: person.fullName,
|
||||||
email: person.email,
|
email: person.email,
|
||||||
phone: person.phone,
|
phone: person.phone,
|
||||||
groups: toMemberships(person.attendees),
|
groups: toMemberships(person.attendees),
|
||||||
|
children: (links?.children ?? []).map(({ child }) => ({
|
||||||
|
id: child.id,
|
||||||
|
fullName: child.fullName,
|
||||||
|
groups: toMemberships(child.attendees),
|
||||||
|
})),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,9 +128,24 @@ export async function countsAsNewStudent(db: PeopleDb, ownerId: string, rawPhone
|
|||||||
return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
|
return !person?.attendees.some((membership) => membership.status === 'ACTIVE');
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The number the teacher reaches the person on: theirs, or the guardian's. */
|
/* The number the teacher reaches the person on: the adult in charge when there
|
||||||
export function contactPhone(person: { phone: string | null; guardianPhone: string | null }): string | null {
|
is one (a kid's own phone, if any, is not who answers for them), else theirs. */
|
||||||
return person.phone ?? person.guardianPhone;
|
export function contactPhone(person: { phone: string | null } & WithGuardians): string | null {
|
||||||
|
return primaryGuardian(person)?.phone ?? person.phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The adult in charge, found by phone among the teacher's people (their stored
|
||||||
|
data wins, like any other person) or created. */
|
||||||
|
export async function findOrCreateGuardian(
|
||||||
|
db: PeopleDb,
|
||||||
|
ownerId: string,
|
||||||
|
data: { fullName: string; phone: string; email?: string | null },
|
||||||
|
): Promise<{ id: string; created: boolean }> {
|
||||||
|
return findOrCreatePerson(db, ownerId, {
|
||||||
|
fullName: data.fullName.trim(),
|
||||||
|
phone: normalizePhone(data.phone),
|
||||||
|
email: data.email?.trim() || null,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isUniqueViolation(error: unknown): boolean {
|
export function isUniqueViolation(error: unknown): boolean {
|
||||||
@@ -134,6 +168,16 @@ export function personExistsProblem(): ProblemDetails {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A kids group: each new kid needs the adult in charge. */
|
||||||
|
export function guardianRequiredProblem(): ProblemDetails {
|
||||||
|
return problemDetails({
|
||||||
|
title: 'Bad Request',
|
||||||
|
status: 400,
|
||||||
|
detail: 'En un grupo de chicos tenés que cargar al adulto a cargo.',
|
||||||
|
code: 'guardian_required',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function personPhoneTakenProblem(): ProblemDetails {
|
export function personPhoneTakenProblem(): ProblemDetails {
|
||||||
return conflictProblem({
|
return conflictProblem({
|
||||||
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
|
detail: 'Otra persona que tenés registrada ya usa este número de teléfono.',
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { err, ok } from '@gruperly/shared';
|
|||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
|
import { guardianSelect } from '@/modules/people/lib/guardians';
|
||||||
import { computeStudentAccess } from '../../lib/status';
|
import { computeStudentAccess } from '../../lib/status';
|
||||||
|
|
||||||
type GetStudentAccessDeps = {
|
type GetStudentAccessDeps = {
|
||||||
@@ -23,9 +24,14 @@ export class GetStudentAccess {
|
|||||||
const access = await findGroupForUser(db, groupId, userId);
|
const access = await findGroupForUser(db, groupId, userId);
|
||||||
if (!access.ok) return access;
|
if (!access.ok) return access;
|
||||||
|
|
||||||
const attendee = await db.attendee.findFirst({ where: { id: attendeeId, groupId }, select: { personId: true } });
|
const attendee = await db.attendee.findFirst({
|
||||||
|
where: { id: attendeeId, groupId },
|
||||||
|
select: { personId: true, person: { select: guardianSelect } },
|
||||||
|
});
|
||||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
|
||||||
return ok(await computeStudentAccess(db, attendee.personId, this.deps.now ?? new Date()));
|
// A kid with an adult in charge uses the adult's account (shared by siblings).
|
||||||
|
const ownerId = attendee.person.guardians[0]?.guardian.id ?? attendee.personId;
|
||||||
|
return ok(await computeStudentAccess(db, ownerId, this.deps.now ?? new Date()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
|
import type { ProblemDetails, Result, StudentInvitationDto } from '@gruperly/shared';
|
||||||
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
|
import { type CountryCode, err, INVITATION_TTL_HOURS, ok, toWhatsappE164 } from '@gruperly/shared';
|
||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma, { UnitOfWork } from '@/lib/prisma';
|
import prisma, { UnitOfWork } from '@/lib/prisma';
|
||||||
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
import { findGroupForUser } from '@/modules/group-waitlist/lib/helpers';
|
||||||
import { contactPhone } from '@/modules/people/lib/people';
|
import { contactPhone, guardianSelect, primaryGuardian } from '@/modules/people/lib/people';
|
||||||
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
import { generateAccessToken, hashToken, studentLinkUrl } from '@/modules/student-portal/lib';
|
||||||
import { computeStudentAccess } from '../../lib/status';
|
import { computeStudentAccess } from '../../lib/status';
|
||||||
|
|
||||||
@@ -38,36 +38,25 @@ export class InviteStudent {
|
|||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
personId: true,
|
personId: true,
|
||||||
person: { select: { fullName: true, phone: true, guardianPhone: true } },
|
person: { select: { fullName: true, phone: true, ...guardianSelect } },
|
||||||
group: { select: { owner: { select: { country: true } } } },
|
group: { select: { owner: { select: { country: true } } } },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
if (!attendee) return err(notFoundResourceProblem('Attendee', attendeeId));
|
||||||
|
|
||||||
|
// The account belongs to the adult in charge when the kid has one: it
|
||||||
|
// reaches all of their kids.
|
||||||
|
const guardian = primaryGuardian(attendee.person);
|
||||||
|
const owner = guardian
|
||||||
|
? { personId: guardian.id, fullName: guardian.fullName }
|
||||||
|
: { personId: attendee.personId, fullName: attendee.person.fullName };
|
||||||
|
|
||||||
const token = generateAccessToken();
|
const token = generateAccessToken();
|
||||||
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
|
const expiresAt = new Date(now.getTime() + INVITATION_TTL_HOURS * 60 * 60 * 1000);
|
||||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma as PrismaClient);
|
||||||
|
|
||||||
const issued = await unitOfWork.executeResult(async (tx) => {
|
const issued = await unitOfWork.executeResult(async (tx) => {
|
||||||
// One account per person: inviting from any of their groups reuses it.
|
const accountId = await resolveAccount(tx, owner, userId);
|
||||||
const link = await tx.studentAccountPerson.findFirst({
|
|
||||||
where: { personId: attendee.personId },
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: { accountId: true },
|
|
||||||
});
|
|
||||||
const accountId =
|
|
||||||
link?.accountId
|
|
||||||
?? (
|
|
||||||
await tx.studentAccount.create({
|
|
||||||
data: {
|
|
||||||
name: attendee.person.fullName,
|
|
||||||
createdById: userId,
|
|
||||||
people: { create: { personId: attendee.personId } },
|
|
||||||
},
|
|
||||||
select: { id: true },
|
|
||||||
})
|
|
||||||
).id;
|
|
||||||
|
|
||||||
await tx.studentAccessToken.updateMany({
|
await tx.studentAccessToken.updateMany({
|
||||||
where: { accountId, usedAt: null, revokedAt: null },
|
where: { accountId, usedAt: null, revokedAt: null },
|
||||||
data: { revokedAt: now },
|
data: { revokedAt: now },
|
||||||
@@ -96,7 +85,7 @@ export class InviteStudent {
|
|||||||
url: studentLinkUrl(token),
|
url: studentLinkUrl(token),
|
||||||
expiresAt: expiresAt.toISOString(),
|
expiresAt: expiresAt.toISOString(),
|
||||||
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
|
whatsappPhone: toWhatsappPhone(contactPhone(attendee.person), attendee.group.owner.country),
|
||||||
access: await computeStudentAccess(db, attendee.personId, now),
|
access: await computeStudentAccess(db, owner.personId, now),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -104,3 +93,52 @@ export class InviteStudent {
|
|||||||
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
|
function toWhatsappPhone(phone: string | null, country: string | null): string | null {
|
||||||
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
|
return phone ? toWhatsappE164(phone, country as CountryCode | null) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type AccountOwner = { personId: string; fullName: string };
|
||||||
|
|
||||||
|
/* One account per person: inviting from any of their groups (or, for an adult
|
||||||
|
in charge, from any of their kids) reuses it. Accounts made before kids
|
||||||
|
groups were linked to the kid: the oldest one of the adult's kids moves to
|
||||||
|
the adult, and the kids stop being linked one by one (they are reached
|
||||||
|
through `person_guardians`). */
|
||||||
|
async function resolveAccount(tx: Prisma.TransactionClient, owner: AccountOwner, userId: string): Promise<string> {
|
||||||
|
const kids = await tx.personGuardian.findMany({ where: { guardianId: owner.personId }, select: { childId: true } });
|
||||||
|
const kidIds = kids.map((kid) => kid.childId);
|
||||||
|
|
||||||
|
const own = await tx.studentAccountPerson.findFirst({
|
||||||
|
where: { personId: owner.personId },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { accountId: true },
|
||||||
|
});
|
||||||
|
const legacy =
|
||||||
|
own || kidIds.length === 0
|
||||||
|
? null
|
||||||
|
: await tx.studentAccountPerson.findFirst({
|
||||||
|
where: { personId: { in: kidIds } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: { accountId: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
let accountId: string;
|
||||||
|
if (own) {
|
||||||
|
accountId = own.accountId;
|
||||||
|
} else if (legacy) {
|
||||||
|
accountId = legacy.accountId;
|
||||||
|
await tx.studentAccount.update({
|
||||||
|
where: { id: accountId },
|
||||||
|
data: { name: owner.fullName, people: { create: { personId: owner.personId } } },
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
accountId = (
|
||||||
|
await tx.studentAccount.create({
|
||||||
|
data: { name: owner.fullName, createdById: userId, people: { create: { personId: owner.personId } } },
|
||||||
|
select: { id: true },
|
||||||
|
})
|
||||||
|
).id;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kidIds.length > 0) {
|
||||||
|
await tx.studentAccountPerson.deleteMany({ where: { personId: { in: kidIds } } });
|
||||||
|
}
|
||||||
|
return accountId;
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { occurrencesBetween } from '@/modules/home/lib/scheduler';
|
|||||||
import {
|
import {
|
||||||
classAlreadyStartedProblem,
|
classAlreadyStartedProblem,
|
||||||
findLinkedAttendee,
|
findLinkedAttendee,
|
||||||
|
linkedPersonWhere,
|
||||||
studentAttendeeNotFoundProblem,
|
studentAttendeeNotFoundProblem,
|
||||||
teacherTimeZone,
|
teacherTimeZone,
|
||||||
} from '../../lib';
|
} from '../../lib';
|
||||||
@@ -127,7 +128,7 @@ export class CancelStudentAbsence {
|
|||||||
where: {
|
where: {
|
||||||
id: noticeId,
|
id: noticeId,
|
||||||
cancelledAt: null,
|
cancelledAt: null,
|
||||||
attendee: { status: { not: 'DROPPED' }, person: { studentAccounts: { some: { accountId } } } },
|
attendee: { status: { not: 'DROPPED' }, person: linkedPersonWhere(accountId) },
|
||||||
},
|
},
|
||||||
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
select: { id: true, attendeeId: true, classSessionId: true, classSession: { select: { startsAt: true } } },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -40,6 +40,21 @@ export class GetStudentFees {
|
|||||||
dueDate: true,
|
dueDate: true,
|
||||||
status: true,
|
status: true,
|
||||||
checkoutUrl: true,
|
checkoutUrl: true,
|
||||||
|
periodKey: true,
|
||||||
|
checkout: {
|
||||||
|
select: {
|
||||||
|
status: true,
|
||||||
|
amount: true,
|
||||||
|
payments: {
|
||||||
|
where: { status: { in: ['PENDING', 'OVERDUE'] } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
group: { select: { name: true } },
|
||||||
|
attendee: { select: { person: { select: { fullName: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } },
|
reportedItems: { where: { reportedPayment: { status: 'REPORTED' } }, select: { paymentId: true } },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
@@ -76,6 +91,17 @@ export class GetStudentFees {
|
|||||||
dueDate: payment.dueDate.toISOString(),
|
dueDate: payment.dueDate.toISOString(),
|
||||||
status,
|
status,
|
||||||
checkoutUrl: payment.checkoutUrl,
|
checkoutUrl: payment.checkoutUrl,
|
||||||
|
periodKey: payment.periodKey,
|
||||||
|
checkout:
|
||||||
|
payment.checkout?.status === 'OPEN' && payment.checkout.payments.length > 1
|
||||||
|
? {
|
||||||
|
total: payment.checkout.amount.toNumber(),
|
||||||
|
items: payment.checkout.payments.map((line) => ({
|
||||||
|
groupName: line.group.name,
|
||||||
|
studentName: line.attendee.person.fullName,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
: null,
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null,
|
transfer: transferAlias ? { alias: transferAlias, holder: transferHolder } : null,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
|
import type { ProblemDetails, Result, StudentLinkInfo } from '@gruperly/shared';
|
||||||
import { ok } from '@gruperly/shared';
|
import { ok } from '@gruperly/shared';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
@@ -9,6 +9,13 @@ type GetStudentLinkInfoDeps = {
|
|||||||
now?: Date;
|
now?: Date;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const firstGroupSelect = {
|
||||||
|
where: { status: { not: 'DROPPED' } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
take: 1,
|
||||||
|
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
|
||||||
|
} satisfies Prisma.Person$attendeesArgs;
|
||||||
|
|
||||||
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
||||||
|
|
||||||
/* GET of the link: only reads, never consumes (WhatsApp previews and link
|
/* GET of the link: only reads, never consumes (WhatsApp previews and link
|
||||||
@@ -38,10 +45,12 @@ export class GetStudentLinkInfo {
|
|||||||
select: {
|
select: {
|
||||||
person: {
|
person: {
|
||||||
select: {
|
select: {
|
||||||
attendees: {
|
attendees: firstGroupSelect,
|
||||||
|
// An adult in charge has no groups of their own: their kids' count.
|
||||||
|
children: {
|
||||||
orderBy: { createdAt: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
take: 1,
|
take: 1,
|
||||||
select: { group: { select: { name: true, owner: { select: { name: true } } } } },
|
select: { child: { select: { attendees: firstGroupSelect } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -62,7 +71,9 @@ export class GetStudentLinkInfo {
|
|||||||
return ok({ status: 'invalid' });
|
return ok({ status: 'invalid' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const group = row.account.people[0]?.person.attendees[0]?.group ?? null;
|
const person = row.account.people[0]?.person;
|
||||||
|
const group =
|
||||||
|
person?.attendees[0]?.group ?? person?.children[0]?.child.attendees[0]?.group ?? null;
|
||||||
return ok({
|
return ok({
|
||||||
status: 'valid',
|
status: 'valid',
|
||||||
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
kind: row.kind === 'INVITATION' ? 'invitation' : 'recovery',
|
||||||
|
|||||||
@@ -1,9 +1,44 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
|
import type { ProblemDetails, Result, StudentMe } from '@gruperly/shared';
|
||||||
import { err, ok } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import { unauthorizedProblem } from '@/http/problem-details';
|
import { unauthorizedProblem } from '@/http/problem-details';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
|
||||||
|
const personGroupsSelect = {
|
||||||
|
fullName: true,
|
||||||
|
attendees: {
|
||||||
|
where: { status: { not: 'DROPPED' } },
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies Prisma.PersonSelect;
|
||||||
|
|
||||||
|
type PersonGroups = Prisma.PersonGetPayload<{ select: typeof personGroupsSelect }>;
|
||||||
|
|
||||||
|
/* One entry per membership; a kid reached twice (linked and through the adult)
|
||||||
|
shows up once. */
|
||||||
|
function studentsOf(people: PersonGroups[]): StudentMe['students'] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
return people.flatMap((person) =>
|
||||||
|
person.attendees.flatMap((attendee) => {
|
||||||
|
if (seen.has(attendee.id)) return [];
|
||||||
|
seen.add(attendee.id);
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
attendeeId: attendee.id,
|
||||||
|
fullName: person.fullName,
|
||||||
|
groupId: attendee.group.id,
|
||||||
|
groupName: attendee.group.name,
|
||||||
|
teacherName: attendee.group.owner.name,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
|
type StudentMeDeps = { db?: Pick<PrismaClient, 'studentAccount'>; now?: Date };
|
||||||
|
|
||||||
export class GetStudentMe {
|
export class GetStudentMe {
|
||||||
@@ -20,21 +55,15 @@ export class GetStudentMe {
|
|||||||
pendingRecoveryEmail: true,
|
pendingRecoveryEmail: true,
|
||||||
welcomedAt: true,
|
welcomedAt: true,
|
||||||
_count: { select: { passkeys: true } },
|
_count: { select: { passkeys: true } },
|
||||||
// Linked people, and every group each of them is in.
|
// Linked people (and the kids of a linked adult in charge), and every
|
||||||
|
// group each of them is in.
|
||||||
people: {
|
people: {
|
||||||
orderBy: { createdAt: 'asc' },
|
orderBy: { createdAt: 'asc' },
|
||||||
select: {
|
select: {
|
||||||
person: {
|
person: {
|
||||||
select: {
|
select: {
|
||||||
fullName: true,
|
...personGroupsSelect,
|
||||||
attendees: {
|
children: { orderBy: { createdAt: 'asc' }, select: { child: { select: personGroupsSelect } } },
|
||||||
where: { status: { not: 'DROPPED' } },
|
|
||||||
orderBy: { createdAt: 'asc' },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
group: { select: { id: true, name: true, owner: { select: { name: true } } } },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -52,15 +81,7 @@ export class GetStudentMe {
|
|||||||
hasPasskey: account._count.passkeys > 0,
|
hasPasskey: account._count.passkeys > 0,
|
||||||
welcomed: account.welcomedAt !== null,
|
welcomed: account.welcomedAt !== null,
|
||||||
},
|
},
|
||||||
students: account.people.flatMap(({ person }) =>
|
students: studentsOf(account.people.flatMap(({ person }) => [person, ...person.children.map(({ child }) => child)])),
|
||||||
person.attendees.map((attendee) => ({
|
|
||||||
attendeeId: attendee.id,
|
|
||||||
fullName: person.fullName,
|
|
||||||
groupId: attendee.group.id,
|
|
||||||
groupName: attendee.group.name,
|
|
||||||
teacherName: attendee.group.owner.name,
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,29 @@ import type { Prisma } from '@generated/prisma/client';
|
|||||||
|
|
||||||
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
export type LinkedAttendeeDb = { attendee: Prisma.AttendeeDelegate };
|
||||||
|
|
||||||
|
/* The people a student account reaches: the ones linked to it and the kids of
|
||||||
|
a linked adult in charge (kids groups). Kids are not linked one by one, so a
|
||||||
|
kid added later shows up without a new invitation. */
|
||||||
|
export function linkedPersonWhere(accountId: string): Prisma.PersonWhereInput {
|
||||||
|
return {
|
||||||
|
OR: [
|
||||||
|
{ studentAccounts: { some: { accountId } } },
|
||||||
|
{ guardians: { some: { guardian: { studentAccounts: { some: { accountId } } } } } },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/* The authorization rule of every student endpoint: an attendee (membership)
|
/* The authorization rule of every student endpoint: an attendee (membership)
|
||||||
of a person linked to the session's account, with what the student screens
|
of a person linked to the session's account, with what the student screens
|
||||||
need from the group. The account is linked to the person, so every group
|
need from the group. The account is linked to the person (or to their adult
|
||||||
they are in shows up. null for anything else (or DROPPED; PAUSED keeps
|
in charge), so every group they are in shows up. null for anything else (or DROPPED; PAUSED keeps
|
||||||
access): routes answer 404, the same as for an id that doesn't exist. */
|
access): routes answer 404, the same as for an id that doesn't exist. */
|
||||||
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
export async function findLinkedAttendee(db: LinkedAttendeeDb, accountId: string, attendeeId: string) {
|
||||||
return db.attendee.findFirst({
|
return db.attendee.findFirst({
|
||||||
where: {
|
where: {
|
||||||
id: attendeeId,
|
id: attendeeId,
|
||||||
status: { not: 'DROPPED' },
|
status: { not: 'DROPPED' },
|
||||||
person: { studentAccounts: { some: { accountId } } },
|
person: linkedPersonWhere(accountId),
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import type { PrismaClient } from '@generated/prisma/client';
|
|||||||
import type {
|
import type {
|
||||||
ProblemDetails,
|
ProblemDetails,
|
||||||
Result,
|
Result,
|
||||||
WhatsappReadiness,
|
|
||||||
WhatsappStatusDto,
|
WhatsappStatusDto,
|
||||||
} from '@gruperly/shared';
|
} from '@gruperly/shared';
|
||||||
import { ok } from '@gruperly/shared';
|
import { ok } from '@gruperly/shared';
|
||||||
@@ -21,6 +20,7 @@ type GetWhatsappStatusDeps = {
|
|||||||
const BLOCKED: WhatsappStatusDto['readiness'] = {
|
const BLOCKED: WhatsappStatusDto['readiness'] = {
|
||||||
PAYMENT_REMINDER: 'blocked',
|
PAYMENT_REMINDER: 'blocked',
|
||||||
REENGAGEMENT: 'blocked',
|
REENGAGEMENT: 'blocked',
|
||||||
|
PAYMENT_LINK: 'blocked',
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -80,6 +80,7 @@ export class GetWhatsappStatus {
|
|||||||
? {
|
? {
|
||||||
PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'),
|
PAYMENT_REMINDER: await provider.readiness(account, 'PAYMENT_REMINDER'),
|
||||||
REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'),
|
REENGAGEMENT: await provider.readiness(account, 'REENGAGEMENT'),
|
||||||
|
PAYMENT_LINK: await provider.readiness(account, 'PAYMENT_LINK'),
|
||||||
}
|
}
|
||||||
: BLOCKED;
|
: BLOCKED;
|
||||||
|
|
||||||
@@ -91,7 +92,7 @@ function dto(
|
|||||||
provider: MessagingProvider,
|
provider: MessagingProvider,
|
||||||
account: WhatsappAccountRecord & { connectedAt?: Date | null } | null,
|
account: WhatsappAccountRecord & { connectedAt?: Date | null } | null,
|
||||||
qrCode: string | null,
|
qrCode: string | null,
|
||||||
readiness: Record<'PAYMENT_REMINDER' | 'REENGAGEMENT', WhatsappReadiness>,
|
readiness: WhatsappStatusDto['readiness'],
|
||||||
): WhatsappStatusDto {
|
): WhatsappStatusDto {
|
||||||
const status = toVisibleWhatsappStatus(account, provider.id);
|
const status = toVisibleWhatsappStatus(account, provider.id);
|
||||||
return {
|
return {
|
||||||
|
|||||||
128
apps/backend/src/modules/whatsapp/jobs/send-payment-links.ts
Normal file
128
apps/backend/src/modules/whatsapp/jobs/send-payment-links.ts
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { countryCodeSchema } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
|
import { type DispatchItem, type DispatchTotals, dispatchForAccount, emptyTotals, sendIntervalFromEnv, sleep } from '../lib/dispatch';
|
||||||
|
import { formatAmount, formatDueDate } from '../lib/format';
|
||||||
|
import { firstNameOf } from '../lib/render-message';
|
||||||
|
import { getMessagingProvider } from '../providers';
|
||||||
|
import type { MessagingProvider } from '../providers/messaging-provider';
|
||||||
|
|
||||||
|
type SendPaymentLinksDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'whatsappAccount' | 'paymentCheckout' | 'outboundMessage' | 'user'>;
|
||||||
|
provider?: MessagingProvider;
|
||||||
|
planGuard?: Pick<PlanGuard, 'hasFeature'>;
|
||||||
|
now?: Date;
|
||||||
|
intervalMs?: number;
|
||||||
|
sleep?: (ms: number) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** "Yoga (Juan), Natación (Ana) y Pilates": what a combined link pays, in Spanish like the rest of the message. */
|
||||||
|
export function paymentLinkDetail(
|
||||||
|
payerId: string,
|
||||||
|
lines: { groupName: string; personId: string; fullName: string }[],
|
||||||
|
): string {
|
||||||
|
const parts = lines.map((line) =>
|
||||||
|
line.personId === payerId ? line.groupName : `${line.groupName} (${firstNameOf(line.fullName)})`,
|
||||||
|
);
|
||||||
|
if (parts.length <= 1) return parts[0] ?? '';
|
||||||
|
return `${parts.slice(0, -1).join(', ')} y ${parts.at(-1)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends each payer the combined link of this month's automatic charge, right
|
||||||
|
* after it is generated. Same gates as the weekly automations: the teacher's
|
||||||
|
* WhatsApp linked with the active provider, the Pro plan and, for Kapso, the
|
||||||
|
* approved template. One message per checkout and month (`outbound_messages`).
|
||||||
|
*/
|
||||||
|
export class SendPaymentLinks {
|
||||||
|
constructor(private readonly deps: SendPaymentLinksDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(ownerId: string, checkoutIds: string[]): Promise<DispatchTotals> {
|
||||||
|
if (checkoutIds.length === 0) return emptyTotals();
|
||||||
|
|
||||||
|
const providerResult = this.deps.provider ? { ok: true as const, value: this.deps.provider } : getMessagingProvider();
|
||||||
|
if (!providerResult.ok) {
|
||||||
|
logger.warn('WhatsApp is not configured; payment links not sent');
|
||||||
|
return emptyTotals();
|
||||||
|
}
|
||||||
|
const provider = providerResult.value;
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
|
||||||
|
const account = await db.whatsappAccount.findFirst({
|
||||||
|
where: { ownerId, provider: provider.id, status: 'ACTIVE' },
|
||||||
|
});
|
||||||
|
if (!account) return emptyTotals();
|
||||||
|
if (!(await (this.deps.planGuard ?? new PlanGuard()).hasFeature(ownerId, 'whatsappAutomations'))) return emptyTotals();
|
||||||
|
if ((await provider.readiness(account, 'PAYMENT_LINK')) !== 'ready') return emptyTotals();
|
||||||
|
|
||||||
|
const owner = await db.user.findUnique({ where: { id: ownerId }, select: { country: true } });
|
||||||
|
const parsedCountry = countryCodeSchema.safeParse(owner?.country);
|
||||||
|
const country = parsedCountry.success ? parsedCountry.data : null;
|
||||||
|
|
||||||
|
const checkouts = await db.paymentCheckout.findMany({
|
||||||
|
where: { id: { in: checkoutIds }, ownerId, status: 'OPEN', checkoutUrl: { not: null } },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
amount: true,
|
||||||
|
currency: true,
|
||||||
|
dueDate: true,
|
||||||
|
checkoutUrl: true,
|
||||||
|
payer: { select: { id: true, fullName: true, phone: true } },
|
||||||
|
payments: {
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
groupId: true,
|
||||||
|
attendeeId: true,
|
||||||
|
periodKey: true,
|
||||||
|
group: { select: { name: true } },
|
||||||
|
attendee: { select: { person: { select: { id: true, fullName: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const items: DispatchItem[] = [];
|
||||||
|
for (const checkout of checkouts) {
|
||||||
|
const first = checkout.payments[0];
|
||||||
|
if (!first || !checkout.checkoutUrl) continue;
|
||||||
|
items.push({
|
||||||
|
groupId: first.groupId,
|
||||||
|
attendeeId: first.attendeeId,
|
||||||
|
checkoutId: checkout.id,
|
||||||
|
// One per checkout and month: an attendee is in a single checkout a month.
|
||||||
|
periodKey: first.periodKey ?? undefined,
|
||||||
|
rawPhone: checkout.payer.phone,
|
||||||
|
message: {
|
||||||
|
kind: 'PAYMENT_LINK',
|
||||||
|
studentName: checkout.payer.fullName,
|
||||||
|
detail: paymentLinkDetail(
|
||||||
|
checkout.payer.id,
|
||||||
|
checkout.payments.map((payment) => ({
|
||||||
|
groupName: payment.group.name,
|
||||||
|
personId: payment.attendee.person.id,
|
||||||
|
fullName: payment.attendee.person.fullName,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
amount: formatAmount(Number(checkout.amount.toString()), checkout.currency, country),
|
||||||
|
dueDate: formatDueDate(checkout.dueDate, country),
|
||||||
|
paymentLink: checkout.checkoutUrl,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return dispatchForAccount(
|
||||||
|
{
|
||||||
|
db,
|
||||||
|
provider,
|
||||||
|
now: this.deps.now ?? new Date(),
|
||||||
|
intervalMs: this.deps.intervalMs ?? sendIntervalFromEnv(),
|
||||||
|
sleep: this.deps.sleep ?? sleep,
|
||||||
|
},
|
||||||
|
account,
|
||||||
|
country,
|
||||||
|
items,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { contactPhone } from '@/modules/people/lib/people';
|
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
||||||
import {
|
import {
|
||||||
addTotals,
|
addTotals,
|
||||||
type DispatchItem,
|
type DispatchItem,
|
||||||
@@ -15,6 +15,7 @@ import { formatAmount, formatDueDate } from '../lib/format';
|
|||||||
import { getMessagingProvider } from '../providers';
|
import { getMessagingProvider } from '../providers';
|
||||||
import type { MessagingProvider } from '../providers/messaging-provider';
|
import type { MessagingProvider } from '../providers/messaging-provider';
|
||||||
import { findEligibleAccounts } from './eligible-accounts';
|
import { findEligibleAccounts } from './eligible-accounts';
|
||||||
|
import { paymentLinkDetail } from './send-payment-links';
|
||||||
|
|
||||||
/** Only charges that are due within the coming week (or already overdue). */
|
/** Only charges that are due within the coming week (or already overdue). */
|
||||||
const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000;
|
const DUE_HORIZON_MS = 7 * 24 * 60 * 60 * 1000;
|
||||||
@@ -32,7 +33,9 @@ type SendPaymentRemindersDeps = {
|
|||||||
* a Checkout Pro link, in groups whose owner turned the automation on.
|
* 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 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).
|
* one goes in the message (the rest are in the same Cobros screen anyway). A
|
||||||
|
* fee of a combined link is reminded once per link, to whoever pays it, with
|
||||||
|
* the link's total: an adult with two kids gets one message, not two.
|
||||||
*/
|
*/
|
||||||
export class SendPaymentReminders {
|
export class SendPaymentReminders {
|
||||||
constructor(private readonly deps: SendPaymentRemindersDeps = {}) {}
|
constructor(private readonly deps: SendPaymentRemindersDeps = {}) {}
|
||||||
@@ -52,6 +55,7 @@ export class SendPaymentReminders {
|
|||||||
|
|
||||||
for (const { account, country, groups } of accounts) {
|
for (const { account, country, groups } of accounts) {
|
||||||
const items: DispatchItem[] = [];
|
const items: DispatchItem[] = [];
|
||||||
|
const seenCheckouts = new Set<string>();
|
||||||
|
|
||||||
for (const group of groups) {
|
for (const group of groups) {
|
||||||
const payments = await db.payment.findMany({
|
const payments = await db.payment.findMany({
|
||||||
@@ -70,8 +74,23 @@ export class SendPaymentReminders {
|
|||||||
currency: true,
|
currency: true,
|
||||||
dueDate: true,
|
dueDate: true,
|
||||||
checkoutUrl: true,
|
checkoutUrl: true,
|
||||||
|
checkout: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
status: true,
|
||||||
|
amount: true,
|
||||||
|
payer: { select: { id: true, fullName: true, phone: true } },
|
||||||
|
payments: {
|
||||||
|
orderBy: { createdAt: 'asc' },
|
||||||
|
select: {
|
||||||
|
group: { select: { name: true } },
|
||||||
|
attendee: { select: { person: { select: { id: true, fullName: true } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
attendee: {
|
attendee: {
|
||||||
select: { id: true, person: { select: { fullName: true, phone: true, guardianPhone: true } } },
|
select: { id: true, person: { select: { fullName: true, phone: true, ...guardianSelect } } },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
orderBy: { dueDate: 'asc' },
|
orderBy: { dueDate: 'asc' },
|
||||||
@@ -81,6 +100,34 @@ export class SendPaymentReminders {
|
|||||||
for (const payment of payments) {
|
for (const payment of payments) {
|
||||||
if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue;
|
if (seen.has(payment.attendee.id) || !payment.checkoutUrl) continue;
|
||||||
seen.add(payment.attendee.id);
|
seen.add(payment.attendee.id);
|
||||||
|
const checkout = payment.checkout?.status === 'OPEN' ? payment.checkout : null;
|
||||||
|
if (checkout) {
|
||||||
|
if (seenCheckouts.has(checkout.id)) continue;
|
||||||
|
seenCheckouts.add(checkout.id);
|
||||||
|
items.push({
|
||||||
|
groupId: group.id,
|
||||||
|
attendeeId: payment.attendee.id,
|
||||||
|
paymentId: payment.id,
|
||||||
|
checkoutId: checkout.id,
|
||||||
|
rawPhone: checkout.payer.phone,
|
||||||
|
message: {
|
||||||
|
kind: 'PAYMENT_REMINDER',
|
||||||
|
studentName: checkout.payer.fullName,
|
||||||
|
groupName: paymentLinkDetail(
|
||||||
|
checkout.payer.id,
|
||||||
|
checkout.payments.map((line) => ({
|
||||||
|
groupName: line.group.name,
|
||||||
|
personId: line.attendee.person.id,
|
||||||
|
fullName: line.attendee.person.fullName,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
amount: formatAmount(Number(checkout.amount.toString()), payment.currency, country),
|
||||||
|
dueDate: formatDueDate(payment.dueDate, country),
|
||||||
|
paymentLink: payment.checkoutUrl,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
items.push({
|
items.push({
|
||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
attendeeId: payment.attendee.id,
|
attendeeId: payment.attendee.id,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
findStudentsAtRisk,
|
findStudentsAtRisk,
|
||||||
type StudentsAtRiskDb,
|
type StudentsAtRiskDb,
|
||||||
} from '@/modules/analytics/features/get-students-at-risk/use-case';
|
} from '@/modules/analytics/features/get-students-at-risk/use-case';
|
||||||
import { contactPhone } from '@/modules/people/lib/people';
|
import { contactPhone, guardianSelect } from '@/modules/people/lib/people';
|
||||||
import {
|
import {
|
||||||
addTotals,
|
addTotals,
|
||||||
type DispatchItem,
|
type DispatchItem,
|
||||||
@@ -70,7 +70,7 @@ export class SendReengagementMessages {
|
|||||||
}),
|
}),
|
||||||
db.attendee.findMany({
|
db.attendee.findMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
select: { id: true, person: { select: { phone: true, guardianPhone: true } } },
|
select: { id: true, person: { select: { phone: true, ...guardianSelect } } },
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
const coolingDown = new Set(recent.map((row) => row.attendeeId));
|
const coolingDown = new Set(recent.map((row) => row.attendeeId));
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import prisma from '@/lib/prisma';
|
|||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { KapsoProvider } from '../providers';
|
import { KapsoProvider } from '../providers';
|
||||||
import { getKapsoConfig } from '../providers/kapso/config';
|
import { getKapsoConfig } from '../providers/kapso/config';
|
||||||
|
import { KAPSO_TEMPLATES } from '../providers/kapso/templates';
|
||||||
|
|
||||||
type SyncKapsoTemplatesDeps = {
|
type SyncKapsoTemplatesDeps = {
|
||||||
db?: Pick<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>;
|
db?: Pick<PrismaClient, 'whatsappAccount' | 'whatsappTemplate'>;
|
||||||
@@ -12,7 +13,7 @@ type SyncKapsoTemplatesDeps = {
|
|||||||
export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number };
|
export type SyncKapsoTemplatesResult = { checked: number; updated: number; failed: number };
|
||||||
|
|
||||||
/** How many templates each account should have (one per message kind). */
|
/** How many templates each account should have (one per message kind). */
|
||||||
const EXPECTED_TEMPLATES = 2;
|
const EXPECTED_TEMPLATES = Object.keys(KAPSO_TEMPLATES).length;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Meta reviews templates on its own schedule (up to ~24h) and Kapso documents
|
* Meta reviews templates on its own schedule (up to ~24h) and Kapso documents
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ export type DispatchItem = {
|
|||||||
groupId: string;
|
groupId: string;
|
||||||
attendeeId: string;
|
attendeeId: string;
|
||||||
paymentId?: string | null;
|
paymentId?: string | null;
|
||||||
|
/** Combined link the message is about (PAYMENT_LINK). */
|
||||||
|
checkoutId?: string | null;
|
||||||
|
/** Overrides the ISO week: the month for the monthly payment link. */
|
||||||
|
periodKey?: string;
|
||||||
/** The member's phone, or their guardian's, as stored. */
|
/** The member's phone, or their guardian's, as stored. */
|
||||||
rawPhone: string | null;
|
rawPhone: string | null;
|
||||||
message: WhatsappMessage;
|
message: WhatsappMessage;
|
||||||
@@ -74,7 +78,7 @@ export async function dispatchForAccount(
|
|||||||
items: DispatchItem[],
|
items: DispatchItem[],
|
||||||
): Promise<DispatchTotals> {
|
): Promise<DispatchTotals> {
|
||||||
const totals = emptyTotals();
|
const totals = emptyTotals();
|
||||||
const periodKey = isoWeekKey(deps.now);
|
const weekKey = isoWeekKey(deps.now);
|
||||||
let sentBefore = false;
|
let sentBefore = false;
|
||||||
|
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
@@ -83,9 +87,10 @@ export async function dispatchForAccount(
|
|||||||
groupId: item.groupId,
|
groupId: item.groupId,
|
||||||
attendeeId: item.attendeeId,
|
attendeeId: item.attendeeId,
|
||||||
paymentId: item.paymentId ?? null,
|
paymentId: item.paymentId ?? null,
|
||||||
|
checkoutId: item.checkoutId ?? null,
|
||||||
kind: item.message.kind as WhatsappMessageKind,
|
kind: item.message.kind as WhatsappMessageKind,
|
||||||
provider: deps.provider.id,
|
provider: deps.provider.id,
|
||||||
periodKey,
|
periodKey: item.periodKey ?? weekKey,
|
||||||
};
|
};
|
||||||
|
|
||||||
const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null;
|
const e164 = item.rawPhone ? toWhatsappE164(item.rawPhone, country) : null;
|
||||||
@@ -152,6 +157,7 @@ type RecordInput = {
|
|||||||
groupId: string;
|
groupId: string;
|
||||||
attendeeId: string;
|
attendeeId: string;
|
||||||
paymentId: string | null;
|
paymentId: string | null;
|
||||||
|
checkoutId: string | null;
|
||||||
kind: WhatsappMessageKind;
|
kind: WhatsappMessageKind;
|
||||||
provider: MessagingProvider['id'];
|
provider: MessagingProvider['id'];
|
||||||
periodKey: string;
|
periodKey: string;
|
||||||
|
|||||||
@@ -18,6 +18,12 @@ export function renderMessage(message: WhatsappMessage): string {
|
|||||||
`por ${message.amount}, con vencimiento el ${message.dueDate}. ` +
|
`por ${message.amount}, con vencimiento el ${message.dueDate}. ` +
|
||||||
`Podés pagarlo desde este link: ${message.paymentLink}`
|
`Podés pagarlo desde este link: ${message.paymentLink}`
|
||||||
);
|
);
|
||||||
|
case 'PAYMENT_LINK':
|
||||||
|
return (
|
||||||
|
`¡Hola ${firstName}! Ya está disponible el pago de este mes: ${message.detail}, ` +
|
||||||
|
`por ${message.amount}, con vencimiento el ${message.dueDate}. ` +
|
||||||
|
`Podés pagarlo desde este link: ${message.paymentLink}`
|
||||||
|
);
|
||||||
case 'REENGAGEMENT':
|
case 'REENGAGEMENT':
|
||||||
// Same copy the teacher sends by hand from "Alumnos en riesgo".
|
// Same copy the teacher sends by hand from "Alumnos en riesgo".
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -58,6 +58,41 @@ export const KAPSO_TEMPLATES: Record<WhatsappMessageKind, TemplateSpec> = {
|
|||||||
]
|
]
|
||||||
: [],
|
: [],
|
||||||
},
|
},
|
||||||
|
PAYMENT_LINK: {
|
||||||
|
definition: {
|
||||||
|
name: 'gruperly_payment_link',
|
||||||
|
language: TEMPLATE_LANGUAGE,
|
||||||
|
category: 'UTILITY',
|
||||||
|
parameter_format: 'NAMED',
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
type: 'BODY',
|
||||||
|
text:
|
||||||
|
'¡Hola {{student_name}}! Ya está disponible el pago de este mes: {{detail}}, 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: 'Laura' },
|
||||||
|
{ param_name: 'detail', example: 'Natación (Juan) y Yoga (Ana)' },
|
||||||
|
{ param_name: 'amount', example: '$ 50.000' },
|
||||||
|
{ param_name: 'due_date', example: '10/12' },
|
||||||
|
{ param_name: 'payment_link', example: 'https://mpago.la/2xYz123' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
parameters: (message) =>
|
||||||
|
message.kind === 'PAYMENT_LINK'
|
||||||
|
? [
|
||||||
|
{ name: 'student_name', text: firstNameOf(message.studentName) },
|
||||||
|
{ name: 'detail', text: message.detail },
|
||||||
|
{ name: 'amount', text: message.amount },
|
||||||
|
{ name: 'due_date', text: message.dueDate },
|
||||||
|
{ name: 'payment_link', text: message.paymentLink },
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
},
|
||||||
REENGAGEMENT: {
|
REENGAGEMENT: {
|
||||||
definition: {
|
definition: {
|
||||||
name: 'gruperly_reengagement',
|
name: 'gruperly_reengagement',
|
||||||
@@ -80,10 +115,13 @@ export const KAPSO_TEMPLATES: Record<WhatsappMessageKind, TemplateSpec> = {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
parameters: (message) => [
|
parameters: (message) =>
|
||||||
{ name: 'student_name', text: firstNameOf(message.studentName) },
|
message.kind === 'REENGAGEMENT'
|
||||||
{ name: 'group_name', text: message.groupName },
|
? [
|
||||||
],
|
{ name: 'student_name', text: firstNameOf(message.studentName) },
|
||||||
|
{ name: 'group_name', text: message.groupName },
|
||||||
|
]
|
||||||
|
: [],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -40,6 +40,16 @@ export type WhatsappMessage =
|
|||||||
kind: 'REENGAGEMENT';
|
kind: 'REENGAGEMENT';
|
||||||
studentName: string;
|
studentName: string;
|
||||||
groupName: string;
|
groupName: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
/** The monthly combined link, to whoever pays (the adult for kids). */
|
||||||
|
kind: 'PAYMENT_LINK';
|
||||||
|
studentName: string;
|
||||||
|
/** What it pays, e.g. "Yoga (Juan) y Natación (Ana)". */
|
||||||
|
detail: string;
|
||||||
|
amount: string;
|
||||||
|
dueDate: string;
|
||||||
|
paymentLink: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type StartConnectionContext = {
|
export type StartConnectionContext = {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user