Language selector on onboarding screen

Fixed docker-compose
This commit is contained in:
Jose Selesan
2026-11-10 18:27:15 -03:00
parent 8cb5fe9b08
commit abb18f1815
7 changed files with 251 additions and 96 deletions

View File

@@ -3,7 +3,9 @@
# Local: copy this file to `.env` at the root and fill in the values. # Local: copy this file to `.env` at the root and fill in the values.
# Dokploy: no file needed; define the same variables in the Environment tab of # Dokploy: no file needed; define the same variables in the Environment tab of
# the Compose service (Dokploy writes them to a `.env` next to the compose # the Compose service (Dokploy writes them to a `.env` next to the compose
# file, which is where the `${...}` come from). # file). The api container receives this whole file through `env_file`, so any
# variable the backend reads (docs/environment.md) works without touching the
# compose.
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and # Public origin of the app, no trailing slash. The same value feeds WEB_URL and
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a # BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
@@ -46,17 +48,25 @@ BETTER_AUTH_SECRET=""
# MP_CLIENT_ID="" # MP_CLIENT_ID=""
# MP_CLIENT_SECRET="" # MP_CLIENT_SECRET=""
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md). # Suscripción a Gruperly Pro (ver docs/billing.md y docs/environment.md).
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra # Argentina la cobra con Suscripciones de Mercado Pago; el resto, con Stripe.
# entre países). No son las del OAuth del profesor. Un país sin las dos queda # Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina. No
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY. # son las del OAuth del profesor. Sin las dos, Pro queda "no disponible" (503).
# MP_PLATFORM_ACCESS_TOKEN_AR="" # MP_PLATFORM_ACCESS_TOKEN_AR=""
# MP_PLATFORM_WEBHOOK_SECRET_AR="" # MP_PLATFORM_WEBHOOK_SECRET_AR=""
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda de
# cada país. Secret key (sk_live_…) y signing secret del webhook (whsec_…) del
# endpoint https://<API>/api/v1/billing/webhooks/stripe. Sin las dos, 503 ahí.
# STRIPE_SECRET_KEY=""
# STRIPE_WEBHOOK_SECRET=""
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro. # on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
# BILLING_ENFORCEMENT="off" # BILLING_ENFORCEMENT="off"
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando. # Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
# BILLING_GRACE_DAYS="7" # BILLING_GRACE_DAYS="7"
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
# ADMIN_EMAILS=""
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md). # WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503 # Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
# whatsapp_not_configured y el paso del onboarding es salteable. # whatsapp_not_configured y el paso del onboarding es salteable.

View File

@@ -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>` nativo (transparente encima de la píldora), que
en mobile es la hoja del sistema. Guarda en la cuenta igual que en Ajustes. */
export function LanguageSwitcher() {
const { t } = useTranslation('settings')
const { preference, locale, device } = useLocale()
const select = useSelectLocale(true)
return (
<div className="relative inline-flex items-center gap-1 rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-foreground/70 transition-colors focus-within:ring-2 focus-within:ring-accent hover:bg-primary-soft">
<Languages className="size-3.5" aria-hidden="true" />
<span aria-hidden="true">{locale.split('-')[0].toUpperCase()}</span>
<ChevronDown className="size-3" aria-hidden="true" />
<select
aria-label={t('language.title')}
value={preference}
onChange={(event) => select(event.target.value as LocalePreference)}
className="absolute inset-0 cursor-pointer appearance-none opacity-0"
>
{OPTIONS.map((option) => (
<option key={option} value={option} lang={option === 'system' ? undefined : option}>
{option === 'system'
? `${t('language.system')} (${LOCALE_NAMES[device]})`
: LOCALE_NAMES[option]}
</option>
))}
</select>
</div>
)
}

View File

@@ -8,6 +8,7 @@ import { useAuth } from '../../context/AuthProvider'
import { ConfirmationStep } from './ConfirmationStep' import { ConfirmationStep } from './ConfirmationStep'
import { CountryStep } from './CountryStep' import { CountryStep } from './CountryStep'
import { FirstGroupStep } from './FirstGroupStep' import { FirstGroupStep } from './FirstGroupStep'
import { LanguageSwitcher } from './LanguageSwitcher'
import { useOnboarding } from './OnboardingProvider' import { useOnboarding } from './OnboardingProvider'
import { PaymentStep } from './PaymentStep' import { PaymentStep } from './PaymentStep'
import { PlanStep } from './PlanStep' import { PlanStep } from './PlanStep'
@@ -108,8 +109,11 @@ export function OnboardingView() {
return ( return (
<main className="mx-auto flex min-h-dvh w-full max-w-md flex-col px-4 pt-8 pb-[calc(3rem+env(safe-area-inset-bottom))] sm:pt-12"> <main className="mx-auto flex min-h-dvh w-full max-w-md flex-col px-4 pt-8 pb-[calc(3rem+env(safe-area-inset-bottom))] sm:pt-12">
<header className="mb-6 flex items-center justify-center"> <header className="relative mb-6 flex items-center justify-center">
<Logo className="h-6" /> <Logo className="h-6" />
<div className="absolute right-0">
<LanguageSwitcher />
</div>
</header> </header>
{/* Con Free no se muestran Cobros ni WhatsApp: el stepper refleja solo {/* Con Free no se muestran Cobros ni WhatsApp: el stepper refleja solo

View File

@@ -1,12 +1,10 @@
import { SUPPORTED_LOCALES } from '@gruperly/shared' import { SUPPORTED_LOCALES } from '@gruperly/shared'
import { Check, Languages } from 'lucide-react' import { Check, Languages } from 'lucide-react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useToast } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider'
import { useLocale, type LocalePreference } from '../../i18n' import { useLocale, type LocalePreference } from '../../i18n'
import { LOCALE_NAMES } from '../../i18n/locales' import { LOCALE_NAMES } from '../../i18n/locales'
import { authClient } from '../../lib/auth-client'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { useSelectLocale } from './useSelectLocale'
const OPTIONS: LocalePreference[] = ['system', ...SUPPORTED_LOCALES] const OPTIONS: LocalePreference[] = ['system', ...SUPPORTED_LOCALES]
@@ -18,19 +16,8 @@ type LanguageCardProps = {
export function LanguageCard({ syncProfile = false }: LanguageCardProps) { export function LanguageCard({ syncProfile = false }: LanguageCardProps) {
const { t } = useTranslation('settings') const { t } = useTranslation('settings')
const { preference, device, setPreference } = useLocale() const { preference, device } = useLocale()
const { user } = useAuth() const select = useSelectLocale(syncProfile)
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'))
})
}
return ( return (
<div className="divide-y divide-border rounded-xl border border-border bg-surface"> <div className="divide-y divide-border rounded-xl border border-border bg-surface">

View File

@@ -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'))
})
}
}

View File

@@ -7,88 +7,27 @@
# `location /api/` block from apps/web/nginx.conf and set VITE_API_URL when # `location /api/` block from apps/web/nginx.conf and set VITE_API_URL when
# building web. # 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 x-backend-env: &backend-env
NODE_ENV: production NODE_ENV: production
# Web and API share the public domain: same origin for cookies and CORS.
DATABASE_URL: "${DATABASE_URL:?falta DATABASE_URL}" DATABASE_URL: "${DATABASE_URL:?falta DATABASE_URL}"
WEB_URL: "${WEB_URL:?falta WEB_URL - origen publico de la app, sin barra final}" 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_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}" 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 <no-reply@gruperly.com>}"
# 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 # 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} 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: <WEB_URL>/api/v1/whatsapp/webhooks/openwa (requiere el secreto).
OPENWA_WEBHOOK_URL: ${OPENWA_WEBHOOK_URL:-}
OPENWA_WEBHOOK_SECRET: ${OPENWA_WEBHOOK_SECRET:-}
KAPSO_API_KEY: ${KAPSO_API_KEY:-}
KAPSO_CALLBACK_URL: ${KAPSO_CALLBACK_URL:-}
KAPSO_WEBHOOK_URL: ${KAPSO_WEBHOOK_URL:-}
KAPSO_WEBHOOK_SECRET: ${KAPSO_WEBHOOK_SECRET:-}
services: services:
api: api:
@@ -96,6 +35,9 @@ services:
context: . context: .
dockerfile: Dockerfile.backend dockerfile: Dockerfile.backend
target: api target: api
env_file:
- path: .env
required: false
environment: *backend-env environment: *backend-env
restart: unless-stopped restart: unless-stopped
expose: expose:

148
docs/environment.md Normal file
View File

@@ -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_<CC>`, `MP_PLATFORM_WEBHOOK_SECRET_<CC>` |
| 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>/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 (`<CC>`); 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>/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_*_<CC>` 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>/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 <no-reply@gruperly.com>` | 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>/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>/api/v1/whatsapp/callback` (vuelta del setup link). Pública. |
| `KAPSO_WEBHOOK_URL` | — | `https://<API>/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`). |