From abb18f1815f7f75a0bb345bc7d1c5752e0c9980d Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 10 Nov 2026 18:27:15 -0300 Subject: [PATCH 1/2] Language selector on onboarding screen Fixed docker-compose --- .env.example | 20 ++- .../features/onboarding/LanguageSwitcher.tsx | 39 +++++ .../features/onboarding/OnboardingView.tsx | 6 +- .../src/features/settings/LanguageCard.tsx | 19 +-- .../src/features/settings/useSelectLocale.ts | 25 +++ docker-compose.yml | 90 ++--------- docs/environment.md | 148 ++++++++++++++++++ 7 files changed, 251 insertions(+), 96 deletions(-) create mode 100644 apps/web/src/features/onboarding/LanguageSwitcher.tsx create mode 100644 apps/web/src/features/settings/useSelectLocale.ts create mode 100644 docs/environment.md diff --git a/.env.example b/.env.example index 867841c..1bd7d30 100644 --- a/.env.example +++ b/.env.example @@ -3,7 +3,9 @@ # Local: copy this file to `.env` at the root and fill in the values. # Dokploy: no file needed; define the same variables in the Environment tab of # the Compose service (Dokploy writes them to a `.env` next to the compose -# file, which is where the `${...}` come from). +# 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 # BETTER_AUTH_URL because nginx proxies /api: the web and the API share a @@ -46,17 +48,25 @@ BETTER_AUTH_SECRET="" # MP_CLIENT_ID="" # MP_CLIENT_SECRET="" -# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md). -# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra -# entre países). No son las del OAuth del profesor. Un país sin las dos queda -# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY. +# Suscripción a Gruperly Pro (ver docs/billing.md y docs/environment.md). +# Argentina la cobra con Suscripciones de Mercado Pago; el resto, con Stripe. +# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina. No +# son las del OAuth del profesor. Sin las dos, Pro queda "no disponible" (503). # MP_PLATFORM_ACCESS_TOKEN_AR="" # MP_PLATFORM_WEBHOOK_SECRET_AR="" +# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda de +# cada país. Secret key (sk_live_…) y signing secret del webhook (whsec_…) del +# endpoint https:///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. # BILLING_ENFORCEMENT="off" # Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando. # BILLING_GRACE_DAYS="7" +# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie. +# ADMIN_EMAILS="" + # WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md). # Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503 # whatsapp_not_configured y el paso del onboarding es salteable. diff --git a/apps/web/src/features/onboarding/LanguageSwitcher.tsx b/apps/web/src/features/onboarding/LanguageSwitcher.tsx new file mode 100644 index 0000000..f303fe8 --- /dev/null +++ b/apps/web/src/features/onboarding/LanguageSwitcher.tsx @@ -0,0 +1,39 @@ +import { SUPPORTED_LOCALES } from '@gruperly/shared' +import { ChevronDown, Languages } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { useLocale, type LocalePreference } from '../../i18n' +import { LOCALE_NAMES } from '../../i18n/locales' +import { useSelectLocale } from '../settings/useSelectLocale' + +const OPTIONS: LocalePreference[] = ['system', ...SUPPORTED_LOCALES] + +/* Selector compacto para el header del onboarding: muestra el código del idioma + actual y abre el ` select(event.target.value as LocalePreference)} + className="absolute inset-0 cursor-pointer appearance-none opacity-0" + > + {OPTIONS.map((option) => ( + + ))} + + + ) +} diff --git a/apps/web/src/features/onboarding/OnboardingView.tsx b/apps/web/src/features/onboarding/OnboardingView.tsx index ad06fab..1716881 100644 --- a/apps/web/src/features/onboarding/OnboardingView.tsx +++ b/apps/web/src/features/onboarding/OnboardingView.tsx @@ -8,6 +8,7 @@ import { useAuth } from '../../context/AuthProvider' import { ConfirmationStep } from './ConfirmationStep' import { CountryStep } from './CountryStep' import { FirstGroupStep } from './FirstGroupStep' +import { LanguageSwitcher } from './LanguageSwitcher' import { useOnboarding } from './OnboardingProvider' import { PaymentStep } from './PaymentStep' import { PlanStep } from './PlanStep' @@ -108,8 +109,11 @@ export function OnboardingView() { return (
-
+
+
+ +
{/* Con Free no se muestran Cobros ni WhatsApp: el stepper refleja solo diff --git a/apps/web/src/features/settings/LanguageCard.tsx b/apps/web/src/features/settings/LanguageCard.tsx index 298761a..813c781 100644 --- a/apps/web/src/features/settings/LanguageCard.tsx +++ b/apps/web/src/features/settings/LanguageCard.tsx @@ -1,12 +1,10 @@ import { SUPPORTED_LOCALES } from '@gruperly/shared' import { Check, Languages } from 'lucide-react' import { useTranslation } from 'react-i18next' -import { useToast } from '../../components/ui' -import { useAuth } from '../../context/AuthProvider' import { useLocale, type LocalePreference } from '../../i18n' import { LOCALE_NAMES } from '../../i18n/locales' -import { authClient } from '../../lib/auth-client' import { cn } from '../../lib/utils' +import { useSelectLocale } from './useSelectLocale' const OPTIONS: LocalePreference[] = ['system', ...SUPPORTED_LOCALES] @@ -18,19 +16,8 @@ type LanguageCardProps = { export function LanguageCard({ syncProfile = false }: LanguageCardProps) { const { t } = useTranslation('settings') - const { preference, device, setPreference } = useLocale() - const { user } = useAuth() - const toast = useToast() - - const select = (next: LocalePreference) => { - if (next === preference) return - // Optimista: el idioma cambia ya; la cuenta se actualiza por detrás. - setPreference(next) - if (!syncProfile || !user) return - void authClient.updateUser({ locale: next === 'system' ? null : next }).then(({ error }) => { - if (error) toast.error(t('language.saveError')) - }) - } + const { preference, device } = useLocale() + const select = useSelectLocale(syncProfile) return (
diff --git a/apps/web/src/features/settings/useSelectLocale.ts b/apps/web/src/features/settings/useSelectLocale.ts new file mode 100644 index 0000000..c8f0b41 --- /dev/null +++ b/apps/web/src/features/settings/useSelectLocale.ts @@ -0,0 +1,25 @@ +import { useTranslation } from 'react-i18next' +import { useToast } from '../../components/ui' +import { useAuth } from '../../context/AuthProvider' +import { useLocale, type LocalePreference } from '../../i18n' +import { authClient } from '../../lib/auth-client' + +/** Cambia el idioma al instante y, con `syncProfile`, lo guarda en la cuenta + * del profe (Better Auth). La app de alumnos no tiene esa sesión: ahí queda + * solo en el dispositivo. */ +export function useSelectLocale(syncProfile: boolean) { + const { t } = useTranslation('settings') + const { preference, setPreference } = useLocale() + const { user } = useAuth() + const toast = useToast() + + return (next: LocalePreference) => { + if (next === preference) return + // Optimista: el idioma cambia ya; la cuenta se actualiza por detrás. + setPreference(next) + if (!syncProfile || !user) return + void authClient.updateUser({ locale: next === 'system' ? null : next }).then(({ error }) => { + if (error) toast.error(t('language.saveError')) + }) + } +} diff --git a/docker-compose.yml b/docker-compose.yml index bea85d5..90bd37a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,88 +7,27 @@ # `location /api/` block from apps/web/nginx.conf and set VITE_API_URL when # building web. +# Backend variables. The api container receives the whole `.env` next to this +# file through `env_file` (Dokploy writes it from the Environment tab before +# `docker compose up`; locally, copy .env.example). Every variable the API reads +# is documented in docs/environment.md: adding one there is enough, there is no +# list to keep in sync here. +# +# `environment` wins over `env_file`, so it only keeps what the compose has to +# force or validate: +# - the required ones, with `:?` so the deploy fails early instead of the API +# crashing at runtime; +# - BETTER_AUTH_URL, derived from WEB_URL (web and API share the domain); +# - defaults that differ from the code's, for this deployment (Traefik + nginx). x-backend-env: &backend-env NODE_ENV: production - # Web and API share the public domain: same origin for cookies and CORS. DATABASE_URL: "${DATABASE_URL:?falta DATABASE_URL}" WEB_URL: "${WEB_URL:?falta WEB_URL - origen publico de la app, sin barra final}" BETTER_AUTH_URL: "${WEB_URL:?falta WEB_URL - origen publico de la app, sin barra final}" BETTER_AUTH_SECRET: "${BETTER_AUTH_SECRET:?falta BETTER_AUTH_SECRET - generalo con openssl rand -base64 32}" - GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-} - GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-} - EMAIL_PROVIDER: ${EMAIL_PROVIDER:-smtp} - EMAIL_SERVER_HOST: ${EMAIL_SERVER_HOST:-} - EMAIL_SERVER_PORT: ${EMAIL_SERVER_PORT:-587} - EMAIL_SERVER_USER: ${EMAIL_SERVER_USER:-} - EMAIL_SERVER_PASSWORD: ${EMAIL_SERVER_PASSWORD:-} - EMAIL_FROM: "${EMAIL_FROM:-Gruperly }" - # Mercado Pago OAuth. Opcionales: sin credenciales, GET /mp/connect responde - # 503 mp_not_configured y la app sigue funcionando (el paso es salteable). - MP_CLIENT_ID: ${MP_CLIENT_ID:-} - MP_CLIENT_SECRET: ${MP_CLIENT_SECRET:-} - # Tiene que coincidir con la "Redirect URL" del panel de MP, character por - # character. En produccion, HTTPS y la URL publica de la API. - MP_REDIRECT_URI: ${MP_REDIRECT_URI:-} - # Clave de 32 bytes en base64 (openssl rand -base64 32) para cifrar los tokens - # en reposo. Sin ella, mp/callback falla al guardar la cuenta. - TOKEN_ENCRYPTION_KEY: ${TOKEN_ENCRYPTION_KEY:-} - # Suscripcion a Gruperly Pro (docs/billing.md): credenciales de las cuentas de MP - # de Gruperly, una por pais. Un pais sin las dos variables no ofrece Pro (503). - MP_PLATFORM_ACCESS_TOKEN_AR: ${MP_PLATFORM_ACCESS_TOKEN_AR:-} - MP_PLATFORM_WEBHOOK_SECRET_AR: ${MP_PLATFORM_WEBHOOK_SECRET_AR:-} - MP_PLATFORM_ACCESS_TOKEN_BR: ${MP_PLATFORM_ACCESS_TOKEN_BR:-} - MP_PLATFORM_WEBHOOK_SECRET_BR: ${MP_PLATFORM_WEBHOOK_SECRET_BR:-} - MP_PLATFORM_ACCESS_TOKEN_CL: ${MP_PLATFORM_ACCESS_TOKEN_CL:-} - MP_PLATFORM_WEBHOOK_SECRET_CL: ${MP_PLATFORM_WEBHOOK_SECRET_CL:-} - MP_PLATFORM_ACCESS_TOKEN_CO: ${MP_PLATFORM_ACCESS_TOKEN_CO:-} - MP_PLATFORM_WEBHOOK_SECRET_CO: ${MP_PLATFORM_WEBHOOK_SECRET_CO:-} - MP_PLATFORM_ACCESS_TOKEN_MX: ${MP_PLATFORM_ACCESS_TOKEN_MX:-} - MP_PLATFORM_WEBHOOK_SECRET_MX: ${MP_PLATFORM_WEBHOOK_SECRET_MX:-} - MP_PLATFORM_ACCESS_TOKEN_PE: ${MP_PLATFORM_ACCESS_TOKEN_PE:-} - MP_PLATFORM_WEBHOOK_SECRET_PE: ${MP_PLATFORM_WEBHOOK_SECRET_PE:-} - MP_PLATFORM_ACCESS_TOKEN_UY: ${MP_PLATFORM_ACCESS_TOKEN_UY:-} - MP_PLATFORM_WEBHOOK_SECRET_UY: ${MP_PLATFORM_WEBHOOK_SECRET_UY:-} - # `on` aplica los limites del plan Free; cualquier otro valor deja a todos en Pro. - BILLING_ENFORCEMENT: ${BILLING_ENFORCEMENT:-off} - BILLING_GRACE_DAYS: ${BILLING_GRACE_DAYS:-7} - # App de alumnos: comprobantes de pago en un storage S3 privado (RustFS). Sin - # las cuatro primeras, "Informar pago" responde 503 y el resto funciona igual. - S3_ENDPOINT: ${S3_ENDPOINT:-} - S3_BUCKET: ${S3_BUCKET:-} - S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-} - S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-} - S3_REGION: ${S3_REGION:-us-east-1} - S3_VIRTUAL_HOSTED: ${S3_VIRTUAL_HOSTED:-} - # Dias que se guarda un comprobante ya revisado. 0 = para siempre. - RECEIPT_RETENTION_DAYS: ${RECEIPT_RETENTION_DAYS:-0} - # WebAuthn (Face ID / huella del alumno): por defecto salen de WEB_URL. - WEBAUTHN_RP_ID: ${WEBAUTHN_RP_ID:-} - WEBAUTHN_ORIGIN: ${WEBAUTHN_ORIGIN:-} # Traefik + nginx delante de la API: la IP del cliente es la 2da desde el final - # de X-Forwarded-For (rate limit de "Pedir un link a mi mail"). + # de X-Forwarded-For (rate limit de "Pedir un link a mi mail"). El codigo usa 1. TRUSTED_PROXY_HOPS: ${TRUSTED_PROXY_HOPS:-2} - # WhatsApp (recordatorios de pago y reenganche semanales). Ver docs/whatsapp.md. - # `openwa` (MVP, gateway instalado aparte) o `kapso` (API oficial de Meta). Sin las - # variables del proveedor elegido, /whatsapp/* responde 503 y el paso del - # onboarding es salteable. - WHATSAPP_PROVIDER: ${WHATSAPP_PROVIDER:-openwa} - # Pausa entre dos envios del mismo profesor (ms). No bajar de ~4000 con OpenWA. - WHATSAPP_SEND_INTERVAL_MS: ${WHATSAPP_SEND_INTERVAL_MS:-5000} - # OpenWA se instala por separado (no vive en este compose): URL de su API, - # p. ej. https://openwa.example.com/api. - OPENWA_API_URL: ${OPENWA_API_URL:-} - # Key OPERATOR sin `allowedSessions` (crea sesiones). Se crea con la key ADMIN - # que OpenWA escribe en /app/data/.api-key la primera vez que arranca. - OPENWA_API_KEY: ${OPENWA_API_KEY:-} - # Opcional: sin webhook la vinculacion funciona igual (polling), pero no se - # registran las confirmaciones de entrega/lectura. Tiene que ser una URL que - # OpenWA alcance: /api/v1/whatsapp/webhooks/openwa (requiere el secreto). - OPENWA_WEBHOOK_URL: ${OPENWA_WEBHOOK_URL:-} - OPENWA_WEBHOOK_SECRET: ${OPENWA_WEBHOOK_SECRET:-} - KAPSO_API_KEY: ${KAPSO_API_KEY:-} - KAPSO_CALLBACK_URL: ${KAPSO_CALLBACK_URL:-} - KAPSO_WEBHOOK_URL: ${KAPSO_WEBHOOK_URL:-} - KAPSO_WEBHOOK_SECRET: ${KAPSO_WEBHOOK_SECRET:-} services: api: @@ -96,6 +35,9 @@ services: context: . dockerfile: Dockerfile.backend target: api + env_file: + - path: .env + required: false environment: *backend-env restart: unless-stopped expose: diff --git a/docs/environment.md b/docs/environment.md new file mode 100644 index 0000000..08d626f --- /dev/null +++ b/docs/environment.md @@ -0,0 +1,148 @@ +# Variables de entorno + +Qué hace cada variable, quién la lee y qué pasa si falta. Las plantillas son: + +| Archivo | Para qué | +| --- | --- | +| `apps/backend/.env.example` → `apps/backend/.env` | API en local (`bun dev`). Prisma también lo necesita. | +| `apps/web/.env.example` → `apps/web/.env` | Web en local (solo `VITE_API_URL`). | +| `.env.example` (raíz) → `.env` | `docker compose` / Dokploy. Dokploy escribe el `.env` desde la pestaña Environment antes de levantar el compose. | + +> **Cómo llegan al contenedor**: el servicio `api` de `docker-compose.yml` recibe **todo** el `.env` de la raíz con `env_file`, así que cualquier variable que cargues en Dokploy llega a la API sin tocar el compose. El bloque `environment` (`x-backend-env`) pisa al `env_file` y solo guarda lo que el compose fuerza o valida: `NODE_ENV=production`, las obligatorias con `:?` (`DATABASE_URL`, `WEB_URL`, `BETTER_AUTH_SECRET`; el deploy falla antes de arrancar si faltan), `BETTER_AUTH_URL` (sale de `WEB_URL`) y `TRUSTED_PROXY_HOPS` con default `2`. Al sumar una variable nueva, documentala acá y en los `.env.example`. + +--- + +## Mercado Pago: dos usos que no hay que mezclar + +Gruperly habla con Mercado Pago por **dos motivos completamente distintos**, con credenciales distintas, cuentas distintas y plata que va a lugares distintos: + +| | **Cobros a alumnos** (`modules/mp`, `modules/payments`) | **Suscripción a Gruperly Pro** (`modules/billing`) | +| --- | --- | --- | +| Quién paga | El **alumno** | El **profesor** | +| Quién cobra | El **profesor**, en su propia cuenta de MP | **Gruperly** | +| Producto de MP | Checkout Pro (links de pago `/checkout/preferences`) | Suscripciones (`/preapproval`, débito automático) | +| Cómo se autentica | OAuth (Authorization Code + PKCE): el profesor vincula **su** cuenta y Gruperly guarda **su** access token (cifrado) | Access token **de la cuenta de Gruperly**, fijo en el entorno | +| Variables | `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI`, `TOKEN_ENCRYPTION_KEY` | `MP_PLATFORM_ACCESS_TOKEN_`, `MP_PLATFORM_WEBHOOK_SECRET_` | +| Países | Todos (cada profesor usa la cuenta de MP de su país) | Solo **AR**. El resto de los países paga Pro con **Stripe** (`STRIPE_*`) | +| Cómo se entera de un pago | Polling (`ReconcilePayments`, cada 15 min). No hay webhook | Webhook `POST /api/v1/billing/webhooks/mp/:country` + polling de respaldo | +| Si faltan las variables | `GET /mp/connect` falla; el paso "Cobros" del onboarding es salteable y el resto de la app anda | `503 billing_not_available` en ese país: Pro aparece "no disponible", Free sigue funcionando | + +Regla mental: **`MP_CLIENT_*` identifica a la *aplicación* Gruperly frente a MP para que los profesores le den permiso; nunca cobra nada a nombre de Gruperly. `MP_PLATFORM_*` es la *cuenta* de Gruperly que recibe la plata de Pro.** El código nunca cruza unas con otras: billing jamás usa `getMpAccessToken` (el token del profesor) y los cobros a alumnos jamás usan `MP_PLATFORM_*`. + +### Cuenta del profesor (cobros a alumnos) + +El profesor toca "Vincular Mercado Pago", MP le pide permiso para la aplicación de Gruperly y vuelve a `GET /api/v1/mp/callback` con un `code`. La API lo canjea por un access token + refresh token **del profesor** y los guarda cifrados en la base. Con ese token se crean los links de pago de sus alumnos y se consulta si se pagaron. Es una integración directa (`platform_id=mp`, sin marketplace): la plata cae entera en la cuenta del profesor y Gruperly no se queda con comisión. + +| Variable | Obligatoria | Qué es | +| --- | --- | --- | +| `MP_CLIENT_ID` | Para cobrar a alumnos | **Client ID** de la aplicación de Gruperly en el [panel de desarrolladores de MP](https://www.mercadopago.com/developers/panel/app). Identifica a Gruperly en la pantalla de autorización que ve el profesor. Son las credenciales **de producción** también en local: MP no tiene OAuth de sandbox, y el OAuth solo vincula, no mueve plata. | +| `MP_CLIENT_SECRET` | Para cobrar a alumnos | **Client Secret** de esa misma aplicación. Se usa para canjear el `code` y para renovar tokens (cron `17 3 * * *` UTC). Nunca se loguea. | +| `MP_REDIRECT_URI` | Para cobrar a alumnos | URL a la que MP vuelve después de autorizar: `https:///api/v1/mp/callback`. Tiene que coincidir **carácter por carácter** con la "Redirect URL" cargada en el panel. El panel exige HTTPS, así que en local va un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`). | +| `TOKEN_ENCRYPTION_KEY` | Para cobrar a alumnos | Clave AES-256-GCM con la que se cifran en la base los tokens de MP de los profesores. Base64 que decodifique a **32 bytes**: `openssl rand -base64 32`. **No la rotes**: cambiarla deja ilegibles todas las cuentas vinculadas y los profesores tienen que volver a vincular. | + +Si falta alguna de las tres `MP_*`, el error nombra la variable en el log (nunca su valor). Si falta `TOKEN_ENCRYPTION_KEY`, falla cualquier operación que lea o guarde un token. + +### Cuenta de Gruperly (suscripción Pro en Argentina) + +Gruperly le cobra al profesor argentino la suscripción mensual a Pro desde **su propia cuenta de MP**. MP no cobra entre países, por eso las variables llevan el código de país (``); hoy solo se usa `AR` (`BILLING_PROVIDER_BY_COUNTRY` en `packages/shared/src/schemas/billing.ts`). Guía completa en [`billing.md`](./billing.md). + +| Variable | Obligatoria | Qué es | +| --- | --- | --- | +| `MP_PLATFORM_ACCESS_TOKEN_AR` | Para vender Pro en AR | **Access Token de producción** de la cuenta de MP **de Gruperly** en Argentina (no de un profesor, no el `MP_CLIENT_SECRET`). Crea y consulta las suscripciones (`/preapproval`). | +| `MP_PLATFORM_WEBHOOK_SECRET_AR` | Para vender Pro en AR | **Clave secreta** del webhook configurado en esa cuenta (URL `https:///api/v1/billing/webhooks/mp/ar`, eventos de Planes y suscripciones). Verifica la firma `x-signature`. | + +Hacen falta **las dos**; con una sola el país queda sin Pro (`503`). El código acepta cualquier `MP_PLATFORM_*_` si algún día otro país vuelve a cobrarse con MP, pero hoy el resto usa Stripe. + +> La cuenta de Gruperly y la aplicación OAuth pueden vivir en el mismo usuario de MP, pero son credenciales distintas: `MP_CLIENT_ID`/`MP_CLIENT_SECRET` son de la **aplicación** (para que otros te autoricen) y `MP_PLATFORM_ACCESS_TOKEN_AR` es el token de **tu propia cuenta** (para cobrar vos). + +--- + +## Stripe (suscripción Pro fuera de Argentina) + +Una sola cuenta de Stripe de Gruperly cobra Pro en BR, CL, CO, MX, PE y UY, en la moneda de cada país. No tiene nada que ver con los alumnos. + +| Variable | Obligatoria | Qué es | +| --- | --- | --- | +| `STRIPE_SECRET_KEY` | Para vender Pro fuera de AR | Secret key de la cuenta (`sk_test_…` en local, `sk_live_…` en producción). | +| `STRIPE_WEBHOOK_SECRET` | Para vender Pro fuera de AR | Signing secret (`whsec_…`) del endpoint `https:///api/v1/billing/webhooks/stripe`. En local lo imprime `stripe listen`. | + +Sin las dos, esos países ven Pro como no disponible (`503`). + +## Plan (billing) + +| Variable | Default | Qué es | +| --- | --- | --- | +| `BILLING_ENFORCEMENT` | `off` | `on` aplica los límites del plan Free (`402 plan_*`). Cualquier otro valor: todos funcionan como Pro y los guards no tocan la base. | +| `BILLING_GRACE_DAYS` | `7` | Días que un Pro vencido (cancelado o con cobro rechazado) sigue funcionando después del último día pago. | + +--- + +## Base, servidor y auth + +| Variable | Obligatoria | Default | Qué es | +| --- | --- | --- | --- | +| `DATABASE_URL` | Sí | — | Connection string de PostgreSQL. La usan Prisma CLI (`prisma.config.ts`) y el cliente. Si la contraseña tiene `# @ : / ? %` o espacios, va percent-encoded (si no, `P1013`). | +| `PORT` | No | `4000` | Puerto de `Bun.serve`. | +| `NODE_ENV` | No | — | `production` activa HSTS en los security headers y cambia el formato del logger. El compose lo fija. | +| `WEB_URL` | Sí en prod | `http://localhost:6173` | Origen público de la web, sin barra final. Se usa para CORS, CSRF (`Origin` del portal de alumnos), los redirects del callback de MP, los links de invitación y de alumnos, y como base de WebAuthn. | +| `BETTER_AUTH_URL` | Sí | — | URL base de Better Auth. En el compose es igual a `WEB_URL` porque nginx proxea `/api` (cookie first-party). | +| `BETTER_AUTH_SECRET` | Sí | — | Secreto para firmar sesiones de profesores. `openssl rand -base64 32`. Cambiarlo cierra todas las sesiones. | +| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | No | — | Login con Google. Sin los dos, el proveedor no se registra. | +| `ADMIN_EMAILS` | No | vacío | Emails del equipo de Gruperly con acceso al backoffice `/admin`, separados por coma. Vacío = nadie. | +| `PROBLEM_DOMAIN_URL` | No | `https://gruperly.com` | Dominio con el que se arma el `type` de los Problem Details. | +| `APP_TIMEZONE` | No | `America/Argentina/Buenos_Aires` | Zona horaria por defecto (Inicio, clases de hoy, avisos de falta) cuando no llega una desde el request o el país del profesor. | +| `ABSENCE_RELEASE_HOURS` | No | `12` | Horas antes de la clase hasta las que una falta avisada libera el cupo. | + +## Email + +| Variable | Default | Qué es | +| --- | --- | --- | +| `EMAIL_PROVIDER` | `smtp` | Implementación de envío. Hoy solo existe `smtp`. | +| `EMAIL_SERVER_HOST` | — | Host SMTP. | +| `EMAIL_SERVER_PORT` | `587` | Puerto SMTP. `465` activa TLS directo. | +| `EMAIL_SERVER_USER` / `EMAIL_SERVER_PASSWORD` | — | Credenciales SMTP. | +| `EMAIL_FROM` | `Gruperly ` | Remitente. | + +## WhatsApp + +Mensajes automáticos semanales (recordatorio de pago y reenganche). Guía en [`whatsapp.md`](./whatsapp.md). Sin las variables del proveedor elegido, `/whatsapp/*` responde `503 whatsapp_not_configured` y el paso del onboarding se puede saltear. + +| Variable | Default | Qué es | +| --- | --- | --- | +| `WHATSAPP_PROVIDER` | `openwa` | `openwa` (MVP, gateway self-hosted con QR) o `kapso` (API oficial de Meta). Cambiarlo deja las cuentas del proveedor anterior en `requires_reconnect`. | +| `WHATSAPP_SEND_INTERVAL_MS` | `5000` | Pausa entre dos envíos del mismo profesor. | +| `OPENWA_API_URL` | — | URL de la API de OpenWA (se instala aparte). Obligatoria con `openwa`. | +| `OPENWA_API_KEY` | — | Key **OPERATOR** sin `allowedSessions`. Obligatoria con `openwa`. | +| `OPENWA_WEBHOOK_URL` | — | Opcional: `https:///api/v1/whatsapp/webhooks/openwa`. Sin ella la vinculación anda por polling, pero no llegan confirmaciones de entrega/lectura. | +| `OPENWA_WEBHOOK_SECRET` | — | HMAC del webhook, 16+ caracteres (`openssl rand -hex 24`). Obligatorio si hay `OPENWA_WEBHOOK_URL`. | +| `KAPSO_API_KEY` | — | API key de Kapso. Obligatoria con `kapso`. | +| `KAPSO_CALLBACK_URL` | — | `https:///api/v1/whatsapp/callback` (vuelta del setup link). Pública. | +| `KAPSO_WEBHOOK_URL` | — | `https:///api/v1/whatsapp/webhooks/kapso`. Pública. | +| `KAPSO_WEBHOOK_SECRET` | — | El mismo secreto del project webhook del dashboard de Kapso. | +| `KAPSO_API_URL` | `https://api.kapso.ai` | Solo para apuntar a otro host. | + +## App de alumnos + +| Variable | Default | Qué es | +| --- | --- | --- | +| `S3_ENDPOINT` | — | Endpoint del storage S3 privado de comprobantes (RustFS, MinIO, R2, AWS). | +| `S3_BUCKET` | — | Bucket. | +| `S3_ACCESS_KEY_ID` / `S3_SECRET_ACCESS_KEY` | — | Credenciales. Sin estas cuatro, "Informar pago" responde `503 storage_not_available` y el resto anda. | +| `S3_REGION` | `us-east-1` | Región. | +| `S3_VIRTUAL_HOSTED` | vacío | `on` = URLs estilo AWS (`bucket.endpoint`). RustFS/MinIO usan path-style: dejalo vacío. | +| `RECEIPT_RETENTION_DAYS` | `0` | Días que se guarda un comprobante ya revisado. `0` = para siempre. | +| `WEBAUTHN_RP_ID` | host de `WEB_URL` | RP ID de las passkeys (Face ID / huella). Solo si la web se sirve desde otro origen. | +| `WEBAUTHN_ORIGIN` | `WEB_URL` | Origen esperado por WebAuthn; también se acepta en el chequeo CSRF. | +| `TRUSTED_PROXY_HOPS` | `1` (`2` en el compose) | Cuántos proxies agregan `X-Forwarded-For` delante de la API. Define qué IP cuenta para el rate limit de "Pedir un link a mi mail". | + +## Web (`apps/web`) + +| Variable | Qué es | +| --- | --- | +| `VITE_API_URL` | Origen de la API. Se hornea en el bundle en build. En producción dejalo vacío (mismo origen, nginx proxea `/api`); solo se usa si la API vive en otro dominio. | + +## Solo tests + +| Variable | Qué es | +| --- | --- | +| `DB_TESTS` | `1` habilita los tests de `test/db/` contra Postgres real (`bun --filter @gruperly/backend test:db`). | -- 2.49.1 From aac142d3241758e86b1ac04d1ebdcd681cd86155 Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Wed, 11 Nov 2026 07:50:14 -0300 Subject: [PATCH 2/2] feat(billing): configurable plans from the backoffice and MP payment notifications Plans: - Plan limits and Pro prices per country live in the database (plan_configs, plan_prices, seeded with the previous constants) and are read through PlanCatalog (30 s cache, defaults as fallback). - /admin/plans edits limits (with the count of accounts that would become read-only) and prices, optionally pushing the new price to live subscriptions from their next charge (MP preapproval amount, Stripe item without proration) via the ApplyPriceChanges job, with an email and a notice on /billing. - GET /billing/plans feeds the onboarding and the billing screen. Mercado Pago: - The Pro checkout returns through GET /billing/return on API_PUBLIC_URL, since MP refuses a back_url on localhost. - The OAuth callback bounces from the tunnel to BETTER_AUTH_URL to find the session, requires the session to own the state, and redirects instead of answering JSON on unexpected errors. - Checkout Pro links skip auto_return off public HTTPS and carry a notification_url to POST /payments/webhooks/mp/:paymentId, which confirms the payment with the owner's token (same rule as the polling job, which stays as fallback). The search now prefers the approved attempt. Co-Authored-By: Claude Opus 5.5 --- .env.example | 3 + AGENTS.md | 6 +- apps/backend/.env.example | 5 + .../migration.sql | 67 +++++ apps/backend/prisma/models/billing.prisma | 56 ++++ apps/backend/src/app.ts | 4 + apps/backend/src/http/session-auth.ts | 9 + apps/backend/src/lib/email.ts | 24 ++ apps/backend/src/lib/public-origin.ts | 17 ++ .../admin/features/get-account/use-case.ts | 22 +- .../modules/admin/features/get-plans/route.ts | 12 + .../admin/features/get-plans/use-case.ts | 55 ++++ .../features/plan-limits-impact/route.ts | 23 ++ .../features/plan-limits-impact/use-case.ts | 52 ++++ .../features/update-plan-limits/route.ts | 26 ++ .../features/update-plan-limits/use-case.ts | 29 ++ .../admin/features/update-plan-price/route.ts | 27 ++ .../features/update-plan-price/use-case.ts | 89 ++++++ apps/backend/src/modules/admin/routes.ts | 10 + .../modules/billing/features/plans/route.ts | 16 ++ .../modules/billing/features/return/route.ts | 19 ++ .../billing/features/status/use-case.ts | 28 +- .../billing/features/subscribe/use-case.ts | 21 +- .../billing/jobs/apply-price-changes.ts | 117 ++++++++ .../backend/src/modules/billing/jobs/index.ts | 3 +- .../src/modules/billing/jobs/schedule.ts | 25 ++ .../src/modules/billing/lib/catalog.ts | 108 +++++++ .../backend/src/modules/billing/lib/config.ts | 2 + .../src/modules/billing/lib/entitlements.ts | 6 +- .../src/modules/billing/lib/helpers.ts | 14 +- apps/backend/src/modules/billing/lib/index.ts | 13 +- .../billing/providers/billing-provider.ts | 2 + .../billing/providers/mercado-pago/index.ts | 7 + .../providers/mercado-pago/preapproval.ts | 19 ++ .../modules/billing/providers/stripe/index.ts | 33 +++ apps/backend/src/modules/billing/routes.ts | 4 + .../src/modules/mp/features/callback/route.ts | 10 +- .../modules/mp/features/callback/use-case.ts | 10 + .../src/modules/mp/lib/callback-origin.ts | 39 +++ apps/backend/src/modules/mp/lib/index.ts | 1 + apps/backend/src/modules/mp/lib/mp-http.ts | 29 +- .../features/create-batch/use-case.ts | 6 +- .../payments/features/renew/use-case.ts | 6 +- .../payments/features/webhook/route.ts | 17 ++ .../payments/features/webhook/use-case.ts | 45 +++ .../payments/jobs/reconcile-payments.ts | 47 ++-- .../payments/lib/confirm-mp-payment.ts | 45 +++ .../backend/src/modules/payments/lib/index.ts | 6 + apps/backend/src/modules/payments/routes.ts | 2 + apps/backend/test/admin.test.ts | 19 ++ .../backend/test/billing-entitlements.test.ts | 3 +- .../backend/test/billing-plan-catalog.test.ts | 266 ++++++++++++++++++ apps/backend/test/billing-return.test.ts | 55 ++++ apps/backend/test/billing-subscribe.test.ts | 23 +- apps/backend/test/mp-preference.test.ts | 78 +++++ apps/backend/test/mp.test.ts | 39 +++ apps/backend/test/payments-batch.test.ts | 5 +- apps/backend/test/payments-renew.test.ts | 3 +- apps/backend/test/payments-webhook.test.ts | 103 +++++++ .../features/admin/AdminAccountDetailView.tsx | 3 +- apps/web/src/features/admin/AdminLayout.tsx | 25 +- .../src/features/admin/AdminPlansProvider.tsx | 95 +++++++ .../web/src/features/admin/AdminPlansView.tsx | 61 ++++ apps/web/src/features/admin/LimitInput.tsx | 52 ++++ .../web/src/features/admin/PlanLimitsCard.tsx | 131 +++++++++ apps/web/src/features/admin/PlanPriceRow.tsx | 118 ++++++++ apps/web/src/features/billing/BillingView.tsx | 7 +- .../src/features/billing/PlanSummaryCard.tsx | 7 +- apps/web/src/features/billing/index.ts | 1 + .../src/features/billing/usePlanCatalog.ts | 23 ++ apps/web/src/features/onboarding/PlanStep.tsx | 14 +- apps/web/src/i18n/locales/en/admin.json | 44 +++ apps/web/src/i18n/locales/en/billing.json | 3 +- apps/web/src/i18n/locales/en/validation.json | 3 + apps/web/src/i18n/locales/es-419/admin.json | 44 +++ apps/web/src/i18n/locales/es-419/billing.json | 3 +- .../src/i18n/locales/es-419/validation.json | 3 + apps/web/src/i18n/locales/es-AR/admin.json | 44 +++ apps/web/src/i18n/locales/es-AR/billing.json | 3 +- .../src/i18n/locales/es-AR/validation.json | 3 + apps/web/src/i18n/locales/pt-BR/admin.json | 44 +++ apps/web/src/i18n/locales/pt-BR/billing.json | 3 +- .../src/i18n/locales/pt-BR/validation.json | 3 + apps/web/src/lib/api.ts | 33 +++ apps/web/src/routeTree.gen.ts | 21 ++ apps/web/src/routes/admin/plans.tsx | 11 + docs/billing.md | 15 +- docs/environment.md | 3 +- packages/shared/src/schemas/admin.ts | 82 +++++- packages/shared/src/schemas/billing.ts | 14 +- 90 files changed, 2642 insertions(+), 104 deletions(-) create mode 100644 apps/backend/prisma/migrations/20261110214656_configurable_plans/migration.sql create mode 100644 apps/backend/src/lib/public-origin.ts create mode 100644 apps/backend/src/modules/admin/features/get-plans/route.ts create mode 100644 apps/backend/src/modules/admin/features/get-plans/use-case.ts create mode 100644 apps/backend/src/modules/admin/features/plan-limits-impact/route.ts create mode 100644 apps/backend/src/modules/admin/features/plan-limits-impact/use-case.ts create mode 100644 apps/backend/src/modules/admin/features/update-plan-limits/route.ts create mode 100644 apps/backend/src/modules/admin/features/update-plan-limits/use-case.ts create mode 100644 apps/backend/src/modules/admin/features/update-plan-price/route.ts create mode 100644 apps/backend/src/modules/admin/features/update-plan-price/use-case.ts create mode 100644 apps/backend/src/modules/billing/features/plans/route.ts create mode 100644 apps/backend/src/modules/billing/features/return/route.ts create mode 100644 apps/backend/src/modules/billing/jobs/apply-price-changes.ts create mode 100644 apps/backend/src/modules/billing/lib/catalog.ts create mode 100644 apps/backend/src/modules/mp/lib/callback-origin.ts create mode 100644 apps/backend/src/modules/payments/features/webhook/route.ts create mode 100644 apps/backend/src/modules/payments/features/webhook/use-case.ts create mode 100644 apps/backend/src/modules/payments/lib/confirm-mp-payment.ts create mode 100644 apps/backend/test/billing-plan-catalog.test.ts create mode 100644 apps/backend/test/billing-return.test.ts create mode 100644 apps/backend/test/mp-preference.test.ts create mode 100644 apps/backend/test/payments-webhook.test.ts create mode 100644 apps/web/src/features/admin/AdminPlansProvider.tsx create mode 100644 apps/web/src/features/admin/AdminPlansView.tsx create mode 100644 apps/web/src/features/admin/LimitInput.tsx create mode 100644 apps/web/src/features/admin/PlanLimitsCard.tsx create mode 100644 apps/web/src/features/admin/PlanPriceRow.tsx create mode 100644 apps/web/src/features/billing/usePlanCatalog.ts create mode 100644 apps/web/src/routes/admin/plans.tsx diff --git a/.env.example b/.env.example index 1bd7d30..5dbcf40 100644 --- a/.env.example +++ b/.env.example @@ -54,6 +54,9 @@ BETTER_AUTH_SECRET="" # son las del OAuth del profesor. Sin las dos, Pro queda "no disponible" (503). # MP_PLATFORM_ACCESS_TOKEN_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/v1/billing/webhooks/stripe. Sin las dos, 503 ahí. diff --git a/AGENTS.md b/AGENTS.md index 9149b33..555804a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web - `src/modules//` — por módulo: `index.ts`, `routes.ts` y `features//{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`. - `src/logger.ts` — pino + pino-pretty. - - Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; 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**. - `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/*`. @@ -39,10 +39,10 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web ## 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`. - **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**. - **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//`. 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. diff --git a/apps/backend/.env.example b/apps/backend/.env.example index 891ba73..e264320 100644 --- a/apps/backend/.env.example +++ b/apps/backend/.env.example @@ -38,6 +38,11 @@ TOKEN_ENCRYPTION_KEY="" # son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503). MP_PLATFORM_ACCESS_TOKEN_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 # 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. diff --git a/apps/backend/prisma/migrations/20261110214656_configurable_plans/migration.sql b/apps/backend/prisma/migrations/20261110214656_configurable_plans/migration.sql new file mode 100644 index 0000000..be828d8 --- /dev/null +++ b/apps/backend/prisma/migrations/20261110214656_configurable_plans/migration.sql @@ -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); diff --git a/apps/backend/prisma/models/billing.prisma b/apps/backend/prisma/models/billing.prisma index 895bab2..9fa3298 100644 --- a/apps/backend/prisma/models/billing.prisma +++ b/apps/backend/prisma/models/billing.prisma @@ -39,6 +39,12 @@ model BillingSubscription { // period, even after a cancellation or a failed renewal. paidThrough DateTime? @map("paid_through") 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") updatedAt DateTime @updatedAt @map("updated_at") @@ -47,6 +53,7 @@ model BillingSubscription { // The reconciliation job walks PENDING and stale AUTHORIZED rows. @@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx") + @@index([pendingAmount], map: "billing_subscriptions_pending_amount_idx") @@map("billing_subscriptions") } @@ -80,3 +87,52 @@ model BillingWebhookEvent { @@index([receivedAt], map: "billing_webhook_events_receivedAt_idx") @@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") + 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") +} diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index 3a064d7..eb3750e 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -25,6 +25,7 @@ import { healthCheckRoutes } from './modules/health-check'; import { homeRoutes } from './modules/home'; import { invitationsRoutes } from './modules/invitations'; import { mpRoutes } from './modules/mp'; +import { mpCallbackOriginMiddleware } from './modules/mp/lib'; import { onboardingRoutes } from './modules/onboarding'; import { paymentsRoutes } from './modules/payments'; 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'); +// 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); // Read-only accounts (Free over its limits) cannot write domain data. Billing, diff --git a/apps/backend/src/http/session-auth.ts b/apps/backend/src/http/session-auth.ts index cf0c3f7..bdb04bf 100644 --- a/apps/backend/src/http/session-auth.ts +++ b/apps/backend/src/http/session-auth.ts @@ -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)) { 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\/[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`. if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') { return true; diff --git a/apps/backend/src/lib/email.ts b/apps/backend/src/lib/email.ts index dd62ad2..d909cdb 100644 --- a/apps/backend/src/lib/email.ts +++ b/apps/backend/src/lib/email.ts @@ -6,6 +6,15 @@ type PasswordResetEmailData = { email: string; url: string; name?: string } type InvitationEmailData = { email: string; url: string; organizationName: string } type StudentEmailConfirmationData = { email: string; url: string; name: string } type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] } +type 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 = { email: string name: string @@ -42,6 +51,7 @@ export interface EmailProvider { sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise + sendProPriceChanged(data: ProPriceChangedData): Promise } // 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), ) } + + 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.

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.

${button(billingUrl, 'Ver mi plan')}`, + ), + ) + } } // Future: transactional providers (Resend, SendGrid, Postmark). diff --git a/apps/backend/src/lib/public-origin.ts b/apps/backend/src/lib/public-origin.ts new file mode 100644 index 0000000..73ccf13 --- /dev/null +++ b/apps/backend/src/lib/public-origin.ts @@ -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 = 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; + } +} diff --git a/apps/backend/src/modules/admin/features/get-account/use-case.ts b/apps/backend/src/modules/admin/features/get-account/use-case.ts index fab9353..b5e30ef 100644 --- a/apps/backend/src/modules/admin/features/get-account/use-case.ts +++ b/apps/backend/src/modules/admin/features/get-account/use-case.ts @@ -1,9 +1,16 @@ import type { PrismaClient } from '@generated/prisma/client'; 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 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'; const RECENT_CHARGES = 12; @@ -13,6 +20,7 @@ type GetAccountDeps = { enforced?: boolean; graceDays?: number; now?: () => Date; + catalog?: PlanCatalogReader; }; /** 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 enforced = this.deps.enforced ?? isBillingEnforced(); 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({ ...summary, planSelectedAt: user.planSelectedAt?.toISOString() ?? null, graceUntil: graceUntil?.toISOString() ?? null, - // Same rule as the PlanGuard: an account without a plan is held to Free. readOnly: - enforced - && exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], { - groups: usage.groupsCount, - attendees: usage.attendeesCount, - }), + enforced && exceedsLimits(limits, { groups: usage.groupsCount, attendees: usage.attendeesCount }), + limits, subscription: summary.subscription && subscription ? { diff --git a/apps/backend/src/modules/admin/features/get-plans/route.ts b/apps/backend/src/modules/admin/features/get-plans/route.ts new file mode 100644 index 0000000..781536d --- /dev/null +++ b/apps/backend/src/modules/admin/features/get-plans/route.ts @@ -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; diff --git a/apps/backend/src/modules/admin/features/get-plans/use-case.ts b/apps/backend/src/modules/admin/features/get-plans/use-case.ts new file mode 100644 index 0000000..3ed3910 --- /dev/null +++ b/apps/backend/src/modules/admin/features/get-plans/use-case.ts @@ -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; + 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> { + 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 }); + } +} diff --git a/apps/backend/src/modules/admin/features/plan-limits-impact/route.ts b/apps/backend/src/modules/admin/features/plan-limits-impact/route.ts new file mode 100644 index 0000000..c650ac5 --- /dev/null +++ b/apps/backend/src/modules/admin/features/plan-limits-impact/route.ts @@ -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; diff --git a/apps/backend/src/modules/admin/features/plan-limits-impact/use-case.ts b/apps/backend/src/modules/admin/features/plan-limits-impact/use-case.ts new file mode 100644 index 0000000..96c95ff --- /dev/null +++ b/apps/backend/src/modules/admin/features/plan-limits-impact/use-case.ts @@ -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; + 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> { + 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 }); + } +} diff --git a/apps/backend/src/modules/admin/features/update-plan-limits/route.ts b/apps/backend/src/modules/admin/features/update-plan-limits/route.ts new file mode 100644 index 0000000..47da175 --- /dev/null +++ b/apps/backend/src/modules/admin/features/update-plan-limits/route.ts @@ -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(); + +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; diff --git a/apps/backend/src/modules/admin/features/update-plan-limits/use-case.ts b/apps/backend/src/modules/admin/features/update-plan-limits/use-case.ts new file mode 100644 index 0000000..8710555 --- /dev/null +++ b/apps/backend/src/modules/admin/features/update-plan-limits/use-case.ts @@ -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; + catalog?: Pick; +}; + +/** 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> { + 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); + } +} diff --git a/apps/backend/src/modules/admin/features/update-plan-price/route.ts b/apps/backend/src/modules/admin/features/update-plan-price/route.ts new file mode 100644 index 0000000..ba087d1 --- /dev/null +++ b/apps/backend/src/modules/admin/features/update-plan-price/route.ts @@ -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(); + +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; diff --git a/apps/backend/src/modules/admin/features/update-plan-price/use-case.ts b/apps/backend/src/modules/admin/features/update-plan-price/use-case.ts new file mode 100644 index 0000000..2b4b492 --- /dev/null +++ b/apps/backend/src/modules/admin/features/update-plan-price/use-case.ts @@ -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; + catalog?: Pick; + /** Kicks the job that pushes queued prices to the providers. */ + applyQueued?: () => Promise; +}; + +/** + * 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> { + 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 }); + } +} diff --git a/apps/backend/src/modules/admin/routes.ts b/apps/backend/src/modules/admin/routes.ts index 1abc5a9..d4f6a7c 100644 --- a/apps/backend/src/modules/admin/routes.ts +++ b/apps/backend/src/modules/admin/routes.ts @@ -1,7 +1,11 @@ import { Hono } from 'hono'; import getAccountRoute from './features/get-account/route'; +import getPlansRoute from './features/get-plans/route'; import listAccountsRoute from './features/list-accounts/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'; const routes = new Hono(); @@ -11,7 +15,13 @@ routes.route('/', meRoute); // Everything below `/me` is the backoffice itself. routes.use('/accounts', adminOnlyMiddleware()); routes.use('/accounts/*', adminOnlyMiddleware()); +routes.use('/plans', adminOnlyMiddleware()); +routes.use('/plans/*', adminOnlyMiddleware()); routes.route('/', listAccountsRoute); routes.route('/', getAccountRoute); +routes.route('/', getPlansRoute); +routes.route('/', planLimitsImpactRoute); +routes.route('/', updatePlanLimitsRoute); +routes.route('/', updatePlanPriceRoute); export default routes; diff --git a/apps/backend/src/modules/billing/features/plans/route.ts b/apps/backend/src/modules/billing/features/plans/route.ts new file mode 100644 index 0000000..1e57160 --- /dev/null +++ b/apps/backend/src/modules/billing/features/plans/route.ts @@ -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; diff --git a/apps/backend/src/modules/billing/features/return/route.ts b/apps/backend/src/modules/billing/features/return/route.ts new file mode 100644 index 0000000..c8bcd5e --- /dev/null +++ b/apps/backend/src/modules/billing/features/return/route.ts @@ -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; diff --git a/apps/backend/src/modules/billing/features/status/use-case.ts b/apps/backend/src/modules/billing/features/status/use-case.ts index 42130ef..114b6e2 100644 --- a/apps/backend/src/modules/billing/features/status/use-case.ts +++ b/apps/backend/src/modules/billing/features/status/use-case.ts @@ -1,17 +1,18 @@ import type { PrismaClient } from '@generated/prisma/client'; import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared'; -import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; +import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared'; import { notFoundResourceProblem } from '@/http/problem-builders'; 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'; /** A PENDING subscription is re-read from Mercado Pago at most this often. */ const PENDING_SYNC_INTERVAL_MS = 30 * 1000; type GetBillingStatusDeps = { - db?: Pick; + db?: Pick; guard?: PlanGuard; + catalog?: PlanCatalogReader; sync?: Pick; providers?: BillingProviderResolver; now?: () => Date; @@ -54,6 +55,24 @@ export class GetBillingStatus { 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({ plan: entitlements.plan, status: subscription?.status ?? null, @@ -65,7 +84,8 @@ export class GetBillingStatus { ? (subscription.nextPaymentDate?.toISOString() ?? null) : 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], country, provider: provider.id, diff --git a/apps/backend/src/modules/billing/features/subscribe/use-case.ts b/apps/backend/src/modules/billing/features/subscribe/use-case.ts index 52ecbe0..dac0189 100644 --- a/apps/backend/src/modules/billing/features/subscribe/use-case.ts +++ b/apps/backend/src/modules/billing/features/subscribe/use-case.ts @@ -1,6 +1,6 @@ import type { PrismaClient } from '@generated/prisma/client'; import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared'; -import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; +import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared'; import { billingNotAvailableProblem, notFoundResourceProblem, @@ -9,15 +9,20 @@ import { } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { logger } from '@/logger'; -import { getWebOrigin } from '@/modules/mp/lib'; -import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib'; +import { + buildSubscriptionBackUrl, + countryOf, + getApiPublicOrigin, + type PlanCatalogReader, planCatalog, subscriptionRefOf } from '../../lib'; import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers'; type SubscribeDeps = { db?: Pick; providers?: BillingProviderResolver; - webOrigin?: string; + /** Public origin of the API, where the provider sends the browser back. */ + apiOrigin?: string; 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 fields = { country, @@ -82,6 +87,10 @@ export class Subscribe { checkoutRef: null, authorizedAt: null, nextPaymentDate: null, + pendingAmount: null, + priceChangeId: null, + priceChangeAttempts: 0, + priceChangeError: null, }, }); @@ -97,7 +106,7 @@ export class Subscribe { amount, currency, payerEmail: input.payerEmail ?? null, - backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo), + backUrl: buildSubscriptionBackUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), input.returnTo), startDate, }); } catch (error) { diff --git a/apps/backend/src/modules/billing/jobs/apply-price-changes.ts b/apps/backend/src/modules/billing/jobs/apply-price-changes.ts new file mode 100644 index 0000000..fa3c04d --- /dev/null +++ b/apps/backend/src/modules/billing/jobs/apply-price-changes.ts @@ -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; + providers?: BillingProviderResolver; + email?: Pick; + 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 { + 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; + } +} diff --git a/apps/backend/src/modules/billing/jobs/index.ts b/apps/backend/src/modules/billing/jobs/index.ts index 01574f3..daf5c80 100644 --- a/apps/backend/src/modules/billing/jobs/index.ts +++ b/apps/backend/src/modules/billing/jobs/index.ts @@ -1,2 +1,3 @@ +export { ApplyPriceChanges, type ApplyPriceChangesTotals, MAX_PRICE_CHANGE_ATTEMPTS } from './apply-price-changes'; export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions'; -export { startBillingJobs } from './schedule'; +export { runPriceChanges, startBillingJobs } from './schedule'; diff --git a/apps/backend/src/modules/billing/jobs/schedule.ts b/apps/backend/src/modules/billing/jobs/schedule.ts index 5e9b60f..faf6b29 100644 --- a/apps/backend/src/modules/billing/jobs/schedule.ts +++ b/apps/backend/src/modules/billing/jobs/schedule.ts @@ -1,7 +1,9 @@ import { logger } from '@/logger'; +import { ApplyPriceChanges } from './apply-price-changes'; import { ReconcileSubscriptions } from './reconcile-subscriptions'; const RECONCILE_CRON = '*/30 * * * *'; +const PRICE_CHANGES_CRON = '*/5 * * * *'; /** * Registers the billing background jobs. Called once from `server.ts`, with the @@ -21,4 +23,27 @@ export function startBillingJobs(): void { }, { tz: 'UTC' }, ).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 { + 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'); + } } diff --git a/apps/backend/src/modules/billing/lib/catalog.ts b/apps/backend/src/modules/billing/lib/catalog.ts new file mode 100644 index 0000000..9159d51 --- /dev/null +++ b/apps/backend/src/modules/billing/lib/catalog.ts @@ -0,0 +1,108 @@ +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; + /** Monthly price of Pro, in the currency of each country. */ + proPrices: Record; +}; + +export function defaultPlanCatalog(): PlanCatalogSnapshot { + return { + limits: { FREE: { ...PLAN_LIMITS.FREE }, PRO: { ...PLAN_LIMITS.PRO } }, + proPrices: { ...PRO_PRICE_BY_COUNTRY }, + }; +} + +type PlanCatalogDeps = { + db?: Pick; + 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 { + 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, + }; + } + 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 { + return (await this.snapshot()).limits[plan]; + } + + async getProPrice(country: CountryCode): Promise { + 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; + +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 }; +} diff --git a/apps/backend/src/modules/billing/lib/config.ts b/apps/backend/src/modules/billing/lib/config.ts index 4dbb7bd..d1ef8c7 100644 --- a/apps/backend/src/modules/billing/lib/config.ts +++ b/apps/backend/src/modules/billing/lib/config.ts @@ -14,3 +14,5 @@ export function getGraceDays(env: Record = process.e const value = Number(env.BILLING_GRACE_DAYS); return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS; } + +export { getApiPublicOrigin } from '@/lib/public-origin'; diff --git a/apps/backend/src/modules/billing/lib/entitlements.ts b/apps/backend/src/modules/billing/lib/entitlements.ts index ab8746d..fa3c787 100644 --- a/apps/backend/src/modules/billing/lib/entitlements.ts +++ b/apps/backend/src/modules/billing/lib/entitlements.ts @@ -1,12 +1,13 @@ import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared'; -import { err, ok, PLAN_LIMITS } from '@gruperly/shared'; +import { err, ok } from '@gruperly/shared'; import { planFeatureRequiredProblem, planLimitReachedProblem, planReadOnlyProblem, } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; +import { type PlanCatalogReader, planCatalog } from './catalog'; import { getGraceDays, isBillingEnforced } from './config'; const DAY_MS = 24 * 60 * 60 * 1000; @@ -90,6 +91,7 @@ type PlanGuardDeps = { enforced?: boolean; graceDays?: number; now?: () => Date; + catalog?: PlanCatalogReader; }; /** @@ -123,7 +125,7 @@ export class PlanGuard { ]); 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 enforced = this.enforced; diff --git a/apps/backend/src/modules/billing/lib/helpers.ts b/apps/backend/src/modules/billing/lib/helpers.ts index e9baf89..aa0d6dd 100644 --- a/apps/backend/src/modules/billing/lib/helpers.ts +++ b/apps/backend/src/modules/billing/lib/helpers.ts @@ -19,8 +19,18 @@ export function countryOf(user: { country: string | null } | null): CountryCode 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`; } diff --git a/apps/backend/src/modules/billing/lib/index.ts b/apps/backend/src/modules/billing/lib/index.ts index 59f697a..8fab2a9 100644 --- a/apps/backend/src/modules/billing/lib/index.ts +++ b/apps/backend/src/modules/billing/lib/index.ts @@ -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 { type Entitlements, exceedsLimits, @@ -9,5 +18,5 @@ export { resolvePlan, type SubscriptionSnapshot, } from './entitlements'; -export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers'; +export { buildSubscriptionBackUrl, buildSubscriptionReturnUrl, countryOf, toBillingChargeDto } from './helpers'; export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync'; diff --git a/apps/backend/src/modules/billing/providers/billing-provider.ts b/apps/backend/src/modules/billing/providers/billing-provider.ts index 3b4eb39..a35c61c 100644 --- a/apps/backend/src/modules/billing/providers/billing-provider.ts +++ b/apps/backend/src/modules/billing/providers/billing-provider.ts @@ -105,6 +105,8 @@ export interface BillingProvider { /** `null` while the professor has not completed the checkout. */ fetch(ref: SubscriptionRef): Promise; listCharges(ref: SubscriptionRef & { externalId: string }): Promise; + /** New monthly amount from the next charge on; what was already charged stays. */ + updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise; /** Stops the monthly charge, or voids a checkout never completed. */ cancel(ref: SubscriptionRef): Promise; parseWebhook(request: BillingWebhookRequest): Promise>; diff --git a/apps/backend/src/modules/billing/providers/mercado-pago/index.ts b/apps/backend/src/modules/billing/providers/mercado-pago/index.ts index abe05ae..0fd28ed 100644 --- a/apps/backend/src/modules/billing/providers/mercado-pago/index.ts +++ b/apps/backend/src/modules/billing/providers/mercado-pago/index.ts @@ -137,6 +137,13 @@ export class MercadoPagoBillingProvider implements BillingProvider { await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId); } + async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise { + 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 * with its own secret. Mercado Pago signs a manifest of the notified id, the diff --git a/apps/backend/src/modules/billing/providers/mercado-pago/preapproval.ts b/apps/backend/src/modules/billing/providers/mercado-pago/preapproval.ts index af0b49b..fefd21d 100644 --- a/apps/backend/src/modules/billing/providers/mercado-pago/preapproval.ts +++ b/apps/backend/src/modules/billing/providers/mercado-pago/preapproval.ts @@ -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 { + 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): MpAuthorizedPayment { const payment = (payload.payment ?? null) as Record | null; return { @@ -181,6 +198,7 @@ export type PreapprovalClient = { createPreapproval: typeof createPreapproval; getPreapproval: typeof getPreapproval; cancelPreapproval: typeof cancelPreapproval; + updatePreapprovalAmount: typeof updatePreapprovalAmount; getAuthorizedPayment: typeof getAuthorizedPayment; searchAuthorizedPayments: typeof searchAuthorizedPayments; }; @@ -189,6 +207,7 @@ export const mpPreapprovalClient: PreapprovalClient = { createPreapproval, getPreapproval, cancelPreapproval, + updatePreapprovalAmount, getAuthorizedPayment, searchAuthorizedPayments, }; diff --git a/apps/backend/src/modules/billing/providers/stripe/index.ts b/apps/backend/src/modules/billing/providers/stripe/index.ts index ef2bf0b..1028f75 100644 --- a/apps/backend/src/modules/billing/providers/stripe/index.ts +++ b/apps/backend/src/modules/billing/providers/stripe/index.ts @@ -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 { + 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. */ async parseWebhook( request: BillingWebhookRequest, diff --git a/apps/backend/src/modules/billing/routes.ts b/apps/backend/src/modules/billing/routes.ts index 7d8b587..4071e57 100644 --- a/apps/backend/src/modules/billing/routes.ts +++ b/apps/backend/src/modules/billing/routes.ts @@ -1,6 +1,8 @@ import { Hono } from 'hono'; import cancelRoute from './features/cancel/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 subscribeRoute from './features/subscribe/route'; import webhookRoute from './features/webhook/route'; @@ -11,6 +13,8 @@ routes.route('/', statusRoute); routes.route('/', subscribeRoute); routes.route('/', cancelRoute); routes.route('/', chargesRoute); +routes.route('/', plansRoute); +routes.route('/', returnRoute); routes.route('/', webhookRoute); export default routes; diff --git a/apps/backend/src/modules/mp/features/callback/route.ts b/apps/backend/src/modules/mp/features/callback/route.ts index 2ac60bd..15e44d9 100644 --- a/apps/backend/src/modules/mp/features/callback/route.ts +++ b/apps/backend/src/modules/mp/features/callback/route.ts @@ -25,8 +25,14 @@ route.get('/', validate.query(MpCallbackQuerySchema), async (c) => { return c.redirect(new URL('/login', getWebOrigin()).toString()); } - const useCase = new CompleteMpAuthorization(); - const result = await useCase.execute({ code, state, error }); + let result: Awaited>; + 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) { logger.warn( diff --git a/apps/backend/src/modules/mp/features/callback/use-case.ts b/apps/backend/src/modules/mp/features/callback/use-case.ts index 6114478..c457f59 100644 --- a/apps/backend/src/modules/mp/features/callback/use-case.ts +++ b/apps/backend/src/modules/mp/features/callback/use-case.ts @@ -39,6 +39,8 @@ export class CompleteMpAuthorization { code?: string; state?: string; error?: string; + /** The signed-in teacher; has to be the one who started the flow. */ + userId: string; }): Promise> { let config: ReturnType; try { @@ -70,6 +72,14 @@ export class CompleteMpAuthorization { 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 // means someone replayed a state we already consumed. const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } }); diff --git a/apps/backend/src/modules/mp/lib/callback-origin.ts b/apps/backend/src/modules/mp/lib/callback-origin.ts new file mode 100644 index 0000000..31ad158 --- /dev/null +++ b/apps/backend/src/modules/mp/lib/callback-origin.ts @@ -0,0 +1,39 @@ +import type { MiddlewareHandler } from 'hono'; + +type Env = Record; + +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(); +}; diff --git a/apps/backend/src/modules/mp/lib/index.ts b/apps/backend/src/modules/mp/lib/index.ts index 76d252d..bcacbf4 100644 --- a/apps/backend/src/modules/mp/lib/index.ts +++ b/apps/backend/src/modules/mp/lib/index.ts @@ -1,3 +1,4 @@ +export { mpCallbackBounceUrl, mpCallbackOriginMiddleware } from './callback-origin'; export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config'; export { codeChallengeFromVerifier, diff --git a/apps/backend/src/modules/mp/lib/mp-http.ts b/apps/backend/src/modules/mp/lib/mp-http.ts index 680c6ec..7ddf40e 100644 --- a/apps/backend/src/modules/mp/lib/mp-http.ts +++ b/apps/backend/src/modules/mp/lib/mp-http.ts @@ -13,6 +13,8 @@ export type MpCreatePreferenceInput = { externalReference: string; /** Where the buyer lands after paying (pending/success/failure). */ backUrl: string; + /** Where Mercado Pago notifies the payment (`POST /payments/webhooks/mp/:id`). */ + notificationUrl?: string; }; export type MpPreference = { @@ -21,6 +23,21 @@ export type MpPreference = { 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 * *link*: nothing is charged, and creating it again after a lost connection is @@ -50,7 +67,10 @@ export async function createCheckoutPreference( }, ], external_reference: input.externalReference, - auto_return: 'approved', + ...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}), + ...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl) + ? { notification_url: input.notificationUrl } + : {}), back_urls: { success: input.backUrl, pending: input.backUrl, @@ -120,9 +140,10 @@ export async function searchMpPaymentByExternalReference( const payload = (await response.json()) as { results?: Record[] } | null; const results = payload?.results ?? []; - const match = results.find( - (payment) => payment.external_reference === externalReference, - ); + // A rejected attempt and a later approved one share the reference: the + // 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) { return null; } diff --git a/apps/backend/src/modules/payments/features/create-batch/use-case.ts b/apps/backend/src/modules/payments/features/create-batch/use-case.ts index 9a57861..d0b9df0 100644 --- a/apps/backend/src/modules/payments/features/create-batch/use-case.ts +++ b/apps/backend/src/modules/payments/features/create-batch/use-case.ts @@ -15,17 +15,20 @@ import { notFoundResourceProblem, } from '@/http/problem-builders'; 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, MpApiError } from '@/modules/mp/lib'; -import { CHECKOUT_BACK_PATH } from '../../lib'; +import { CHECKOUT_BACK_PATH, paymentNotificationUrl } from '../../lib'; type BatchDeps = { db?: Pick; createPreference?: typeof createCheckoutPreference; getToken?: typeof getMpAccessToken; webOrigin?: string; + /** Public origin of the API, where Mercado Pago notifies the payment. */ + apiOrigin?: string; planGuard?: Pick; }; @@ -128,6 +131,7 @@ export class CreatePaymentBatch { currencyId: currency, externalReference: payment.id, backUrl, + notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id), }); link = preference; } catch (error) { diff --git a/apps/backend/src/modules/payments/features/renew/use-case.ts b/apps/backend/src/modules/payments/features/renew/use-case.ts index 1766487..755bf81 100644 --- a/apps/backend/src/modules/payments/features/renew/use-case.ts +++ b/apps/backend/src/modules/payments/features/renew/use-case.ts @@ -8,17 +8,20 @@ import { notFoundResourceProblem, } from '@/http/problem-builders'; 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 { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from '../../lib'; +import { CHECKOUT_BACK_PATH, type PaymentRecord, paymentNotificationUrl, toPaymentDto } from '../../lib'; type RenewDeps = { db?: Pick; createPreference?: typeof createCheckoutPreference; getToken?: typeof getMpAccessToken; webOrigin?: string; + /** Public origin of the API, where Mercado Pago notifies the payment. */ + apiOrigin?: string; planGuard?: Pick; }; @@ -94,6 +97,7 @@ export class RenewPaymentLink { currencyId: currency, externalReference: payment.id, backUrl, + notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id), }); } catch (error) { if (error instanceof Error) { diff --git a/apps/backend/src/modules/payments/features/webhook/route.ts b/apps/backend/src/modules/payments/features/webhook/route.ts new file mode 100644 index 0000000..2f5ea7e --- /dev/null +++ b/apps/backend/src/modules/payments/features/webhook/route.ts @@ -0,0 +1,17 @@ +import { Hono } from 'hono'; +import { problemJson } from '@/http/problem-details'; +import { 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 }); +}); + +export default route; diff --git a/apps/backend/src/modules/payments/features/webhook/use-case.ts b/apps/backend/src/modules/payments/features/webhook/use-case.ts new file mode 100644 index 0000000..0f0a0bd --- /dev/null +++ b/apps/backend/src/modules/payments/features/webhook/use-case.ts @@ -0,0 +1,45 @@ +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 ConfirmMpPaymentDeps, type ConfirmMpPaymentOutcome, confirmMpPayment } from '../../lib'; + +type HandleMpPaymentNotificationDeps = ConfirmMpPaymentDeps & { + db?: Pick; +}; + +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> { + 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()); + } + } +} diff --git a/apps/backend/src/modules/payments/jobs/reconcile-payments.ts b/apps/backend/src/modules/payments/jobs/reconcile-payments.ts index bc2048c..9e8877a 100644 --- a/apps/backend/src/modules/payments/jobs/reconcile-payments.ts +++ b/apps/backend/src/modules/payments/jobs/reconcile-payments.ts @@ -3,15 +3,13 @@ import prisma from '@/lib/prisma'; import { logger } from '@/logger'; import { getMpAccessToken } from '@/modules/mp'; import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib'; +import { confirmMpPayment } from '../lib'; /** - * Pulls payments from Mercado Pago instead of trusting a webhook. A payment - * link is just a preference until someone pays it; this job asks the seller's - * account for our `external_reference` and marks approved payments as PAID. - * - * 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. + * Pulls payments from Mercado Pago. The notification + * (`POST /payments/webhooks/mp/:id`) confirms them right away; this job is the + * fallback for links created before it existed and for lost notifications. + * Both go through `confirmMpPayment`. */ const RECONCILE_AFTER_MS = 5 * 60 * 1000; const BATCH_LIMIT = 50; @@ -51,34 +49,21 @@ export class ReconcilePayments { const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 }; 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 { - const found = await search(token.value.accessToken, payment.id); - if (found && found.status === 'approved' && found.externalReference === payment.id) { - await db.payment.update({ - where: { id: payment.id }, - data: { - status: 'PAID', - mpPaymentId: found.id, - paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(), - }, - }); - totals.paid += 1; - } + const outcome = await confirmMpPayment( + db, + { id: payment.id, ownerId: payment.group.createdById }, + { getToken, search }, + ); + // No usable token is not a payment problem: the row stays PENDING and + // the account notice tells the professor what to do. + if (outcome === 'no_token') totals.skipped += 1; + if (outcome === 'paid') totals.paid += 1; } catch (error) { - if (error instanceof MpApiError) { - totals.failed += 1; - } else { + if (!(error instanceof MpApiError)) { logger.error({ err: error }, 'Unexpected payment reconciliation failure'); - totals.failed += 1; } + totals.failed += 1; } } diff --git a/apps/backend/src/modules/payments/lib/confirm-mp-payment.ts b/apps/backend/src/modules/payments/lib/confirm-mp-payment.ts new file mode 100644 index 0000000..7609497 --- /dev/null +++ b/apps/backend/src/modules/payments/lib/confirm-mp-payment.ts @@ -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, + payment: { id: string; ownerId: string }, + deps: ConfirmMpPaymentDeps = {}, +): Promise { + 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`; +} diff --git a/apps/backend/src/modules/payments/lib/index.ts b/apps/backend/src/modules/payments/lib/index.ts index e75766d..6131111 100644 --- a/apps/backend/src/modules/payments/lib/index.ts +++ b/apps/backend/src/modules/payments/lib/index.ts @@ -1 +1,7 @@ +export { + type ConfirmMpPaymentDeps, + type ConfirmMpPaymentOutcome, + confirmMpPayment, + paymentNotificationUrl, +} from './confirm-mp-payment'; export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers'; diff --git a/apps/backend/src/modules/payments/routes.ts b/apps/backend/src/modules/payments/routes.ts index 8d5676c..0545a6f 100644 --- a/apps/backend/src/modules/payments/routes.ts +++ b/apps/backend/src/modules/payments/routes.ts @@ -3,6 +3,7 @@ import getAllRoute from './features/get-all/route'; import renewRoute from './features/renew/route'; import reportedRoute from './features/reported/route'; import transferDetailsRoute from './features/transfer-details/route'; +import webhookRoute from './features/webhook/route'; const routes = new Hono(); @@ -10,5 +11,6 @@ routes.route('/', getAllRoute); routes.route('/', reportedRoute); routes.route('/', transferDetailsRoute); routes.route('/', renewRoute); +routes.route('/', webhookRoute); export default routes; \ No newline at end of file diff --git a/apps/backend/test/admin.test.ts b/apps/backend/test/admin.test.ts index ab27bd9..f24a307 100644 --- a/apps/backend/test/admin.test.ts +++ b/apps/backend/test/admin.test.ts @@ -114,6 +114,25 @@ describe('admin access', () => { expect(db.user.findUnique).not.toHaveBeenCalled(); }); + it('forbids the plans to anyone outside the allowlist', async () => { + const app = makeApp('profe@gmail.com'); + expect((await app.request('/admin/plans')).status).toBe(403); + expect((await app.request('/admin/plans/FREE/impact?maxGroups=1')).status).toBe(403); + const json = { 'Content-Type': 'application/json' }; + const limits = await app.request('/admin/plans/FREE/limits', { + method: 'PUT', + headers: json, + body: JSON.stringify({ maxGroups: 1, maxAttendees: 1, whatsappAutomations: false, mpCharges: false }), + }); + expect(limits.status).toBe(403); + const price = await app.request('/admin/plans/prices/AR', { + method: 'PUT', + headers: json, + body: JSON.stringify({ amount: 1, applyToExisting: true }), + }); + expect(price.status).toBe(403); + }); + it('asks for a session without a user', async () => { const response = await makeApp(null).request('/admin/accounts'); expect(response.status).toBe(401); diff --git a/apps/backend/test/billing-entitlements.test.ts b/apps/backend/test/billing-entitlements.test.ts index 5dc8687..572d0b9 100644 --- a/apps/backend/test/billing-entitlements.test.ts +++ b/apps/backend/test/billing-entitlements.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, mock } from 'bun:test'; +import { staticPlanCatalog } from '@/modules/billing/lib/catalog'; import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements'; const now = new Date('2026-10-22T12:00:00.000Z'); @@ -18,7 +19,7 @@ function makeDb(params: { } function makeGuard(db: ReturnType, enforced = true) { - return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now }); + return new PlanGuard({ db: db as never, enforced, graceDays: 7, now: () => now, catalog: staticPlanCatalog() }); } describe('resolvePlan', () => { diff --git a/apps/backend/test/billing-plan-catalog.test.ts b/apps/backend/test/billing-plan-catalog.test.ts new file mode 100644 index 0000000..cd7d373 --- /dev/null +++ b/apps/backend/test/billing-plan-catalog.test.ts @@ -0,0 +1,266 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'; +import { UpdatePlanPrice } from '@/modules/admin/features/update-plan-price/use-case'; +import { ApplyPriceChanges } from '@/modules/billing/jobs/apply-price-changes'; +import { defaultPlanCatalog, PlanCatalog, PlanGuard, staticPlanCatalog } from '@/modules/billing/lib'; +import { MercadoPagoBillingProvider } from '@/modules/billing/providers/mercado-pago'; +import { StripeBillingProvider } from '@/modules/billing/providers/stripe'; + +const decimal = (value: number) => ({ toString: () => String(value) }); + +function catalogDb(configs: unknown[] = [], prices: unknown[] = []) { + return { + planConfig: { findMany: mock(async () => configs) }, + planPrice: { findMany: mock(async () => prices) }, + }; +} + +describe('PlanCatalog', () => { + it('falls back to the shared defaults when the tables are empty', async () => { + const catalog = new PlanCatalog({ db: catalogDb() as never }); + expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE); + expect(await catalog.getProPrice('AR')).toBe(PRO_PRICE_BY_COUNTRY.AR); + }); + + it('reads the limits and prices edited from the backoffice', async () => { + const db = catalogDb( + [{ plan: 'FREE', maxGroups: 2, maxAttendees: 30, whatsappAutomations: true, mpCharges: false }], + [{ country: 'AR', amount: decimal(18000) }, { country: 'XX', amount: decimal(1) }], + ); + const catalog = new PlanCatalog({ db: db as never }); + expect(await catalog.getLimits('FREE')).toEqual({ + maxGroups: 2, + maxAttendees: 30, + whatsappAutomations: true, + mpCharges: false, + }); + expect(await catalog.getLimits('PRO')).toEqual(PLAN_LIMITS.PRO); + expect(await catalog.getProPrice('AR')).toBe(18000); + expect(await catalog.getProPrice('MX')).toBe(PRO_PRICE_BY_COUNTRY.MX); + }); + + it('caches within the TTL until invalidated', async () => { + let clock = 0; + const db = catalogDb(); + const catalog = new PlanCatalog({ db: db as never, ttlMs: 1000, now: () => clock }); + await catalog.snapshot(); + clock = 500; + await catalog.snapshot(); + expect(db.planConfig.findMany).toHaveBeenCalledTimes(1); + catalog.invalidate(); + await catalog.snapshot(); + expect(db.planConfig.findMany).toHaveBeenCalledTimes(2); + clock = 2000; + await catalog.snapshot(); + expect(db.planConfig.findMany).toHaveBeenCalledTimes(3); + }); + + it('keeps working on the defaults if the database fails, without caching them', async () => { + const db = { + planConfig: { findMany: mock(async () => Promise.reject(new Error('down'))) }, + planPrice: { findMany: mock(async () => []) }, + }; + const catalog = new PlanCatalog({ db: db as never }); + expect(await catalog.getLimits('FREE')).toEqual(PLAN_LIMITS.FREE); + await catalog.snapshot(); + expect(db.planConfig.findMany).toHaveBeenCalledTimes(2); + }); + + it('feeds the PlanGuard', async () => { + const snapshot = defaultPlanCatalog(); + snapshot.limits.FREE = { ...snapshot.limits.FREE, maxGroups: 3 }; + const guard = new PlanGuard({ + enforced: true, + catalog: staticPlanCatalog(snapshot), + db: { + billingSubscription: { findUnique: async () => null }, + group: { count: async () => 2 }, + person: { count: async () => 0 }, + } as never, + }); + expect((await guard.canCreateGroup('owner-1')).ok).toBe(true); + }); +}); + +function priceTx(updated = 3) { + const tx = { + planPrice: { upsert: mock(async () => ({})) }, + planPriceChange: { create: mock(async () => ({ id: 'change-1' })), update: mock(async () => ({})) }, + billingSubscription: { updateMany: mock(async () => ({ count: updated })) }, + }; + const db = { $transaction: mock(async (run: (client: typeof tx) => unknown) => run(tx)) }; + return { tx, db }; +} + +describe('UpdatePlanPrice', () => { + const catalog = { invalidate: mock(), getProPrice: mock(async () => 15000) }; + + it('queues the live subscriptions of the country and kicks the job', async () => { + const { tx, db } = priceTx(3); + const applyQueued = mock(async () => {}); + const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute( + 'AR', + { amount: 18000, applyToExisting: true }, + 'staff-1', + ); + + expect(result).toEqual({ ok: true, value: { country: 'AR', amount: 18000, queued: 3 } }); + expect(tx.planPrice.upsert).toHaveBeenCalled(); + expect(tx.planPriceChange.create.mock.calls[0]?.[0]).toMatchObject({ + data: { country: 'AR', previousAmount: 15000, newAmount: 18000, currency: 'ARS', applyToExisting: true }, + }); + expect(tx.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({ + where: { + country: 'AR', + status: { in: ['AUTHORIZED', 'PAUSED'] }, + externalId: { not: null }, + }, + }); + expect(tx.planPriceChange.update).toHaveBeenCalledWith({ where: { id: 'change-1' }, data: { queued: 3 } }); + expect(catalog.invalidate).toHaveBeenCalled(); + expect(applyQueued).toHaveBeenCalledTimes(1); + }); + + it('only changes the price for new subscriptions when not applied to existing ones', async () => { + const { tx, db } = priceTx(); + const applyQueued = mock(async () => {}); + const result = await new UpdatePlanPrice({ db: db as never, catalog, applyQueued }).execute( + 'AR', + { amount: 18000, applyToExisting: false }, + 'staff-1', + ); + expect(result.ok && result.value.queued).toBe(0); + expect(tx.billingSubscription.updateMany).not.toHaveBeenCalled(); + expect(applyQueued).not.toHaveBeenCalled(); + }); +}); + +function row(overrides: Record = {}) { + return { + id: 'sub-1', + country: 'AR', + currency: 'ARS', + provider: 'MERCADO_PAGO', + status: 'AUTHORIZED', + externalId: 'pre-1', + checkoutRef: null, + amount: decimal(15000), + pendingAmount: decimal(18000), + nextPaymentDate: new Date('2026-12-05T12:00:00.000Z'), + user: { name: 'Ana', email: 'ana@gruperly.test', country: 'AR' }, + ...overrides, + }; +} + +function applyHarness(rows: unknown[], { fail = false, moved = 1 } = {}) { + const db = { + billingSubscription: { + findMany: mock(async () => rows), + updateMany: mock(async () => ({ count: moved })), + }, + }; + const provider = { + updateAmount: mock(async () => { + if (fail) throw new Error('boom'); + }), + }; + const email = { sendProPriceChanged: mock(async () => {}) }; + const job = new ApplyPriceChanges({ + db: db as never, + providers: () => provider as never, + email, + webOrigin: 'http://web', + }); + return { db, provider, email, job }; +} + +describe('ApplyPriceChanges', () => { + it('pushes the price to the provider, moves it to amount and emails the professor', async () => { + const pending = row(); + const { db, provider, email, job } = applyHarness([pending]); + + expect(await job.execute()).toEqual({ applied: 1, failed: 0, dropped: 0 }); + expect(provider.updateAmount).toHaveBeenCalledWith( + { country: 'AR', externalId: 'pre-1', checkoutRef: null }, + 18000, + 'ARS', + ); + expect(db.billingSubscription.updateMany).toHaveBeenCalledWith({ + where: { id: 'sub-1', pendingAmount: pending.pendingAmount }, + data: { amount: pending.pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null }, + }); + expect(email.sendProPriceChanged).toHaveBeenCalledTimes(1); + const sent = (email.sendProPriceChanged.mock.calls[0] as unknown[])[0] as Record; + expect(sent).toMatchObject({ email: 'ana@gruperly.test', name: 'Ana', billingUrl: 'http://web/billing' }); + expect(sent.amount).toContain('18.000'); + }); + + it('counts a refusal as an attempt and keeps the change queued', async () => { + const { db, email, job } = applyHarness([row()], { fail: true }); + expect(await job.execute()).toEqual({ applied: 0, failed: 1, dropped: 0 }); + expect(db.billingSubscription.updateMany.mock.calls[0]?.[0]).toMatchObject({ + data: { priceChangeAttempts: { increment: 1 }, priceChangeError: 'provider_error' }, + }); + expect(email.sendProPriceChanged).not.toHaveBeenCalled(); + }); + + it('drops the change of a subscription cancelled meanwhile', async () => { + const { provider, job } = applyHarness([row({ status: 'CANCELLED' })]); + expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 1 }); + expect(provider.updateAmount).not.toHaveBeenCalled(); + }); + + it('does not email twice when another instance already applied it', async () => { + const { email, job } = applyHarness([row()], { moved: 0 }); + expect(await job.execute()).toEqual({ applied: 0, failed: 0, dropped: 0 }); + expect(email.sendProPriceChanged).not.toHaveBeenCalled(); + }); +}); + +describe('updateAmount', () => { + it('Mercado Pago changes the preapproval amount', async () => { + const client = { updatePreapprovalAmount: mock(async () => ({})) }; + const provider = new MercadoPagoBillingProvider({ + client: client as never, + credentials: () => ({ accessToken: 'platform-token', webhookSecret: 'secret' }), + }); + await provider.updateAmount({ country: 'AR', externalId: 'pre-1', checkoutRef: null }, 18000, 'ARS'); + expect(client.updatePreapprovalAmount).toHaveBeenCalledWith('platform-token', 'pre-1', { + amount: 18000, + currencyId: 'ARS', + }); + }); + + it('Stripe reprices the item on its product without proration', async () => { + const calls: { method: string; path: string; body: URLSearchParams | null }[] = []; + const fetch = mock(async (input: string, init: RequestInit) => { + const method = init.method ?? 'GET'; + calls.push({ + method, + path: new URL(input).pathname, + body: init.body ? new URLSearchParams(String(init.body)) : null, + }); + return new Response( + JSON.stringify({ id: 'sub_1', items: { data: [{ id: 'si_1', price: { product: 'prod_1' } }] } }), + ); + }); + const provider = new StripeBillingProvider({ + config: () => ({ secretKey: 'sk_test', webhookSecret: 'whsec' }), + fetch: fetch as never, + }); + + await provider.updateAmount({ country: 'MX', externalId: 'sub_1', checkoutRef: null }, 249, 'MXN'); + + expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual([ + 'GET /v1/subscriptions/sub_1', + 'POST /v1/subscriptions/sub_1', + ]); + const body = calls[1]?.body; + expect(body?.get('proration_behavior')).toBe('none'); + expect(body?.get('items[0][id]')).toBe('si_1'); + expect(body?.get('items[0][price_data][product]')).toBe('prod_1'); + expect(body?.get('items[0][price_data][unit_amount]')).toBe('24900'); + expect(body?.get('items[0][price_data][currency]')).toBe('mxn'); + expect(body?.get('items[0][price_data][recurring][interval]')).toBe('month'); + }); +}); diff --git a/apps/backend/test/billing-return.test.ts b/apps/backend/test/billing-return.test.ts new file mode 100644 index 0000000..3937112 --- /dev/null +++ b/apps/backend/test/billing-return.test.ts @@ -0,0 +1,55 @@ +import { afterEach, describe, expect, it } from 'bun:test'; +import { Hono } from 'hono'; +import { isPublicApiRequest } from '@/http/session-auth'; +import returnRoute from '@/modules/billing/features/return/route'; +import { getApiPublicOrigin } from '@/modules/billing/lib'; + +const previousWebUrl = process.env.WEB_URL; + +function makeApp() { + return new Hono().basePath('/api/v1').route('/billing', returnRoute); +} + +describe('GET /billing/return', () => { + afterEach(() => { + process.env.WEB_URL = previousWebUrl; + }); + + it('bounces the browser to the billing screen of the web', async () => { + process.env.WEB_URL = 'https://app.example.com'; + const res = await makeApp().request('/api/v1/billing/return?to=billing&preapproval_id=pre-1'); + + expect(res.status).toBe(302); + expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return'); + }); + + it('goes back to the onboarding step when it started there', async () => { + process.env.WEB_URL = 'https://app.example.com'; + const res = await makeApp().request('/api/v1/billing/return?to=onboarding'); + + expect(res.headers.get('location')).toBe('https://app.example.com/onboarding?sub=return'); + }); + + it('never redirects anywhere but the web', async () => { + process.env.WEB_URL = 'https://app.example.com'; + const res = await makeApp().request('/api/v1/billing/return?to=https://evil.example'); + + expect(res.headers.get('location')).toBe('https://app.example.com/billing?sub=return'); + }); + + it('is reachable without a session', () => { + expect(isPublicApiRequest('GET', '/api/v1/billing/return')).toBe(true); + expect(isPublicApiRequest('POST', '/api/v1/billing/return')).toBe(false); + }); +}); + +describe('getApiPublicOrigin', () => { + it('prefers API_PUBLIC_URL, then BETTER_AUTH_URL, then localhost', () => { + expect( + getApiPublicOrigin({ API_PUBLIC_URL: 'https://x.ngrok-free.app/', BETTER_AUTH_URL: 'http://localhost:4000' }), + ).toBe('https://x.ngrok-free.app'); + expect(getApiPublicOrigin({ BETTER_AUTH_URL: 'https://app.example.com' })).toBe('https://app.example.com'); + expect(getApiPublicOrigin({})).toBe('http://localhost:4000'); + expect(getApiPublicOrigin({ API_PUBLIC_URL: 'not a url' })).toBe('http://localhost:4000'); + }); +}); diff --git a/apps/backend/test/billing-subscribe.test.ts b/apps/backend/test/billing-subscribe.test.ts index 121c7b9..f066717 100644 --- a/apps/backend/test/billing-subscribe.test.ts +++ b/apps/backend/test/billing-subscribe.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test'; import { CancelSubscription } from '@/modules/billing/features/cancel/use-case'; import { Subscribe } from '@/modules/billing/features/subscribe/use-case'; +import { staticPlanCatalog } from '@/modules/billing/lib/catalog'; import type { BillingProvider } from '@/modules/billing/providers'; import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago'; @@ -53,7 +54,7 @@ function subscribe(db: ReturnType, client = makeClient()) { return { client, run: (returnTo: 'billing' | 'onboarding' = 'billing') => - new Subscribe({ db: db as never, providers: () => provider, webOrigin: 'http://web', now: () => now }).execute( + new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider, apiOrigin: 'https://api', now: () => now }).execute( userId, { payerEmail: 'profe@mail.com', returnTo }, ), @@ -79,7 +80,7 @@ describe('Subscribe', () => { payerEmail: 'profe@mail.com', amount: 15000, currencyId: 'ARS', - backUrl: 'http://web/billing?sub=return', + backUrl: 'https://api/api/v1/billing/return?to=billing', startDate: undefined, }); expect(db.billingSubscription.update).toHaveBeenCalledWith({ @@ -93,7 +94,7 @@ describe('Subscribe', () => { await run('onboarding'); expect((client.createPreapproval as ReturnType).mock.calls[0]?.[1]).toMatchObject({ - backUrl: 'http://web/onboarding?sub=return', + backUrl: 'https://api/api/v1/billing/return?to=onboarding', }); }); @@ -131,7 +132,7 @@ describe('Subscribe', () => { const db = makeDb(null, 'AR'); const client = makeClient(); const provider = new MercadoPagoBillingProvider({ client, credentials: () => null }); - const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, { + const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, { payerEmail: 'profe@mail.com', returnTo: 'billing', }); @@ -224,13 +225,13 @@ describe('Subscribe outside Argentina (Stripe)', () => { const stripe = fakeStripe(); const resolved: string[] = []; - const result = await new Subscribe({ + const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: (id) => { resolved.push(id); return stripe; }, - webOrigin: 'http://web', + apiOrigin: 'https://api', now: () => now, }).execute(userId, { returnTo: 'billing' }); @@ -242,7 +243,7 @@ describe('Subscribe outside Argentina (Stripe)', () => { amount: 199, currency: 'MXN', payerEmail: null, - backUrl: 'http://web/billing?sub=return', + backUrl: 'https://api/api/v1/billing/return?to=billing', startDate: undefined, }); expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record }])[0].create).toMatchObject({ @@ -261,10 +262,10 @@ describe('Subscribe outside Argentina (Stripe)', () => { const mp = mpProvider(client); const stripe = fakeStripe(); - await new Subscribe({ + await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe), - webOrigin: 'http://web', + apiOrigin: 'https://api', now: () => now, }).execute(userId, { returnTo: 'billing' }); @@ -275,7 +276,7 @@ describe('Subscribe outside Argentina (Stripe)', () => { const db = makeDb(null, 'CL'); const stripe = fakeStripe({ isAvailable: () => false }); - const result = await new Subscribe({ db: db as never, providers: () => stripe }).execute(userId, { + const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => stripe }).execute(userId, { returnTo: 'billing', }); @@ -288,7 +289,7 @@ describe('Subscribe outside Argentina (Stripe)', () => { const db = makeDb(null, 'AR'); const provider = mpProvider(makeClient()); - const result = await new Subscribe({ db: db as never, providers: () => provider }).execute(userId, { + const result = await new Subscribe({ catalog: staticPlanCatalog(), db: db as never, providers: () => provider }).execute(userId, { returnTo: 'billing', }); diff --git a/apps/backend/test/mp-preference.test.ts b/apps/backend/test/mp-preference.test.ts new file mode 100644 index 0000000..60f1af4 --- /dev/null +++ b/apps/backend/test/mp-preference.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it } from 'bun:test'; +import { createCheckoutPreference, isPublicHttpsUrl, searchMpPaymentByExternalReference } from '@/modules/mp/lib/mp-http'; + +describe('isPublicHttpsUrl', () => { + it('only asks Mercado Pago for the automatic return on public HTTPS', () => { + expect(isPublicHttpsUrl('https://app.gruperly.com/student/payments')).toBe(true); + expect(isPublicHttpsUrl('http://localhost:6173/student/payments')).toBe(false); + expect(isPublicHttpsUrl('https://localhost:6173/student/payments')).toBe(false); + expect(isPublicHttpsUrl('http://app.gruperly.com/student/payments')).toBe(false); + expect(isPublicHttpsUrl('not a url')).toBe(false); + }); +}); + +describe('createCheckoutPreference', () => { + const realFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = realFetch; + }); + + async function sentBody(input: { backUrl: string; notificationUrl?: string }) { + let body: Record = {}; + globalThis.fetch = (async (_url: string, init: RequestInit) => { + body = JSON.parse(String(init.body)); + return new Response(JSON.stringify({ id: 'pref-1', init_point: 'https://mp/pay' }), { status: 201 }); + }) as unknown as typeof fetch; + await createCheckoutPreference('token', { + title: 'Octubre', + unitPrice: 100, + currencyId: 'ARS', + externalReference: 'pay-1', + ...input, + }); + return body; + } + + it('asks for the automatic return and the notification on public HTTPS', async () => { + const body = await sentBody({ + backUrl: 'https://app.gruperly.com/student/payments', + notificationUrl: 'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks', + }); + expect(body.auto_return).toBe('approved'); + expect(body.notification_url).toBe( + 'https://app.gruperly.com/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks', + ); + }); + + it('leaves both out on localhost, which Mercado Pago refuses', async () => { + const body = await sentBody({ + backUrl: 'http://localhost:6173/student/payments', + notificationUrl: 'http://localhost:4000/api/v1/payments/webhooks/mp/pay-1', + }); + expect(body).not.toHaveProperty('auto_return'); + expect(body).not.toHaveProperty('notification_url'); + }); +}); + +describe('searchMpPaymentByExternalReference', () => { + const realFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = realFetch; + }); + + it('prefers the approved attempt over an earlier rejected one', async () => { + globalThis.fetch = (async () => + new Response( + JSON.stringify({ + results: [ + { id: 1, status: 'rejected', external_reference: 'pay-1' }, + { id: 2, status: 'approved', external_reference: 'pay-1', date_approved: '2026-11-11T03:00:00.000Z' }, + ], + }), + { status: 200 }, + )) as unknown as typeof fetch; + + const found = await searchMpPaymentByExternalReference('token', 'pay-1'); + expect(found).toMatchObject({ id: '2', status: 'approved' }); + }); +}); diff --git a/apps/backend/test/mp.test.ts b/apps/backend/test/mp.test.ts index cc81ba3..074099f 100644 --- a/apps/backend/test/mp.test.ts +++ b/apps/backend/test/mp.test.ts @@ -27,6 +27,7 @@ import prisma from '@/lib/prisma'; import { getMpAccessToken, mpRoutes } from '@/modules/mp'; import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens'; import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account'; +import { mpCallbackBounceUrl } from '@/modules/mp/lib/callback-origin'; import { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto'; import { MpApiError } from '@/modules/mp/lib/mp-oauth'; @@ -579,6 +580,17 @@ describe('modules/mp', () => { expect(location.href).not.toContain(storedState.codeVerifier); }); + it('refuses a state started by another teacher, without spending it', async () => { + prisma.mpOAuthState.findUnique.mockResolvedValue({ ...storedState, ownerId: otherOwnerId }); + + const res = await makeApp({ id: ownerId }).request(callbackUrl('?code=auth-code-123&state=state-abc')); + + expect(res.status).toBe(302); + expect(locationOf(res).searchParams.get('reason')).toBe('invalid_state'); + expect(prisma.mpOAuthState.deleteMany).not.toHaveBeenCalled(); + expect(prisma.mpAccount.upsert).not.toHaveBeenCalled(); + }); + it('sends a teacher without a session to the login screen', async () => { const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc')); @@ -1040,3 +1052,30 @@ describe('modules/mp RefreshExpiringMpTokens', () => { expect(totals).toEqual({ refreshed: 1, requiresReauth: 1, failed: 1 }); }); }); + +describe('mpCallbackBounceUrl', () => { + const env = { + MP_REDIRECT_URI: 'https://tunnel.ngrok-free.app/api/v1/mp/callback', + BETTER_AUTH_URL: 'http://localhost:4000', + }; + const url = 'https://tunnel.ngrok-free.app/api/v1/mp/callback?code=c&state=s'; + + it('replays a callback that came through the tunnel on the origin with the session', () => { + expect(mpCallbackBounceUrl(url, 'tunnel.ngrok-free.app', env)).toBe( + 'http://localhost:4000/api/v1/mp/callback?code=c&state=s', + ); + }); + + it('leaves it alone once it is on the session origin', () => { + expect(mpCallbackBounceUrl('http://localhost:4000/api/v1/mp/callback?code=c', 'localhost:4000', env)).toBeNull(); + }); + + it('never fires when the redirect and the session share a host (production)', () => { + const prod = { + MP_REDIRECT_URI: 'https://app.gruperly.com/api/v1/mp/callback', + BETTER_AUTH_URL: 'https://app.gruperly.com', + }; + expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'app.gruperly.com', prod)).toBeNull(); + expect(mpCallbackBounceUrl('http://api:4000/api/v1/mp/callback?code=c', 'api:4000', prod)).toBeNull(); + }); +}); diff --git a/apps/backend/test/payments-batch.test.ts b/apps/backend/test/payments-batch.test.ts index 455746c..a7473f0 100644 --- a/apps/backend/test/payments-batch.test.ts +++ b/apps/backend/test/payments-batch.test.ts @@ -69,7 +69,7 @@ function batchUseCase() { initPoint: 'https://mp.link/pay-1', sandboxInitPoint: null, })); - return new CreatePaymentBatch({ getToken, createPreference, webOrigin }); + return new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }); } describe('create payments batch', () => { @@ -143,6 +143,7 @@ describe('create payments batch', () => { currencyId: 'ARS', externalReference: 'pay-1', backUrl: `${webOrigin}/student/payments`, + notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks', }); }); @@ -191,7 +192,7 @@ describe('create payments batch', () => { throw new Error('should not be called'); }); - const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin }).execute( + const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute( 'group-1', userId, { dueDate: '2026-10-05T12:00:00.000Z' }, diff --git a/apps/backend/test/payments-renew.test.ts b/apps/backend/test/payments-renew.test.ts index 9c5f16e..5a3165f 100644 --- a/apps/backend/test/payments-renew.test.ts +++ b/apps/backend/test/payments-renew.test.ts @@ -83,7 +83,7 @@ describe('renew payment link', () => { sandboxInitPoint: null, })); - const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute( + const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' }).execute( 'pay-1', userId, ); @@ -102,6 +102,7 @@ describe('renew payment link', () => { currencyId: 'ARS', externalReference: 'pay-1', backUrl: `${webOrigin}/student/payments`, + notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks', }); expect(prisma.payment.update).toHaveBeenCalledWith({ where: { id: 'pay-1' }, diff --git a/apps/backend/test/payments-webhook.test.ts b/apps/backend/test/payments-webhook.test.ts new file mode 100644 index 0000000..f0e6156 --- /dev/null +++ b/apps/backend/test/payments-webhook.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, it, mock } from 'bun:test'; +import { isPublicApiRequest } from '@/http/session-auth'; +import { MpApiError } from '@/modules/mp/lib/mp-oauth'; +import { HandleMpPaymentNotification } from '@/modules/payments/features/webhook/use-case'; +import { paymentNotificationUrl } from '@/modules/payments/lib'; + +const ownerId = 'user-1'; +const tokenOk = () => + mock(async () => ({ ok: true, value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() } })); + +function makeDb(row: unknown) { + return { + payment: { + findFirst: mock(async () => row), + update: mock(async () => ({})), + }, + }; +} + +const linked = { id: 'pay-1', group: { createdById: ownerId } }; + +describe('HandleMpPaymentNotification', () => { + it('marks the payment PAID once the owner account confirms it was approved', async () => { + const db = makeDb(linked); + const getToken = tokenOk(); + const search = mock(async () => ({ + id: '999', + status: 'approved', + externalReference: 'pay-1', + liveMode: true, + dateApproved: '2026-11-11T03:00:00.000Z', + })); + + const result = await new HandleMpPaymentNotification({ db: db as never, getToken, search }).execute('pay-1'); + + expect(result).toEqual({ ok: true, value: { outcome: 'paid' } }); + expect(getToken).toHaveBeenCalledWith(ownerId); + expect(search).toHaveBeenCalledWith('token-1', 'pay-1'); + expect(db.payment.update).toHaveBeenCalledWith({ + where: { id: 'pay-1' }, + data: { status: 'PAID', mpPaymentId: '999', paidAt: new Date('2026-11-11T03:00:00.000Z') }, + }); + expect(db.payment.findFirst).toHaveBeenCalledWith( + expect.objectContaining({ + where: { id: 'pay-1', status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } }, + }), + ); + }); + + it('changes nothing while the payment is not approved', async () => { + const db = makeDb(linked); + const search = mock(async () => ({ + id: '999', + status: 'rejected', + externalReference: 'pay-1', + liveMode: true, + dateApproved: null, + })); + + const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute( + 'pay-1', + ); + + expect(result).toEqual({ ok: true, value: { outcome: 'unpaid' } }); + expect(db.payment.update).not.toHaveBeenCalled(); + }); + + it('ignores an unknown, already paid or link-less payment without asking Mercado Pago', async () => { + const db = makeDb(null); + const search = mock(async () => null); + + const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute( + 'pay-x', + ); + + expect(result).toEqual({ ok: true, value: { outcome: 'ignored' } }); + expect(search).not.toHaveBeenCalled(); + }); + + it('answers an error when Mercado Pago cannot be asked, so it retries', async () => { + const db = makeDb(linked); + const search = mock(async () => { + throw new MpApiError(503, null); + }); + + const result = await new HandleMpPaymentNotification({ db: db as never, getToken: tokenOk(), search }).execute( + 'pay-1', + ); + + expect(result.ok).toBe(false); + expect(db.payment.update).not.toHaveBeenCalled(); + }); +}); + +describe('payment notification URL', () => { + it('points at the public payment webhook, which needs no session', () => { + const url = paymentNotificationUrl('https://x.ngrok-free.app', 'cmabc123'); + expect(url).toBe('https://x.ngrok-free.app/api/v1/payments/webhooks/mp/cmabc123?source_news=webhooks'); + expect(isPublicApiRequest('POST', new URL(url).pathname)).toBe(true); + expect(isPublicApiRequest('GET', new URL(url).pathname)).toBe(false); + expect(isPublicApiRequest('POST', '/api/v1/payments/webhooks/mp/a/b')).toBe(false); + }); +}); diff --git a/apps/web/src/features/admin/AdminAccountDetailView.tsx b/apps/web/src/features/admin/AdminAccountDetailView.tsx index 08f5049..73d5a33 100644 --- a/apps/web/src/features/admin/AdminAccountDetailView.tsx +++ b/apps/web/src/features/admin/AdminAccountDetailView.tsx @@ -1,5 +1,4 @@ import type { AdminAccountDetail } from '@gruperly/shared' -import { PLAN_LIMITS } from '@gruperly/shared' import { Link } from '@tanstack/react-router' import { ArrowLeft, Loader2 } from 'lucide-react' import type { ReactNode } from 'react' @@ -60,7 +59,7 @@ export function AdminAccountDetailView() { function AccountDetail({ account }: { account: AdminAccountDetail }) { const subscription = account.subscription - const limits = PLAN_LIMITS[account.plan ?? 'FREE'] + const limits = account.limits const { t } = useTranslation(['admin', 'common', 'billing']) return ( diff --git a/apps/web/src/features/admin/AdminLayout.tsx b/apps/web/src/features/admin/AdminLayout.tsx index 5b71f57..b69e8c1 100644 --- a/apps/web/src/features/admin/AdminLayout.tsx +++ b/apps/web/src/features/admin/AdminLayout.tsx @@ -4,6 +4,9 @@ import { ArrowLeft } from 'lucide-react' import { ThemeToggle } from '../../components/layout/ThemeToggle' import { useTranslation } from 'react-i18next' +const navLinkClass = 'rounded-xl px-2.5 py-1.5 font-medium text-foreground/60 transition-colors hover:bg-primary-soft hover:text-primary' +const activeNavLinkClass = 'bg-primary-soft text-primary' + /* Layout propio del backoffice: sin la navegación del profesor y pensado para escritorio, aunque en móvil se lee igual (columna única). */ export function AdminLayout({ children }: { children: ReactNode }) { @@ -12,9 +15,25 @@ export function AdminLayout({ children }: { children: ReactNode }) {
- - Gruperly · {t('brand')} - +
+ + Gruperly · {t('brand')} + + +
void + saveLimits: (plan: Plan, input: UpdatePlanLimitsInput) => Promise + isSavingLimits: boolean + savePrice: (country: CountryCode, input: UpdatePlanPriceInput) => Promise + isSavingPrice: boolean +} + +const AdminPlansContext = createContext(null) + +export function AdminPlansProvider({ children }: { children: ReactNode }) { + const queryClient = useQueryClient() + const toast = useToast() + const plansQuery = useQuery({ queryKey: adminPlansQueryKey, queryFn: getAdminPlans }) + + // Lo que ve el profe (catálogo y su estado) también cambia. + const refresh = () => { + void queryClient.invalidateQueries({ queryKey: adminPlansQueryKey }) + void queryClient.invalidateQueries({ queryKey: ['billing'] }) + void queryClient.invalidateQueries({ queryKey: ['admin', 'accounts'] }) + } + + const limitsMutation = useMutation({ + mutationFn: ({ plan, input }: { plan: Plan; input: UpdatePlanLimitsInput }) => updatePlanLimits(plan, input), + onSuccess: () => { + toast.success(i18n.t('admin:plans.limits.saved')) + refresh() + }, + onError: (error) => toast.error(apiErrorMessage(error, i18n.t('admin:plans.saveError'))), + }) + + const priceMutation = useMutation({ + mutationFn: ({ country, input }: { country: CountryCode; input: UpdatePlanPriceInput }) => + updatePlanPrice(country, input), + onSuccess: (result) => { + toast.success( + result.queued > 0 + ? i18n.t('admin:plans.prices.savedQueued', { count: result.queued }) + : i18n.t('admin:plans.prices.saved'), + ) + refresh() + }, + onError: (error) => toast.error(apiErrorMessage(error, i18n.t('admin:plans.saveError'))), + }) + + const run = async (mutation: () => Promise) => { + try { + await mutation() + return true + } catch { + return false + } + } + + return ( + void plansQuery.refetch(), + saveLimits: (plan, input) => run(() => limitsMutation.mutateAsync({ plan, input })), + isSavingLimits: limitsMutation.isPending, + savePrice: (country, input) => run(() => priceMutation.mutateAsync({ country, input })), + isSavingPrice: priceMutation.isPending, + }} + > + {children} + + ) +} + +export function useAdminPlans(): AdminPlansContextValue { + const context = useContext(AdminPlansContext) + if (!context) throw new Error('useAdminPlans must be used inside AdminPlansProvider') + return context +} diff --git a/apps/web/src/features/admin/AdminPlansView.tsx b/apps/web/src/features/admin/AdminPlansView.tsx new file mode 100644 index 0000000..de15634 --- /dev/null +++ b/apps/web/src/features/admin/AdminPlansView.tsx @@ -0,0 +1,61 @@ +import { Loader2 } from 'lucide-react' +import { Button } from '../../components/ui' +import { useAdminPlans } from './AdminPlansProvider' +import { PlanLimitsCard } from './PlanLimitsCard' +import { PlanPriceRow } from './PlanPriceRow' +import { useTranslation } from 'react-i18next' + +export function AdminPlansView() { + const { plans, isPending, isError, errorMessage, retry } = useAdminPlans() + const { t } = useTranslation(['admin', 'common']) + + return ( +
+

{t('plans.title')}

+

{t('plans.subtitle')}

+ + {isPending ? ( +
+
+ ) : null} + + {isError ? ( +
+

{errorMessage}

+ +
+ ) : null} + + {plans ? ( +
+
+

+ {t('plans.limits.title')} +

+

{t('plans.limits.hint')}

+
+ + +
+
+ +
+

+ {t('plans.prices.title')} +

+

{t('plans.prices.hint')}

+
    + {plans.prices.map((price) => ( + + ))} +
+
+
+ ) : null} +
+ ) +} diff --git a/apps/web/src/features/admin/LimitInput.tsx b/apps/web/src/features/admin/LimitInput.tsx new file mode 100644 index 0000000..09d42fe --- /dev/null +++ b/apps/web/src/features/admin/LimitInput.tsx @@ -0,0 +1,52 @@ +import { Input, Switch } from '../../components/ui' +import { useTranslation } from 'react-i18next' + +type LimitInputProps = { + id: string + label: string + /** `null` es sin límite. */ + value: number | null + onChange: (value: number | null) => void + autoFocus?: boolean +} + +/* Un límite numérico con su interruptor de "Sin límite". Al apagar el + interruptor se vuelve al último número escrito. */ +export function LimitInput({ id, label, value, onChange, autoFocus }: LimitInputProps) { + const { t } = useTranslation('admin') + const unlimited = value === null + + return ( +
+ +
+ { + const parsed = Number.parseInt(event.target.value, 10) + onChange(Number.isNaN(parsed) ? 0 : Math.max(0, parsed)) + }} + className="max-w-32" + /> + + onChange(checked ? null : 0)} + aria-label={t('plans.limits.unlimitedFor', { label })} + /> + {t('plans.limits.unlimited')} + +
+
+ ) +} diff --git a/apps/web/src/features/admin/PlanLimitsCard.tsx b/apps/web/src/features/admin/PlanLimitsCard.tsx new file mode 100644 index 0000000..6af29ca --- /dev/null +++ b/apps/web/src/features/admin/PlanLimitsCard.tsx @@ -0,0 +1,131 @@ +import type { Plan, PlanLimits } from '@gruperly/shared' +import { useQuery } from '@tanstack/react-query' +import { AlertTriangle, Loader2, Pencil } from 'lucide-react' +import { useEffect, useState } from 'react' +import { Button, Switch } from '../../components/ui' +import { getPlanLimitsImpact } from '../../lib/api' +import { PLAN_NAMES, planFeatureList } from '../billing' +import { useAdminPlans } from './AdminPlansProvider' +import { LimitInput } from './LimitInput' +import { useTranslation } from 'react-i18next' + +const IMPACT_DEBOUNCE_MS = 400 + +/* Límites de un plan: se ven como la lista de beneficios y se editan en el + lugar. Rigen al instante, así que antes de guardar se muestra cuántas + cuentas quedarían en solo lectura. */ +export function PlanLimitsCard({ plan, limits }: { plan: Plan; limits: PlanLimits }) { + const { t } = useTranslation(['admin', 'billing']) + const { saveLimits, isSavingLimits } = useAdminPlans() + const [draft, setDraft] = useState(null) + + return ( +
+
+

{PLAN_NAMES[plan]}

+ {draft ? null : ( + + )} +
+ + {draft ? ( +
{ + event.preventDefault() + if (await saveLimits(plan, draft)) setDraft(null) + }} + > + setDraft({ ...draft, maxGroups })} + autoFocus + /> + setDraft({ ...draft, maxAttendees })} + /> + setDraft({ ...draft, mpCharges })} + /> + setDraft({ ...draft, whatsappAutomations })} + /> + + + +
+ + +
+ + ) : ( +
    + {planFeatureList(limits).map((feature) => ( +
  • + {feature.label} +
  • + ))} +
+ )} +
+ ) +} + +function FeatureSwitch({ label, checked, onChange }: { label: string; checked: boolean; onChange: (value: boolean) => void }) { + return ( +
+ {label} + +
+ ) +} + +function LimitsImpact({ plan, draft, current }: { plan: Plan; draft: PlanLimits; current: PlanLimits }) { + const { t } = useTranslation('admin') + const [debounced, setDebounced] = useState({ maxGroups: draft.maxGroups, maxAttendees: draft.maxAttendees }) + + useEffect(() => { + const timeout = setTimeout( + () => setDebounced({ maxGroups: draft.maxGroups, maxAttendees: draft.maxAttendees }), + IMPACT_DEBOUNCE_MS, + ) + return () => clearTimeout(timeout) + }, [draft.maxGroups, draft.maxAttendees]) + + // Solo importa si algún límite baja respecto del actual. + const tighter = + (debounced.maxGroups !== null && (current.maxGroups === null || debounced.maxGroups < current.maxGroups)) + || (debounced.maxAttendees !== null && (current.maxAttendees === null || debounced.maxAttendees < current.maxAttendees)) + + const impactQuery = useQuery({ + queryKey: ['admin', 'plans', 'impact', plan, debounced], + queryFn: () => getPlanLimitsImpact(plan, debounced), + enabled: tighter, + }) + + if (!tighter || !impactQuery.data || impactQuery.data.affectedAccounts === 0) return null + + return ( +

+

+ ) +} diff --git a/apps/web/src/features/admin/PlanPriceRow.tsx b/apps/web/src/features/admin/PlanPriceRow.tsx new file mode 100644 index 0000000..4b24346 --- /dev/null +++ b/apps/web/src/features/admin/PlanPriceRow.tsx @@ -0,0 +1,118 @@ +import type { AdminPlanPrice } from '@gruperly/shared' +import { Loader2, Pencil } from 'lucide-react' +import { useState } from 'react' +import { Badge, Button, Input, Switch } from '../../components/ui' +import { formatPrice } from '../../lib/format' +import { BILLING_PROVIDER_NAMES, formatBillingDate } from '../billing' +import { useAdminPlans } from './AdminPlansProvider' +import { countryLabel } from './copy' +import { useTranslation } from 'react-i18next' + +/* Precio de Pro en un país. Al editarlo se puede pasar también a las + suscripciones vivas: el proveedor lo cobra desde el próximo débito y al + profe le llega un mail. */ +export function PlanPriceRow({ price }: { price: AdminPlanPrice }) { + const { t } = useTranslation(['admin', 'billing']) + const { savePrice, isSavingPrice } = useAdminPlans() + const [amount, setAmount] = useState(null) + const [applyToExisting, setApplyToExisting] = useState(true) + + const parsed = Number(amount?.replace(',', '.')) + const valid = amount !== null && Number.isFinite(parsed) && parsed > 0 + const updatedAt = formatBillingDate(price.updatedAt) + + return ( +
  • +
    +
    +

    + {countryLabel(price.country)}{' '} + · {BILLING_PROVIDER_NAMES[price.provider]} +

    +

    + {t('plans.prices.live', { count: price.liveSubscriptions })} + {price.atOtherPrice > 0 ? ` · ${t('plans.prices.atOtherPrice', { count: price.atOtherPrice })}` : ''} + {updatedAt ? ` · ${t('plans.prices.updatedAt', { date: updatedAt })}` : ''} +

    + {price.pendingChanges > 0 || price.failedChanges > 0 ? ( +
    + {price.pendingChanges > 0 ? ( + {t('plans.prices.pending', { count: price.pendingChanges })} + ) : null} + {price.failedChanges > 0 ? ( + {t('plans.prices.failed', { count: price.failedChanges })} + ) : null} +
    + ) : null} +
    +
    + + {t('detail.perMonth', { price: formatPrice(price.amount, price.currency) })} + + {amount === null ? ( + + ) : null} +
    +
    + + {amount !== null ? ( +
    { + event.preventDefault() + if (!valid) return + if (await savePrice(price.country, { amount: parsed, applyToExisting })) setAmount(null) + }} + > + +
    +
    +

    {t('plans.prices.applyToExisting')}

    +

    + {t('plans.prices.applyHint', { count: price.liveSubscriptions })} +

    +
    + +
    +
    + + +
    +
    + ) : null} +
  • + ) +} diff --git a/apps/web/src/features/billing/BillingView.tsx b/apps/web/src/features/billing/BillingView.tsx index e07abb1..78a567d 100644 --- a/apps/web/src/features/billing/BillingView.tsx +++ b/apps/web/src/features/billing/BillingView.tsx @@ -1,4 +1,3 @@ -import { PLAN_LIMITS } from '@gruperly/shared' import { Link } from '@tanstack/react-router' import { ChevronLeft, Sparkles } from 'lucide-react' import { useState } from 'react' @@ -10,6 +9,7 @@ import { ChargesList } from './ChargesList' import { PlanOptionCard } from './PlanOptionCard' import { PlanSummaryCard } from './PlanSummaryCard' import { SubscribeModal } from './SubscribeModal' +import { usePlanCatalog } from './usePlanCatalog' import { useTranslation } from 'react-i18next' export function BillingView() { @@ -17,6 +17,7 @@ export function BillingView() { const [isConfirmingCancel, setIsConfirmingCancel] = useState(false) const { t } = useTranslation(['billing', 'common']) const status = statusQuery.data + const { catalog } = usePlanCatalog() const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED' const pending = status?.status === 'PENDING' @@ -42,10 +43,10 @@ export function BillingView() { {status ? (
    - + {status.status === 'AUTHORIZED' && nextPayment ? (

    - {t('summary.next', { amount: formatPrice(status.priceAmount, status.currency), date: nextPayment })} + {t('summary.next', { amount: formatPrice(status.nextPriceAmount ?? status.priceAmount, status.currency), date: nextPayment })} +

    + ) : null} + {status.nextPriceAmount !== null && status.status !== 'CANCELLED' ? ( +

    + {t('summary.nextPrice', { amount: formatPrice(status.nextPriceAmount, status.currency) })}

    ) : null} {status.status === 'PENDING' ? ( diff --git a/apps/web/src/features/billing/index.ts b/apps/web/src/features/billing/index.ts index 2615296..a43340e 100644 --- a/apps/web/src/features/billing/index.ts +++ b/apps/web/src/features/billing/index.ts @@ -18,4 +18,5 @@ export { PlanSettingsCard } from './PlanSettingsCard' export { PlanUpgradePrompt } from './PlanUpgradePrompt' export { SubscribeForm } from './SubscribeForm' export { billingStatusQueryKey, useBillingStatus } from './useBillingStatus' +export { planCatalogQueryKey, usePlanCatalog } from './usePlanCatalog' export { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling' diff --git a/apps/web/src/features/billing/usePlanCatalog.ts b/apps/web/src/features/billing/usePlanCatalog.ts new file mode 100644 index 0000000..e8241c2 --- /dev/null +++ b/apps/web/src/features/billing/usePlanCatalog.ts @@ -0,0 +1,23 @@ +import { PLAN_LIMITS, PRO_PRICE_BY_COUNTRY, type CountryCode, type PlanCatalogDto, COUNTRY_CURRENCY } from '@gruperly/shared' +import { useQuery } from '@tanstack/react-query' +import { getPlanCatalog } from '../../lib/api' + +export const planCatalogQueryKey = ['billing', 'plans'] as const + +/* Límites y precios los edita el backoffice. Mientras llega la respuesta (o si + falla) se muestran los valores por defecto de shared, que son los mismos con + los que se sembró la base. */ +const FALLBACK: PlanCatalogDto = { + limits: PLAN_LIMITS, + proPrices: Object.fromEntries( + (Object.keys(PRO_PRICE_BY_COUNTRY) as CountryCode[]).map((country) => [ + country, + { amount: PRO_PRICE_BY_COUNTRY[country], currency: COUNTRY_CURRENCY[country] }, + ]), + ) as PlanCatalogDto['proPrices'], +} + +export function usePlanCatalog() { + const query = useQuery({ queryKey: planCatalogQueryKey, queryFn: getPlanCatalog, staleTime: 60_000 }) + return { ...query, catalog: query.data ?? FALLBACK } +} diff --git a/apps/web/src/features/onboarding/PlanStep.tsx b/apps/web/src/features/onboarding/PlanStep.tsx index c5b2bb3..88bc083 100644 --- a/apps/web/src/features/onboarding/PlanStep.tsx +++ b/apps/web/src/features/onboarding/PlanStep.tsx @@ -1,5 +1,5 @@ import type { SelectPlanInput } from '@gruperly/shared' -import { billingProviderForCountry, COUNTRY_CURRENCY, PLAN_LIMITS, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared' +import { billingProviderForCountry, COUNTRY_CURRENCY, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared' import { useMutation, useQueryClient } from '@tanstack/react-query' import { ArrowLeft, ArrowRight, CheckCircle2, Clock, Loader2, Sparkles } from 'lucide-react' import { type ReactNode, useEffect, useState } from 'react' @@ -12,6 +12,7 @@ import { PlanOptionCard, SubscribeForm, useBillingStatus, + usePlanCatalog, useSubscriptionReturnPolling, } from '../billing' import { useOnboarding } from './OnboardingProvider' @@ -37,6 +38,7 @@ export function PlanStep() { const [proUnavailable, setProUnavailable] = useState(false) const polling = useSubscriptionReturnPolling() + const { catalog } = usePlanCatalog() const choseProBefore = selectedPlan === 'PRO' && statusQuery.data?.subscriptionStatus != null const billingQuery = useBillingStatus({ enabled: returnedFromSubscription || choseProBefore, @@ -93,8 +95,12 @@ export function PlanStep() { } } + const countryPrice = catalog.proPrices[country] ?? { + amount: PRO_PRICE_BY_COUNTRY[country], + currency: COUNTRY_CURRENCY[country], + } const proPrice = t('billing:view.perMonth', { - price: formatPrice(PRO_PRICE_BY_COUNTRY[country], COUNTRY_CURRENCY[country]), + price: formatPrice(countryPrice.amount, countryPrice.currency), }) if (subscriptionStatus === 'AUTHORIZED') { @@ -161,7 +167,7 @@ export function PlanStep() { return (
    - + - + {proUnavailable ? (

    {t('billing:view.unavailable')}

    ) : isEnteringEmail ? ( diff --git a/apps/web/src/i18n/locales/en/admin.json b/apps/web/src/i18n/locales/en/admin.json index 4eeb309..924b001 100644 --- a/apps/web/src/i18n/locales/en/admin.json +++ b/apps/web/src/i18n/locales/en/admin.json @@ -86,5 +86,49 @@ "PENDING": "Connecting", "DISCONNECTED": "Disconnected", "NONE": "Not connected" + }, + "plans": { + "title": "Plans", + "subtitle": "Free and Pro limits, and the Pro price in each country.", + "loading": "Loading plans", + "loadError": "We couldn't load the plans.", + "saveError": "We couldn't save the change.", + "edit": "Edit", + "save": "Save", + "cancel": "Cancel", + "limits": { + "title": "Limits", + "hint": "They apply right away to every account on the plan. An account left above them becomes read only.", + "maxGroups": "Groups", + "maxAttendees": "Active students", + "unlimited": "No limit", + "unlimitedFor": "{{label}} with no limit", + "mpCharges": "Mercado Pago charges", + "whatsappAutomations": "Automatic WhatsApp messages", + "impact_one": "{{count}} account already exceeds these limits and will become read only when you save.", + "impact_other": "{{count}} accounts already exceed these limits and will become read only when you save.", + "saved": "Limits saved." + }, + "prices": { + "title": "Pro price", + "hint": "New subscriptions take the price right away. Existing ones keep theirs unless you choose to apply it.", + "live_one": "{{count}} active subscription", + "live_other": "{{count}} active subscriptions", + "atOtherPrice_one": "{{count}} at another price", + "atOtherPrice_other": "{{count}} at another price", + "updatedAt": "changed on {{date}}", + "pending_one": "{{count}} change in progress", + "pending_other": "{{count}} changes in progress", + "failed_one": "{{count}} change failed", + "failed_other": "{{count}} changes failed", + "editFor": "Edit the price for {{country}}", + "amount": "Monthly price ({{currency}})", + "applyToExisting": "Apply to existing subscriptions", + "applyHint_one": "{{count}} subscription moves to the new price from its next charge. We'll email them.", + "applyHint_other": "{{count}} subscriptions move to the new price from their next charge. We'll email them.", + "saved": "Price saved.", + "savedQueued_one": "Price saved. {{count}} subscription moves to the new price from its next charge.", + "savedQueued_other": "Price saved. {{count}} subscriptions move to the new price from their next charge." + } } } diff --git a/apps/web/src/i18n/locales/en/billing.json b/apps/web/src/i18n/locales/en/billing.json index b2736e0..06edbf0 100644 --- a/apps/web/src/i18n/locales/en/billing.json +++ b/apps/web/src/i18n/locales/en/billing.json @@ -88,6 +88,7 @@ "paidThrough": "Paid through {{date}}.", "notEnforced": "For now, every feature is enabled for every account.", "groups": "Groups", - "students": "Active students" + "students": "Active students", + "nextPrice": "New price from your next charge: {{amount}} a month." } } diff --git a/apps/web/src/i18n/locales/en/validation.json b/apps/web/src/i18n/locales/en/validation.json index 0fc741b..6c417e9 100644 --- a/apps/web/src/i18n/locales/en/validation.json +++ b/apps/web/src/i18n/locales/en/validation.json @@ -60,5 +60,8 @@ }, "attendance": { "empty": "Send at least one attendance record" + }, + "billing": { + "priceInvalid": "Enter a price greater than zero" } } diff --git a/apps/web/src/i18n/locales/es-419/admin.json b/apps/web/src/i18n/locales/es-419/admin.json index 0a1b63f..28a77c9 100644 --- a/apps/web/src/i18n/locales/es-419/admin.json +++ b/apps/web/src/i18n/locales/es-419/admin.json @@ -86,5 +86,49 @@ "PENDING": "Conectando", "DISCONNECTED": "Desconectado", "NONE": "Sin conectar" + }, + "plans": { + "title": "Planes", + "subtitle": "Límites de Free y Pro, y precio de Pro en cada país.", + "loading": "Cargando planes", + "loadError": "No pudimos cargar los planes.", + "saveError": "No pudimos guardar el cambio.", + "edit": "Editar", + "save": "Guardar", + "cancel": "Cancelar", + "limits": { + "title": "Límites", + "hint": "Se aplican al instante a todas las cuentas del plan. Una cuenta que quede por encima pasa a solo lectura.", + "maxGroups": "Grupos", + "maxAttendees": "Alumnos activos", + "unlimited": "Sin límite", + "unlimitedFor": "{{label}} sin límite", + "mpCharges": "Cobros con Mercado Pago", + "whatsappAutomations": "Mensajes automáticos por WhatsApp", + "impact_one": "{{count}} cuenta ya supera estos límites y quedará en solo lectura al guardar.", + "impact_other": "{{count}} cuentas ya superan estos límites y quedarán en solo lectura al guardar.", + "saved": "Límites guardados." + }, + "prices": { + "title": "Precio de Pro", + "hint": "Las suscripciones nuevas toman el precio al instante. Las existentes conservan el suyo, salvo que elijas aplicarlo.", + "live_one": "{{count}} suscripción activa", + "live_other": "{{count}} suscripciones activas", + "atOtherPrice_one": "{{count}} con otro precio", + "atOtherPrice_other": "{{count}} con otro precio", + "updatedAt": "cambiado el {{date}}", + "pending_one": "{{count}} cambio en curso", + "pending_other": "{{count}} cambios en curso", + "failed_one": "{{count}} cambio falló", + "failed_other": "{{count}} cambios fallaron", + "editFor": "Editar el precio de {{country}}", + "amount": "Precio mensual ({{currency}})", + "applyToExisting": "Aplicar a las suscripciones existentes", + "applyHint_one": "{{count}} suscripción pasa al precio nuevo desde su próximo cobro. Le avisamos por correo.", + "applyHint_other": "{{count}} suscripciones pasan al precio nuevo desde su próximo cobro. Les avisamos por correo.", + "saved": "Precio guardado.", + "savedQueued_one": "Precio guardado. {{count}} suscripción pasa al precio nuevo desde su próximo cobro.", + "savedQueued_other": "Precio guardado. {{count}} suscripciones pasan al precio nuevo desde su próximo cobro." + } } } diff --git a/apps/web/src/i18n/locales/es-419/billing.json b/apps/web/src/i18n/locales/es-419/billing.json index 02cacdb..667b2bf 100644 --- a/apps/web/src/i18n/locales/es-419/billing.json +++ b/apps/web/src/i18n/locales/es-419/billing.json @@ -88,6 +88,7 @@ "paidThrough": "Pagado hasta el {{date}}.", "notEnforced": "Por ahora todas las funciones están habilitadas para todas las cuentas.", "groups": "Grupos", - "students": "Alumnos activos" + "students": "Alumnos activos", + "nextPrice": "Nuevo precio desde tu próximo cobro: {{amount}} al mes." } } diff --git a/apps/web/src/i18n/locales/es-419/validation.json b/apps/web/src/i18n/locales/es-419/validation.json index 18653a0..f93dc85 100644 --- a/apps/web/src/i18n/locales/es-419/validation.json +++ b/apps/web/src/i18n/locales/es-419/validation.json @@ -60,5 +60,8 @@ }, "attendance": { "empty": "Envía al menos un registro de asistencia" + }, + "billing": { + "priceInvalid": "Ingresa un precio mayor a cero" } } diff --git a/apps/web/src/i18n/locales/es-AR/admin.json b/apps/web/src/i18n/locales/es-AR/admin.json index 18ee36e..97619af 100644 --- a/apps/web/src/i18n/locales/es-AR/admin.json +++ b/apps/web/src/i18n/locales/es-AR/admin.json @@ -86,5 +86,49 @@ "PENDING": "Conectando", "DISCONNECTED": "Desconectado", "NONE": "Sin conectar" + }, + "plans": { + "title": "Planes", + "subtitle": "Límites de Free y Pro, y precio de Pro en cada país.", + "loading": "Cargando planes", + "loadError": "No pudimos cargar los planes.", + "saveError": "No pudimos guardar el cambio.", + "edit": "Editar", + "save": "Guardar", + "cancel": "Cancelar", + "limits": { + "title": "Límites", + "hint": "Rigen al instante para todas las cuentas del plan. Una cuenta que quede por encima pasa a solo lectura.", + "maxGroups": "Grupos", + "maxAttendees": "Alumnos activos", + "unlimited": "Sin límite", + "unlimitedFor": "{{label}} sin límite", + "mpCharges": "Cobros con Mercado Pago", + "whatsappAutomations": "Mensajes automáticos por WhatsApp", + "impact_one": "{{count}} cuenta ya supera estos límites y va a quedar en solo lectura al guardar.", + "impact_other": "{{count}} cuentas ya superan estos límites y van a quedar en solo lectura al guardar.", + "saved": "Límites guardados." + }, + "prices": { + "title": "Precio de Pro", + "hint": "Las suscripciones nuevas toman el precio al instante. Las existentes conservan el suyo, salvo que elijas aplicarlo.", + "live_one": "{{count}} suscripción activa", + "live_other": "{{count}} suscripciones activas", + "atOtherPrice_one": "{{count}} con otro precio", + "atOtherPrice_other": "{{count}} con otro precio", + "updatedAt": "cambiado el {{date}}", + "pending_one": "{{count}} cambio en curso", + "pending_other": "{{count}} cambios en curso", + "failed_one": "{{count}} cambio falló", + "failed_other": "{{count}} cambios fallaron", + "editFor": "Editar el precio de {{country}}", + "amount": "Precio mensual ({{currency}})", + "applyToExisting": "Aplicar a las suscripciones existentes", + "applyHint_one": "{{count}} suscripción pasa al precio nuevo desde su próximo cobro. Le avisamos por mail.", + "applyHint_other": "{{count}} suscripciones pasan al precio nuevo desde su próximo cobro. Les avisamos por mail.", + "saved": "Precio guardado.", + "savedQueued_one": "Precio guardado. {{count}} suscripción pasa al precio nuevo desde su próximo cobro.", + "savedQueued_other": "Precio guardado. {{count}} suscripciones pasan al precio nuevo desde su próximo cobro." + } } } diff --git a/apps/web/src/i18n/locales/es-AR/billing.json b/apps/web/src/i18n/locales/es-AR/billing.json index c28b630..7d443f4 100644 --- a/apps/web/src/i18n/locales/es-AR/billing.json +++ b/apps/web/src/i18n/locales/es-AR/billing.json @@ -88,6 +88,7 @@ "paidThrough": "Pagado hasta el {{date}}.", "notEnforced": "Por ahora todas las funciones están habilitadas para todas las cuentas.", "groups": "Grupos", - "students": "Alumnos activos" + "students": "Alumnos activos", + "nextPrice": "Nuevo precio desde tu próximo cobro: {{amount}} por mes." } } diff --git a/apps/web/src/i18n/locales/es-AR/validation.json b/apps/web/src/i18n/locales/es-AR/validation.json index 43c0893..86aea06 100644 --- a/apps/web/src/i18n/locales/es-AR/validation.json +++ b/apps/web/src/i18n/locales/es-AR/validation.json @@ -60,5 +60,8 @@ }, "attendance": { "empty": "Mandá al menos un registro de asistencia" + }, + "billing": { + "priceInvalid": "Ingresá un precio mayor a cero" } } diff --git a/apps/web/src/i18n/locales/pt-BR/admin.json b/apps/web/src/i18n/locales/pt-BR/admin.json index a23aa96..86bd9f3 100644 --- a/apps/web/src/i18n/locales/pt-BR/admin.json +++ b/apps/web/src/i18n/locales/pt-BR/admin.json @@ -86,5 +86,49 @@ "PENDING": "Conectando", "DISCONNECTED": "Desconectado", "NONE": "Não conectado" + }, + "plans": { + "title": "Planos", + "subtitle": "Limites do Free e do Pro, e preço do Pro em cada país.", + "loading": "Carregando planos", + "loadError": "Não conseguimos carregar os planos.", + "saveError": "Não conseguimos salvar a alteração.", + "edit": "Editar", + "save": "Salvar", + "cancel": "Cancelar", + "limits": { + "title": "Limites", + "hint": "Valem na hora para todas as contas do plano. Uma conta que ficar acima passa a somente leitura.", + "maxGroups": "Grupos", + "maxAttendees": "Alunos ativos", + "unlimited": "Sem limite", + "unlimitedFor": "{{label}} sem limite", + "mpCharges": "Cobranças com Mercado Pago", + "whatsappAutomations": "Mensagens automáticas por WhatsApp", + "impact_one": "{{count}} conta já passa desses limites e vai ficar em somente leitura ao salvar.", + "impact_other": "{{count}} contas já passam desses limites e vão ficar em somente leitura ao salvar.", + "saved": "Limites salvos." + }, + "prices": { + "title": "Preço do Pro", + "hint": "As assinaturas novas usam o preço na hora. As existentes mantêm o delas, a menos que você escolha aplicá-lo.", + "live_one": "{{count}} assinatura ativa", + "live_other": "{{count}} assinaturas ativas", + "atOtherPrice_one": "{{count}} com outro preço", + "atOtherPrice_other": "{{count}} com outro preço", + "updatedAt": "alterado em {{date}}", + "pending_one": "{{count}} alteração em andamento", + "pending_other": "{{count}} alterações em andamento", + "failed_one": "{{count}} alteração falhou", + "failed_other": "{{count}} alterações falharam", + "editFor": "Editar o preço de {{country}}", + "amount": "Preço mensal ({{currency}})", + "applyToExisting": "Aplicar às assinaturas existentes", + "applyHint_one": "{{count}} assinatura passa ao preço novo a partir da próxima cobrança. Avisamos por e-mail.", + "applyHint_other": "{{count}} assinaturas passam ao preço novo a partir da próxima cobrança. Avisamos por e-mail.", + "saved": "Preço salvo.", + "savedQueued_one": "Preço salvo. {{count}} assinatura passa ao preço novo a partir da próxima cobrança.", + "savedQueued_other": "Preço salvo. {{count}} assinaturas passam ao preço novo a partir da próxima cobrança." + } } } diff --git a/apps/web/src/i18n/locales/pt-BR/billing.json b/apps/web/src/i18n/locales/pt-BR/billing.json index 3515d30..4a91a34 100644 --- a/apps/web/src/i18n/locales/pt-BR/billing.json +++ b/apps/web/src/i18n/locales/pt-BR/billing.json @@ -88,6 +88,7 @@ "paidThrough": "Pago até {{date}}.", "notEnforced": "Por enquanto todos os recursos estão liberados para todas as contas.", "groups": "Grupos", - "students": "Alunos ativos" + "students": "Alunos ativos", + "nextPrice": "Novo preço a partir da próxima cobrança: {{amount}} por mês." } } diff --git a/apps/web/src/i18n/locales/pt-BR/validation.json b/apps/web/src/i18n/locales/pt-BR/validation.json index fa91d36..2878744 100644 --- a/apps/web/src/i18n/locales/pt-BR/validation.json +++ b/apps/web/src/i18n/locales/pt-BR/validation.json @@ -60,5 +60,8 @@ }, "attendance": { "empty": "Envie pelo menos um registro de presença" + }, + "billing": { + "priceInvalid": "Informe um preço maior que zero" } } diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 3223dc5..ea09a41 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -1,4 +1,13 @@ import type { + AdminPlansDto, + PlanCatalogDto, + PlanLimits, + PlanLimitsImpactDto, + UpdatePlanLimitsInput, + UpdatePlanPriceInput, + UpdatePlanPriceResultDto, + Plan, + CountryCode, AbsenceDetails, AdminAccountDetail, AdminAccountList, @@ -189,6 +198,9 @@ export const cancelSubscription = () => export const getBillingCharges = (page = 1) => apiFetch(`/api/v1/billing/charges?page=${page}&pageSize=10`) +/* Límites de cada plan y precio de Pro por país, tal como los configuró el backoffice. */ +export const getPlanCatalog = () => apiFetch('/api/v1/billing/plans') + // --- WhatsApp (recordatorios y reenganche automáticos) --- export const startWhatsappConnection = (returnTo: WhatsappReturnTo) => @@ -457,6 +469,27 @@ export const getAdminAccounts = (params: AdminAccountQueryInput) => { export const getAdminAccount = (accountId: string) => apiFetch(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`) +export const getAdminPlans = () => apiFetch('/api/v1/admin/plans') + +export const getPlanLimitsImpact = (plan: Plan, limits: Pick) => { + const query = new URLSearchParams() + if (limits.maxGroups !== null) query.set('maxGroups', String(limits.maxGroups)) + if (limits.maxAttendees !== null) query.set('maxAttendees', String(limits.maxAttendees)) + return apiFetch(`/api/v1/admin/plans/${plan}/impact?${query.toString()}`) +} + +export const updatePlanLimits = (plan: Plan, payload: UpdatePlanLimitsInput) => + apiFetch(`/api/v1/admin/plans/${plan}/limits`, { + method: 'PUT', + body: JSON.stringify(payload), + }) + +export const updatePlanPrice = (country: CountryCode, payload: UpdatePlanPriceInput) => + apiFetch(`/api/v1/admin/plans/prices/${country}`, { + method: 'PUT', + body: JSON.stringify(payload), + }) + // — App del alumno (sesión propia, nunca la del profe) — const STUDENT_API = '/api/v1/student-portal' diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 4e3d4c1..e1d11ea 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -26,6 +26,7 @@ import { Route as AuthenticatedSecurityRouteImport } from './routes/_authenticat import { Route as AuthenticatedSettingsRouteImport } from './routes/_authenticated/settings' import { Route as AccessIndexRouteImport } from './routes/access.index' import { Route as AdminIndexRouteImport } from './routes/admin/index' +import { Route as AdminPlansRouteImport } from './routes/admin/plans' import { Route as ITokenRouteImport } from './routes/i.$token' import { Route as JoinTokenRouteImport } from './routes/join.$token' import { Route as ReportAbsenceTokenRouteImport } from './routes/report-absence.$token' @@ -130,6 +131,11 @@ const AdminIndexRoute = AdminIndexRouteImport.update({ path: '/', getParentRoute: () => AdminRoute, } as any) +const AdminPlansRoute = AdminPlansRouteImport.update({ + id: '/plans', + path: '/plans', + getParentRoute: () => AdminRoute, +} as any) const ITokenRoute = ITokenRouteImport.update({ id: '/i/$token', path: '/i/$token', @@ -254,6 +260,7 @@ export interface FileRoutesByFullPath { '/profile': typeof AuthenticatedProfileRoute '/security': typeof AuthenticatedSecurityRoute '/settings': typeof AuthenticatedSettingsRoute + '/admin/plans': typeof AdminPlansRoute '/i/$token': typeof ITokenRoute '/join/$token': typeof JoinTokenRoute '/report-absence/$token': typeof ReportAbsenceTokenRoute @@ -290,6 +297,7 @@ export interface FileRoutesByTo { '/profile': typeof AuthenticatedProfileRoute '/security': typeof AuthenticatedSecurityRoute '/settings': typeof AuthenticatedSettingsRoute + '/admin/plans': typeof AdminPlansRoute '/i/$token': typeof ITokenRoute '/join/$token': typeof JoinTokenRoute '/report-absence/$token': typeof ReportAbsenceTokenRoute @@ -329,6 +337,7 @@ export interface FileRoutesById { '/_authenticated/profile': typeof AuthenticatedProfileRoute '/_authenticated/security': typeof AuthenticatedSecurityRoute '/_authenticated/settings': typeof AuthenticatedSettingsRoute + '/admin/plans': typeof AdminPlansRoute '/i/$token': typeof ITokenRoute '/join/$token': typeof JoinTokenRoute '/report-absence/$token': typeof ReportAbsenceTokenRoute @@ -369,6 +378,7 @@ export interface FileRouteTypes { | '/profile' | '/security' | '/settings' + | '/admin/plans' | '/i/$token' | '/join/$token' | '/report-absence/$token' @@ -405,6 +415,7 @@ export interface FileRouteTypes { | '/profile' | '/security' | '/settings' + | '/admin/plans' | '/i/$token' | '/join/$token' | '/report-absence/$token' @@ -443,6 +454,7 @@ export interface FileRouteTypes { | '/_authenticated/profile' | '/_authenticated/security' | '/_authenticated/settings' + | '/admin/plans' | '/i/$token' | '/join/$token' | '/report-absence/$token' @@ -606,6 +618,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AdminIndexRouteImport parentRoute: typeof AdminRoute } + '/admin/plans': { + id: '/admin/plans' + path: '/plans' + fullPath: '/admin/plans' + preLoaderRoute: typeof AdminPlansRouteImport + parentRoute: typeof AdminRoute + } '/i/$token': { id: '/i/$token' path: '/i/$token' @@ -815,11 +834,13 @@ const StudentRouteWithChildren = StudentRoute._addFileChildren(StudentRouteChildren) interface AdminRouteChildren { + AdminPlansRoute: typeof AdminPlansRoute AdminIndexRoute: typeof AdminIndexRoute AdminAccountsAccountIdRoute: typeof AdminAccountsAccountIdRoute } const AdminRouteChildren: AdminRouteChildren = { + AdminPlansRoute: AdminPlansRoute, AdminIndexRoute: AdminIndexRoute, AdminAccountsAccountIdRoute: AdminAccountsAccountIdRoute, } diff --git a/apps/web/src/routes/admin/plans.tsx b/apps/web/src/routes/admin/plans.tsx new file mode 100644 index 0000000..7a99644 --- /dev/null +++ b/apps/web/src/routes/admin/plans.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { AdminPlansProvider } from '../../features/admin/AdminPlansProvider' +import { AdminPlansView } from '../../features/admin/AdminPlansView' + +export const Route = createFileRoute('/admin/plans')({ + component: () => ( + + + + ), +}) diff --git a/docs/billing.md b/docs/billing.md index f9d6e87..784e7ec 100644 --- a/docs/billing.md +++ b/docs/billing.md @@ -9,7 +9,17 @@ Gruperly le cobra **al profesor** una suscripción mensual a **Pro** con débito | Cobros a alumnos con Mercado Pago | No | Sí | | Mensajes automáticos por WhatsApp | No | Sí | -Los límites, los precios por país y quién cobra en cada uno viven en `packages/shared/src/schemas/billing.ts` (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`, `BILLING_PROVIDER_BY_COUNTRY`). No hay trial. +La tabla de arriba son los valores **por defecto**. Los límites de cada plan y el precio de Pro por país se editan desde el backoffice (`/admin/plans`) y viven en la base (`plan_configs`, `plan_prices`), sembradas con las constantes de `packages/shared/src/schemas/billing.ts` (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`). Quién cobra en cada país sigue en código (`BILLING_PROVIDER_BY_COUNTRY`). No hay trial. + +## Cambiar límites y precios (backoffice) + +El backend lee límites y precios con `PlanCatalog` (`modules/billing/lib/catalog.ts`): caché en memoria de 30 s, invalidada al guardar desde el backoffice (las otras instancias lo ven en a lo sumo 30 s). Si falta una fila o la base falla, usa las constantes de shared. La web los pide a `GET /billing/plans` (el onboarding todavía no guardó el país, así que trae todos). + +- **Límites** (`PUT /admin/plans/:plan/limits`): rigen **al instante** para todas las cuentas del plan. Una cuenta que quede por encima pasa a solo lectura. Antes de guardar, la pantalla muestra cuántas cuentas quedarían afectadas (`GET /admin/plans/:plan/impact`). +- **Precio de Pro** (`PUT /admin/plans/prices/:country`, `{ amount, applyToExisting }`): las suscripciones nuevas lo toman al instante. Cada cambio queda en `plan_price_changes`. + - Con `applyToExisting`, las suscripciones `AUTHORIZED`/`PAUSED` del país (con `external_id`) y otro precio quedan en cola en `billing_subscriptions.pending_amount`. Las `PENDING` no se tocan: si el profe reintenta, el checkout nuevo sale con el precio nuevo. + - El job `ApplyPriceChanges` (`*/5 * * * *` UTC, y además apenas se guarda) le pide a cada proveedor el monto nuevo **desde el próximo cobro**: Mercado Pago con `PUT /preapproval/:id` (`auto_recurring.transaction_amount`), Stripe cambiando el `price_data` del item (mismo producto) con `proration_behavior=none`. Con éxito mueve `pending_amount` a `amount` (update condicional: si dos instancias corren a la vez, solo una manda el mail) y le avisa al profe por mail. Un rechazo suma `price_change_attempts`; después de 5 queda como fallido en el backoffice. + - El profe ve el aviso en `/billing` (`nextPriceAmount` en `GET /billing/status`) mientras el cambio está en cola y hasta que se cobra el primer mes al precio nuevo. ## Proveedores @@ -62,7 +72,7 @@ Un país cuyo proveedor no tiene credenciales ofrece Pro como "no disponible" (` - **Stripe**: crea una Checkout Session en modo suscripción (`client_reference_id` y `subscription_data.metadata.gruperly_user_id` = id del usuario) y guarda su id en `checkout_ref`. No se pide email: lo carga el profesor en el checkout. La suscripción de Stripe recién existe cuando completa el pago; ahí la sync guarda su id en `external_id` y el email real en `payer_email`. Devuelve `{ checkoutUrl }` y el navegador navega ahí. -2. El profesor autoriza (en MP, **con el mismo email**; en Stripe, cargando la tarjeta) y vuelve a `/billing?sub=return` o a `/onboarding?sub=return`. +2. El profesor autoriza (en MP, **con el mismo email**; en Stripe, cargando la tarjeta) y el proveedor lo devuelve a `GET /api/v1/billing/return?to=billing|onboarding` (público, sobre `API_PUBLIC_URL`), que redirige a `/billing?sub=return` o a `/onboarding?sub=return` de la web. Pasa por la API porque MP rechaza una `back_url` en `localhost`, y en local el túnel apunta a la API, no a la web. 3. El estado se sincroniza por tres caminos, todos con `SyncSubscription`, que es idempotente y **no confía en el body** de ninguna notificación: le vuelve a pedir al proveedor la suscripción y sus facturas, y chequea que sea del usuario. - el **webhook**: MP verifica `x-signature` (HMAC-SHA256 de `id:;request-id:;ts:;`); Stripe verifica `Stripe-Signature` (HMAC-SHA256 de `.`, tolerancia 5 min). Se deduplica en `billing_webhook_events` por `(source, dedupe_key)` (`mp:` + `x-request-id`, o `stripe` + id del evento); - `GET /billing/status` reconsulta al proveedor si la suscripción sigue `PENDING`, como mucho cada 30 s. Es lo que actualiza la pantalla al volver del checkout; @@ -78,6 +88,7 @@ Cancelar (`POST /billing/cancel`) cancela en el proveedor en el acto; Pro sigue ## Desarrollo local - El webhook de MP necesita una URL pública: el mismo túnel de ngrok de `MP_REDIRECT_URI` sirve (`https://TU-DOMINIO.ngrok-free.app/api/v1/billing/webhooks/mp/ar`). Sin webhook todo funciona igual, porque el status sincroniza al leer. +- MP también exige que la vuelta del checkout sea pública: poné el mismo túnel en `API_PUBLIC_URL` (`https://TU-DOMINIO.ngrok-free.app`). Sin eso, `POST /billing/subscribe` falla con `Invalid value for back_url`. - Para probar MP sin plata real, usar **usuarios de prueba** de MP de Argentina (un vendedor de test cuyo token va en `MP_PLATFORM_ACCESS_TOKEN_AR` y un comprador de test para pagar). - Para Stripe, usar las claves de **test mode** (`sk_test_…`) y la CLI: `stripe listen --forward-to localhost:4000/api/v1/billing/webhooks/stripe` imprime el `whsec_…` para `STRIPE_WEBHOOK_SECRET`. Tarjetas de prueba: `4242 4242 4242 4242` (aprobada) y `4000 0000 0000 0341` (se vincula pero rechaza los cobros, para probar la gracia). El profesor tiene que tener un país distinto de AR. - Para simular un vencimiento, poner `paid_through` en el pasado en `billing_subscriptions`. Con `BILLING_ENFORCEMENT=on` y más uso que el permitido por Free, aparece el aviso de solo lectura. diff --git a/docs/environment.md b/docs/environment.md index 08d626f..db06803 100644 --- a/docs/environment.md +++ b/docs/environment.md @@ -24,7 +24,7 @@ Gruperly habla con Mercado Pago por **dos motivos completamente distintos**, con | Cómo se autentica | OAuth (Authorization Code + PKCE): el profesor vincula **su** cuenta y Gruperly guarda **su** access token (cifrado) | Access token **de la cuenta de Gruperly**, fijo en el entorno | | Variables | `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI`, `TOKEN_ENCRYPTION_KEY` | `MP_PLATFORM_ACCESS_TOKEN_`, `MP_PLATFORM_WEBHOOK_SECRET_` | | Países | Todos (cada profesor usa la cuenta de MP de su país) | Solo **AR**. El resto de los países paga Pro con **Stripe** (`STRIPE_*`) | -| Cómo se entera de un pago | Polling (`ReconcilePayments`, cada 15 min). No hay webhook | Webhook `POST /api/v1/billing/webhooks/mp/:country` + polling de respaldo | +| Cómo se entera de un pago | Aviso por link (`notification_url` → `POST /api/v1/payments/webhooks/mp/:paymentId`, sobre `API_PUBLIC_URL`; nada que configurar en el panel) + polling de respaldo (`ReconcilePayments`, cada 15 min) | Webhook `POST /api/v1/billing/webhooks/mp/:country` + polling de respaldo | | Si faltan las variables | `GET /mp/connect` falla; el paso "Cobros" del onboarding es salteable y el resto de la app anda | `503 billing_not_available` en ese país: Pro aparece "no disponible", Free sigue funcionando | Regla mental: **`MP_CLIENT_*` identifica a la *aplicación* Gruperly frente a MP para que los profesores le den permiso; nunca cobra nada a nombre de Gruperly. `MP_PLATFORM_*` es la *cuenta* de Gruperly que recibe la plata de Pro.** El código nunca cruza unas con otras: billing jamás usa `getMpAccessToken` (el token del profesor) y los cobros a alumnos jamás usan `MP_PLATFORM_*`. @@ -86,6 +86,7 @@ Sin las dos, esos países ven Pro como no disponible (`503`). | `NODE_ENV` | No | — | `production` activa HSTS en los security headers y cambia el formato del logger. El compose lo fija. | | `WEB_URL` | Sí en prod | `http://localhost:6173` | Origen público de la web, sin barra final. Se usa para CORS, CSRF (`Origin` del portal de alumnos), los redirects del callback de MP, los links de invitación y de alumnos, y como base de WebAuthn. | | `BETTER_AUTH_URL` | Sí | — | URL base de Better Auth. En el compose es igual a `WEB_URL` porque nginx proxea `/api` (cookie first-party). | +| `API_PUBLIC_URL` | No | `BETTER_AUTH_URL` | Origen público de la API. Es la vuelta del checkout de Pro (`https:///api/v1/billing/return`, que redirige a `WEB_URL`) y la URL de aviso de cada link de pago de alumnos. MP rechaza una `back_url` en `localhost`, así que en local va el túnel de ngrok. En el compose no hace falta: `BETTER_AUTH_URL` ya es el dominio público. | | `BETTER_AUTH_SECRET` | Sí | — | Secreto para firmar sesiones de profesores. `openssl rand -base64 32`. Cambiarlo cierra todas las sesiones. | | `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | No | — | Login con Google. Sin los dos, el proveedor no se registra. | | `ADMIN_EMAILS` | No | vacío | Emails del equipo de Gruperly con acceso al backoffice `/admin`, separados por coma. Vacío = nadie. | diff --git a/packages/shared/src/schemas/admin.ts b/packages/shared/src/schemas/admin.ts index 0e4f709..1c4fe48 100644 --- a/packages/shared/src/schemas/admin.ts +++ b/packages/shared/src/schemas/admin.ts @@ -1,5 +1,11 @@ import { z } from 'zod'; -import { BillingChargeDtoSchema, billingProviderIdSchema, planSchema, subscriptionStatusSchema } from './billing.js'; +import { + BillingChargeDtoSchema, + billingProviderIdSchema, + PlanLimitsSchema, + planSchema, + subscriptionStatusSchema, +} from './billing.js'; import { countryCodeSchema } from './country.js'; import { createPageSchema, createPageSizeSchema, createPaginationSchema } from './pagination.js'; @@ -69,6 +75,8 @@ export const AdminAccountDetailSchema = AdminAccountListItemSchema.extend({ graceUntil: isoDateTimeSchema.nullable(), /** Free with more usage than its limits (only with BILLING_ENFORCEMENT on). */ readOnly: z.boolean(), + /** The current limits of the account's plan (Free while none was chosen). */ + limits: PlanLimitsSchema, subscription: AdminSubscriptionSummarySchema.extend({ payerEmail: z.string(), authorizedAt: isoDateTimeSchema.nullable(), @@ -87,3 +95,75 @@ export const AdminAccountDetailSchema = AdminAccountListItemSchema.extend({ charges: z.array(BillingChargeDtoSchema), }); export type AdminAccountDetail = z.output; + +// Plans: limits of Free and Pro and the price of Pro per country, editable from +// the backoffice. Limits apply right away; a new price applies to new +// subscriptions and, if asked, to live ones from their next charge. + +const limitValueSchema = z.number().int().min(0).max(1_000_000).nullable(); + +export const UpdatePlanLimitsInputSchema = z.strictObject({ + /** `null` means no limit. */ + maxGroups: limitValueSchema, + maxAttendees: limitValueSchema, + whatsappAutomations: z.boolean(), + mpCharges: z.boolean(), +}); +export type UpdatePlanLimitsInput = z.output; + +/** Query values are strings: an empty or missing one means no limit. */ +const limitQuerySchema = z + .string() + .optional() + .transform((value) => (value === undefined || value === '' ? null : Number(value))) + .pipe(limitValueSchema); + +export const PlanLimitsImpactQuerySchema = z.object({ + maxGroups: limitQuerySchema, + maxAttendees: limitQuerySchema, +}); +export type PlanLimitsImpactQuery = z.output; + +export const PlanLimitsImpactDtoSchema = z.object({ + /** Accounts on that plan whose usage would exceed the new limits. */ + affectedAccounts: z.number().int(), +}); +export type PlanLimitsImpactDto = z.output; + +export const UpdatePlanPriceInputSchema = z.strictObject({ + amount: z.number().positive('billing.priceInvalid').max(100_000_000), + /** Also move live subscriptions of that country to the new price, from their next charge. */ + applyToExisting: z.boolean(), +}); +export type UpdatePlanPriceInput = z.output; + +export const UpdatePlanPriceResultDtoSchema = z.object({ + country: countryCodeSchema, + amount: z.number(), + /** Live subscriptions queued to move to the new price. */ + queued: z.number().int(), +}); +export type UpdatePlanPriceResultDto = z.output; + +export const AdminPlanPriceSchema = z.object({ + country: countryCodeSchema, + amount: z.number(), + currency: z.string(), + provider: billingProviderIdSchema, + updatedAt: isoDateTimeSchema.nullable(), + /** Authorized or paused subscriptions of the country: what "apply to existing" moves. */ + liveSubscriptions: z.number().int(), + /** Live subscriptions still at a different price. */ + atOtherPrice: z.number().int(), + /** Price changes waiting to reach the provider. */ + pendingChanges: z.number().int(), + /** Price changes the provider refused after every retry. */ + failedChanges: z.number().int(), +}); +export type AdminPlanPrice = z.output; + +export const AdminPlansDtoSchema = z.object({ + limits: z.object({ FREE: PlanLimitsSchema, PRO: PlanLimitsSchema }), + prices: z.array(AdminPlanPriceSchema), +}); +export type AdminPlansDto = z.output; diff --git a/packages/shared/src/schemas/billing.ts b/packages/shared/src/schemas/billing.ts index 405feae..3afe657 100644 --- a/packages/shared/src/schemas/billing.ts +++ b/packages/shared/src/schemas/billing.ts @@ -20,6 +20,9 @@ export type PlanLimits = { mpCharges: boolean; }; +// Defaults only: the live limits and prices are edited from the backoffice and +// live in `plan_configs` / `plan_prices` (seeded with these values). The backend +// falls back to them when a row is missing; the web asks `GET /billing/plans`. export const PLAN_LIMITS: Record = { FREE: { maxGroups: 1, maxAttendees: 15, whatsappAutomations: false, mpCharges: false }, PRO: { maxGroups: null, maxAttendees: null, whatsappAutomations: true, mpCharges: true }, @@ -66,13 +69,20 @@ export type SubscriptionStatus = z.output; export const billingReturnToSchema = z.enum(['onboarding', 'billing']); export type BillingReturnTo = z.output; -const PlanLimitsSchema = z.object({ +export const PlanLimitsSchema = z.object({ maxGroups: z.number().int().nullable(), maxAttendees: z.number().int().nullable(), whatsappAutomations: z.boolean(), mpCharges: z.boolean(), }); +/** What each plan allows and what Pro costs in each country, as configured now. */ +export const PlanCatalogDtoSchema = z.object({ + limits: z.object({ FREE: PlanLimitsSchema, PRO: PlanLimitsSchema }), + proPrices: z.record(countryCodeSchema, z.object({ amount: z.number(), currency: z.string() })), +}); +export type PlanCatalogDto = z.output; + export const BillingStatusDtoSchema = z.object({ plan: planSchema, /** `null` when the professor never started a subscription. */ @@ -85,6 +95,8 @@ export const BillingStatusDtoSchema = z.object({ nextPaymentDate: isoDateTimeSchema.nullable(), payerEmail: z.string().nullable(), priceAmount: z.number(), + /** A new price that applies from the next charge on; `null` when unchanged. */ + nextPriceAmount: z.number().nullable(), currency: z.string(), country: countryCodeSchema, /** Who collects (or would collect) the subscription. */ -- 2.49.1