Compare commits
10 Commits
925f1a256d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| ca60733ea0 | |||
|
|
aac142d324 | ||
|
|
abb18f1815 | ||
|
|
4211d5cf39 | ||
|
|
8cb5fe9b08 | ||
|
|
f4a6f2653f | ||
| bd7712b28e | |||
|
|
2d80af082f | ||
|
|
70ef049f34 | ||
|
|
f0bb02ab73 |
23
.env.example
23
.env.example
@@ -3,7 +3,9 @@
|
|||||||
# Local: copy this file to `.env` at the root and fill in the values.
|
# Local: copy this file to `.env` at the root and fill in the values.
|
||||||
# Dokploy: no file needed; define the same variables in the Environment tab of
|
# Dokploy: no file needed; define the same variables in the Environment tab of
|
||||||
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
# the Compose service (Dokploy writes them to a `.env` next to the compose
|
||||||
# file, which is where the `${...}` come from).
|
# file). The api container receives this whole file through `env_file`, so any
|
||||||
|
# variable the backend reads (docs/environment.md) works without touching the
|
||||||
|
# compose.
|
||||||
|
|
||||||
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
# Public origin of the app, no trailing slash. The same value feeds WEB_URL and
|
||||||
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
# BETTER_AUTH_URL because nginx proxies /api: the web and the API share a
|
||||||
@@ -46,17 +48,28 @@ BETTER_AUTH_SECRET=""
|
|||||||
# MP_CLIENT_ID=""
|
# MP_CLIENT_ID=""
|
||||||
# MP_CLIENT_SECRET=""
|
# MP_CLIENT_SECRET=""
|
||||||
|
|
||||||
# Suscripción a Gruperly Pro (Suscripciones de Mercado Pago, ver docs/billing.md).
|
# Suscripción a Gruperly Pro (ver docs/billing.md y docs/environment.md).
|
||||||
# Credenciales de las cuentas de MP **de Gruperly**, una por país (MP no cobra
|
# Argentina la cobra con Suscripciones de Mercado Pago; el resto, con Stripe.
|
||||||
# entre países). No son las del OAuth del profesor. Un país sin las dos queda
|
# Mercado Pago: credenciales de la cuenta de MP **de Gruperly** en Argentina. No
|
||||||
# con Pro "no disponible" (503). Códigos: AR, BR, CL, CO, MX, PE, UY.
|
# son las del OAuth del profesor. Sin las dos, Pro queda "no disponible" (503).
|
||||||
# MP_PLATFORM_ACCESS_TOKEN_AR=""
|
# MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||||
# MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
# MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||||
|
# Origen público de la API para la vuelta del checkout de Pro. Vacío =
|
||||||
|
# BETTER_AUTH_URL, que en este compose ya es el dominio público.
|
||||||
|
# API_PUBLIC_URL=""
|
||||||
|
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda de
|
||||||
|
# cada país. Secret key (sk_live_…) y signing secret del webhook (whsec_…) del
|
||||||
|
# endpoint https://<API>/api/v1/billing/webhooks/stripe. Sin las dos, 503 ahí.
|
||||||
|
# STRIPE_SECRET_KEY=""
|
||||||
|
# STRIPE_WEBHOOK_SECRET=""
|
||||||
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
# on = aplica los límites del plan Free. Cualquier otro valor (o vacío): todos Pro.
|
||||||
# BILLING_ENFORCEMENT="off"
|
# BILLING_ENFORCEMENT="off"
|
||||||
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
# Días que un Pro vencido (cancelado o con el cobro rechazado) sigue funcionando.
|
||||||
# BILLING_GRACE_DAYS="7"
|
# BILLING_GRACE_DAYS="7"
|
||||||
|
|
||||||
|
# Backoffice (/admin): emails del equipo de Gruperly, separados por coma. Vacío = nadie.
|
||||||
|
# ADMIN_EMAILS=""
|
||||||
|
|
||||||
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
|
# WhatsApp: recordatorios de pago y reenganche semanales (docs/whatsapp.md).
|
||||||
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
|
# Opcional: sin las variables del proveedor elegido, /whatsapp/* responde 503
|
||||||
# whatsapp_not_configured y el paso del onboarding es salteable.
|
# whatsapp_not_configured y el paso del onboarding es salteable.
|
||||||
|
|||||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -6,6 +6,7 @@ npm-debug.log*
|
|||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
lerna-debug.log*
|
lerna-debug.log*
|
||||||
|
.impeccable
|
||||||
|
|
||||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||||
@@ -149,3 +150,14 @@ apps/backend/generated/
|
|||||||
# env
|
# env
|
||||||
apps/backend/.env
|
apps/backend/.env
|
||||||
|
|
||||||
|
|
||||||
|
# macOS
|
||||||
|
.DS_Store
|
||||||
|
|
||||||
|
# archify: solo se versionan el HTML final y el candidate.json; lo intermedio no
|
||||||
|
.archify/**/*.browser-check.json
|
||||||
|
.archify/**/*.delivery.json
|
||||||
|
.archify/**/*.finalize.json
|
||||||
|
.archify/**/*.finalize-summary.json
|
||||||
|
.archify/**/candidate.before-review.json
|
||||||
|
.archify/**/review-*/
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
|
||||||
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||||
- `src/logger.ts` — pino + pino-pretty.
|
- `src/logger.ts` — pino + pino-pretty.
|
||||||
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; guía en `docs/billing.md`). `admin` (backoffice de solo lectura de las cuentas de profesores: acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
|
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`; recuperar contraseña en la web vía `/forgot-password` → email → `/reset-password?token=…`: el `redirectTo` de `requestPasswordReset` tiene que ser **absoluto** a la web, uno relativo Better Auth lo resuelve contra la URL de la API; `revokeSessionsOnPasswordReset` cierra todas las sesiones), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`. `whatsapp` (mensajes automáticos semanales: recordatorio de pago y reenganche; `WEEKLY_MESSAGES_CRON` `0 13 * * 1` UTC y `SyncKapsoTemplates` `*/30` solo con Kapso, arrancados por `startWhatsappJobs()`; `PATCH /groups/:gid/automations` se engancha en `modules/groups/routes.ts`; guía en `docs/whatsapp.md`). `billing` (plan de Gruperly: Free/Pro con Suscripciones de MP; `startBillingJobs()` y `planReadOnlyMiddleware` en `app.ts`; límites y precio de Pro por país se leen con `PlanCatalog`/`planCatalog`, nunca con `PLAN_LIMITS`/`PRO_PRICE_BY_COUNTRY` directo, que son solo defaults; guía en `docs/billing.md`). `admin` (backoffice de las cuentas de profesores, de solo lectura salvo **Planes** (`/admin/plans`: límites y precio de Pro, con opción de aplicar el precio a las suscripciones vivas desde el próximo cobro): acceso por allowlist `ADMIN_EMAILS`, `GET /admin/me` abierto a cualquier sesión y `adminOnlyMiddleware` en `/admin/accounts*` y `/admin/plans*`; el filtro por plan usa `proSubscriptionWhere`, que tiene que seguir a `resolvePlan`). En la web vive en `/admin`, colgado de la raíz y **no** de `_authenticated` (un admin no pasa por el onboarding); el link aparece en `UserMenu` solo para admins. `attention` ("Requiere atención": `GET /attention` devuelve todos los miembros ACTIVE por grupo con sus alertas, teléfono en E.164 y cuotas `OVERDUE`; `POST /attention/:attendeeId/resolve` guarda `{ tipo, firma }` en `attendee_alert_resolutions`, una fila por alumno y tipo: la alerta vuelve sola cuando cambia la firma —última falta o ids de cuotas vencidas—). Las alertas salen de `computeStudentAlerts` (`packages/shared/src/lib/student-alerts.ts`), que reusa la **única** regla de asistencia (`ATTENDANCE_RISK_RULES` en `attendance-risk.ts`: urgente = 3 seguidas o 4 de las últimas 6 clases marcadas; a vigilar = 2 de las últimas 4) y suma la de cuotas (`STUDENT_ALERT_RULES`: 1 vencida vigilar, 2+ urgente). Inicio, la ficha de grupo y el job de reenganche usan la misma regla.
|
||||||
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
|
- `student-portal` (API del **alumno o tutor**, `/api/v1/student-portal/*`) y `student-access` (su lado profe: invitar/estado en `/groups/:gid/attendees/:aid/student-access`, faltas avisadas en `/groups/:gid/absence-notices`, enganchado en `modules/groups/routes.ts`). La revisión de pagos informados (`/payments/reported*`) y los datos para transferir (`/payments/transfer-details`) viven en `modules/payments`. Guía en el gotcha **App de alumnos**.
|
||||||
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
|
||||||
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
|
||||||
@@ -39,10 +39,10 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
|
|
||||||
## Gotchas operativos
|
## Gotchas operativos
|
||||||
|
|
||||||
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
|
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). Como la cookie de sesión es de `localhost:4000`, el callback que entra por el túnel rebota a `BETTER_AUTH_URL` con la misma query (`mpCallbackOriginMiddleware`, antes del middleware de sesión; no se dispara si ambos hosts coinciden, como en prod). El callback además exige que la sesión sea la del dueño del `state`. El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
|
||||||
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
|
||||||
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
|
||||||
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). Cada link lleva `notification_url` a `POST /payments/webhooks/mp/:paymentId` (público; solo si `API_PUBLIC_URL` es HTTPS pública): el aviso no se lee, se le pregunta a MP con el token del dueño vía `confirmMpPayment`, la misma regla del polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), que sigue de respaldo, y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
|
||||||
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
|
||||||
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
|
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers/<nombre>/`.
|
||||||
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
|
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
|
||||||
@@ -61,7 +61,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
|
3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`).
|
||||||
4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
|
4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback.
|
||||||
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
|
5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`.
|
||||||
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp.
|
6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. El paso vive en `?step=` (el back del dispositivo retrocede un paso) y lo que pide la URL pasa por `effectiveStep`: sin plan no se pasa de Plan y con el grupo ya creado no se vuelve al formulario. Los callbacks (`?mp=`, `?wa=`, `?sub=`) navegan con `replace` al paso que corresponde.
|
||||||
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
|
||||||
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
|
||||||
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).
|
||||||
@@ -98,6 +98,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
|
|||||||
|
|
||||||
## Convenciones repo-específicas
|
## Convenciones repo-específicas
|
||||||
|
|
||||||
|
- **Commits en inglés**: los mensajes de commit (título y cuerpo) van siempre en inglés, con prefijo Conventional Commits (`feat(i18n): …`, `fix: …`, `chore: …`). Los commits anteriores en español quedan como están.
|
||||||
- **Copy de UI traducido**: ningún texto visible va literal en JSX; va en `apps/web/src/i18n/locales/es-AR/<namespace>.json` (fuente, en rioplatense) y en el mismo cambio en `es-419`, `pt-BR` y `en` (ver gotcha **Multi idioma**). Los comentarios del frontend siguen en español.
|
- **Copy de UI traducido**: ningún texto visible va literal en JSX; va en `apps/web/src/i18n/locales/es-AR/<namespace>.json` (fuente, en rioplatense) y en el mismo cambio en `es-419`, `pt-BR` y `en` (ver gotcha **Multi idioma**). Los comentarios del frontend siguen en español.
|
||||||
- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`).
|
- **Paths de rutas en inglés**: aunque el copy esté en español, los segmentos de URL van siempre en inglés, tanto en la web (nombres de archivo en `apps/web/src/routes/`, `createFileRoute`, `to=`/`navigate`) como en la API y en los links que arma el backend (p. ej. `/student/payments`, no `/alumno/pagos`; `/access`, no `/acceso`).
|
||||||
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
|
- **Base de datos**: todas las tablas y columnas físicas usan **snake_case**. Los modelos declaran `@@map` (p. ej. `User` → `users`, `WaitlistEntry` → `waitlist_entries`) y todo campo Prisma camelCase que cree una columna debe declarar `@map("nombre_campo")` (p. ej. `createdAt @map("created_at")`). Al agregar un modelo o campo nuevo, incluir siempre el mapping correspondiente sin cambiar la API camelCase de Prisma Client.
|
||||||
|
|||||||
@@ -206,9 +206,11 @@ Si falta alguna obligatoria, el compose aborta antes de construir, con el nombre
|
|||||||
|
|
||||||
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
|
1. Creá una aplicación tipo **Compose** apuntando al repo (el `docker-compose.yml` de la raíz).
|
||||||
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
|
2. En **Environment** cargá `DATABASE_URL`, `WEB_URL` y `BETTER_AUTH_SECRET` (deshabilitadas las que no uses). Guardá.
|
||||||
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor**, no el del host. El compose publica `8080:80` — el `8080` es para probar en local; nginx escucha `80` adentro. Si ponés `8080` en el panel, Traefik marca la conexión y devuelve Bad Gateway.
|
3. En **General → Domains** asociá el dominio solo al servicio `web`, puerto **`80`**. Ojo: el puerto del dominio es el **puerto del contenedor** (nginx escucha `80` adentro). El compose no publica puertos en el host: Traefik llega por `dokploy-network`.
|
||||||
4. Deploy.
|
4. Deploy.
|
||||||
|
|
||||||
|
Se pueden tener varias apps Compose de este repo en el mismo server (p. ej. dev y prod): como no se publican puertos en el host no chocan, y nginx le pega a su propia API por el alias `gruperly-api`, que solo existe en la red de cada stack. Cada app necesita su dominio, su `WEB_URL`, su `DATABASE_URL` (otra base) y su `BETTER_AUTH_SECRET`.
|
||||||
|
|
||||||
En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
|
En `DATABASE_URL` usá el host interno que muestra la base en Dokploy (ej. `piservices-db-llwatq:5432`), que solo resuelve dentro de `dokploy-network`.
|
||||||
|
|
||||||
Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
|
Si la API no levanta, el motivo está en los logs del servicio `api` (pestaña **Logs**), que incluyen la salida de Prisma.
|
||||||
@@ -226,7 +228,7 @@ Fuera de Dokploy hay que crear `dokploy-network` una vez, porque el compose la d
|
|||||||
```bash
|
```bash
|
||||||
docker network create dokploy-network # una sola vez
|
docker network create dokploy-network # una sola vez
|
||||||
cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
|
cp .env.example .env # completá DATABASE_URL, WEB_URL y BETTER_AUTH_SECRET
|
||||||
docker compose up --build -d
|
docker compose -f docker-compose.yml -f docker-compose.local.yml up --build -d # publica web en :8080
|
||||||
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
|
docker compose logs api # debe salir "migrate: listo" y "Server running on ..."
|
||||||
curl http://localhost:8080/api/v1/health
|
curl http://localhost:8080/api/v1/health
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -38,6 +38,11 @@ TOKEN_ENCRYPTION_KEY=""
|
|||||||
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
|
# son las del OAuth del profesor). Sin las dos, Pro queda "no disponible" (503).
|
||||||
MP_PLATFORM_ACCESS_TOKEN_AR=""
|
MP_PLATFORM_ACCESS_TOKEN_AR=""
|
||||||
MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
MP_PLATFORM_WEBHOOK_SECRET_AR=""
|
||||||
|
# Origen público de esta API, adonde MP y Stripe devuelven el navegador después
|
||||||
|
# del checkout de Pro (GET /api/v1/billing/return, que redirige a la web). MP
|
||||||
|
# rechaza localhost: en local poné el túnel (https://TU-DOMINIO.ngrok-free.app).
|
||||||
|
# Vacío = BETTER_AUTH_URL.
|
||||||
|
API_PUBLIC_URL=""
|
||||||
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
|
# Stripe: una sola cuenta para BR, CL, CO, MX, PE y UY, cobrando en la moneda
|
||||||
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
|
# de cada país. Secret key (sk_test_… en local) y el signing secret del webhook
|
||||||
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
|
# (whsec_…; en local lo imprime `stripe listen`). Sin las dos, 503 en esos países.
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PlanId" AS ENUM ('FREE', 'PRO');
|
||||||
|
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "billing_subscriptions" ADD COLUMN "pending_amount" DECIMAL(12,2),
|
||||||
|
ADD COLUMN "price_change_attempts" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
ADD COLUMN "price_change_error" TEXT,
|
||||||
|
ADD COLUMN "price_change_id" TEXT;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "plan_configs" (
|
||||||
|
"plan" "PlanId" NOT NULL,
|
||||||
|
"max_groups" INTEGER,
|
||||||
|
"max_attendees" INTEGER,
|
||||||
|
"whatsapp_automations" BOOLEAN NOT NULL,
|
||||||
|
"mp_charges" BOOLEAN NOT NULL,
|
||||||
|
"updated_by_id" TEXT,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "plan_configs_pkey" PRIMARY KEY ("plan")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "plan_prices" (
|
||||||
|
"country_code" TEXT NOT NULL,
|
||||||
|
"amount" DECIMAL(12,2) NOT NULL,
|
||||||
|
"updated_by_id" TEXT,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "plan_prices_pkey" PRIMARY KEY ("country_code")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "plan_price_changes" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"country_code" TEXT NOT NULL,
|
||||||
|
"previous_amount" DECIMAL(12,2),
|
||||||
|
"new_amount" DECIMAL(12,2) NOT NULL,
|
||||||
|
"currency" TEXT NOT NULL,
|
||||||
|
"apply_to_existing" BOOLEAN NOT NULL,
|
||||||
|
"queued" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"created_by_id" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "plan_price_changes_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "plan_price_changes_country_created_at_idx" ON "plan_price_changes"("country_code", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "billing_subscriptions_pending_amount_idx" ON "billing_subscriptions"("pending_amount");
|
||||||
|
|
||||||
|
-- Seed with the defaults that lived in code (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`
|
||||||
|
-- in packages/shared), so nothing changes on deploy.
|
||||||
|
INSERT INTO "plan_configs" ("plan", "max_groups", "max_attendees", "whatsapp_automations", "mp_charges", "updated_at") VALUES
|
||||||
|
('FREE', 1, 15, false, false, CURRENT_TIMESTAMP),
|
||||||
|
('PRO', NULL, NULL, true, true, CURRENT_TIMESTAMP);
|
||||||
|
|
||||||
|
INSERT INTO "plan_prices" ("country_code", "amount", "updated_at") VALUES
|
||||||
|
('AR', 15000, CURRENT_TIMESTAMP),
|
||||||
|
('BR', 49, CURRENT_TIMESTAMP),
|
||||||
|
('CL', 9900, CURRENT_TIMESTAMP),
|
||||||
|
('CO', 39900, CURRENT_TIMESTAMP),
|
||||||
|
('MX', 199, CURRENT_TIMESTAMP),
|
||||||
|
('PE', 39, CURRENT_TIMESTAMP),
|
||||||
|
('UY', 390, CURRENT_TIMESTAMP);
|
||||||
@@ -39,6 +39,12 @@ model BillingSubscription {
|
|||||||
// period, even after a cancellation or a failed renewal.
|
// period, even after a cancellation or a failed renewal.
|
||||||
paidThrough DateTime? @map("paid_through")
|
paidThrough DateTime? @map("paid_through")
|
||||||
lastSyncedAt DateTime? @map("last_synced_at")
|
lastSyncedAt DateTime? @map("last_synced_at")
|
||||||
|
// A new price queued by the backoffice for this live subscription: the job
|
||||||
|
// pushes it to the provider (from the next charge) and moves it to `amount`.
|
||||||
|
pendingAmount Decimal? @db.Decimal(12, 2) @map("pending_amount")
|
||||||
|
priceChangeId String? @map("price_change_id")
|
||||||
|
priceChangeAttempts Int @default(0) @map("price_change_attempts")
|
||||||
|
priceChangeError String? @map("price_change_error")
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
@@ -47,6 +53,7 @@ model BillingSubscription {
|
|||||||
|
|
||||||
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
|
// The reconciliation job walks PENDING and stale AUTHORIZED rows.
|
||||||
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
|
@@index([status, lastSyncedAt], map: "billing_subscriptions_status_lastSyncedAt_idx")
|
||||||
|
@@index([pendingAmount], map: "billing_subscriptions_pending_amount_idx")
|
||||||
@@map("billing_subscriptions")
|
@@map("billing_subscriptions")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,3 +87,52 @@ model BillingWebhookEvent {
|
|||||||
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
|
@@index([receivedAt], map: "billing_webhook_events_receivedAt_idx")
|
||||||
@@map("billing_webhook_events")
|
@@map("billing_webhook_events")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum PlanId {
|
||||||
|
FREE
|
||||||
|
PRO
|
||||||
|
}
|
||||||
|
|
||||||
|
// What each plan allows, edited from the backoffice. Seeded with the defaults
|
||||||
|
// of `PLAN_LIMITS` (shared); a missing row falls back to them. Applies at once.
|
||||||
|
model PlanConfig {
|
||||||
|
plan PlanId @id
|
||||||
|
// Null means no limit.
|
||||||
|
maxGroups Int? @map("max_groups")
|
||||||
|
maxAttendees Int? @map("max_attendees")
|
||||||
|
whatsappAutomations Boolean @map("whatsapp_automations")
|
||||||
|
mpCharges Boolean @map("mp_charges")
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import { healthCheckRoutes } from './modules/health-check';
|
|||||||
import { homeRoutes } from './modules/home';
|
import { homeRoutes } from './modules/home';
|
||||||
import { invitationsRoutes } from './modules/invitations';
|
import { invitationsRoutes } from './modules/invitations';
|
||||||
import { mpRoutes } from './modules/mp';
|
import { mpRoutes } from './modules/mp';
|
||||||
|
import { mpCallbackOriginMiddleware } from './modules/mp/lib';
|
||||||
import { onboardingRoutes } from './modules/onboarding';
|
import { onboardingRoutes } from './modules/onboarding';
|
||||||
import { paymentsRoutes } from './modules/payments';
|
import { paymentsRoutes } from './modules/payments';
|
||||||
import { peopleRoutes } from './modules/people';
|
import { peopleRoutes } from './modules/people';
|
||||||
@@ -43,6 +44,9 @@ app.get('/', (c) => c.json({ name: 'Gruperly API', status: 'ok' }));
|
|||||||
|
|
||||||
const api = app.basePath('/api/v1');
|
const api = app.basePath('/api/v1');
|
||||||
|
|
||||||
|
// Local development: the MP callback comes back through the tunnel, without the
|
||||||
|
// session cookie of localhost. Replay it there before asking for a session.
|
||||||
|
api.use('/mp/callback', mpCallbackOriginMiddleware);
|
||||||
api.use('*', sessionAuthMiddleware);
|
api.use('*', sessionAuthMiddleware);
|
||||||
|
|
||||||
// Read-only accounts (Free over its limits) cannot write domain data. Billing,
|
// Read-only accounts (Free over its limits) cannot write domain data. Billing,
|
||||||
|
|||||||
@@ -47,6 +47,15 @@ export function isPublicApiRequest(method: string, path: string): boolean {
|
|||||||
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
|
if (method === 'POST' && /^\/api\/v1\/billing\/webhooks\/mp\/[a-z]{2}$/i.test(normalizedPath)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
// Mercado Pago notifications about a Checkout Pro payment: no session; the
|
||||||
|
// owner's Mercado Pago account is asked before anything changes.
|
||||||
|
if (method === 'POST' && /^\/api\/v1\/payments\/webhooks\/mp\/[A-Za-z0-9_-]+$/.test(normalizedPath)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Back from the Pro checkout: only redirects to the web, which has the session.
|
||||||
|
if (method === 'GET' && normalizedPath === '/api/v1/billing/return') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
|
// Stripe notifications about Pro subscriptions: authenticated by `Stripe-Signature`.
|
||||||
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
|
if (method === 'POST' && normalizedPath === '/api/v1/billing/webhooks/stripe') {
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -6,6 +6,15 @@ type PasswordResetEmailData = { email: string; url: string; name?: string }
|
|||||||
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
type InvitationEmailData = { email: string; url: string; organizationName: string }
|
||||||
type StudentEmailConfirmationData = { email: string; url: string; name: string }
|
type StudentEmailConfirmationData = { email: string; url: string; name: string }
|
||||||
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
|
type StudentRecoveryEmailData = { email: string; links: { name: string; url: string }[] }
|
||||||
|
type ProPriceChangedData = {
|
||||||
|
email: string
|
||||||
|
name: string
|
||||||
|
/** Already formatted in the professor's currency. */
|
||||||
|
amount: string
|
||||||
|
/** Already formatted; `null` when the provider has not scheduled the next charge. */
|
||||||
|
nextPaymentDate: string | null
|
||||||
|
billingUrl: string
|
||||||
|
}
|
||||||
type StudentPaymentReviewedData = {
|
type StudentPaymentReviewedData = {
|
||||||
email: string
|
email: string
|
||||||
name: string
|
name: string
|
||||||
@@ -42,6 +51,7 @@ export interface EmailProvider {
|
|||||||
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
sendStudentEmailConfirmation(data: StudentEmailConfirmationData): Promise<void>
|
||||||
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
sendStudentRecoveryLinks(data: StudentRecoveryEmailData): Promise<void>
|
||||||
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
sendStudentPaymentReviewed(data: StudentPaymentReviewedData): Promise<void>
|
||||||
|
sendProPriceChanged(data: ProPriceChangedData): Promise<void>
|
||||||
}
|
}
|
||||||
|
|
||||||
// Names come from what teachers and students type: never raw into the HTML.
|
// Names come from what teachers and students type: never raw into the HTML.
|
||||||
@@ -176,6 +186,20 @@ class SMTPEmailProvider implements EmailProvider {
|
|||||||
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
|
this.layout(confirmed ? 'Pago confirmado' : 'Pago rechazado', body),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async sendProPriceChanged({ email, name, amount, nextPaymentDate, billingUrl }: ProPriceChangedData) {
|
||||||
|
const when = nextPaymentDate
|
||||||
|
? `desde tu próximo cobro, el ${escapeHtml(nextPaymentDate)}`
|
||||||
|
: 'desde tu próximo cobro'
|
||||||
|
await this.send(
|
||||||
|
email,
|
||||||
|
'Cambia el precio de Gruperly Pro',
|
||||||
|
this.layout(
|
||||||
|
'Nuevo precio de Gruperly Pro',
|
||||||
|
`Hola ${escapeHtml(name)}, te avisamos que el precio de tu suscripción a Gruperly Pro pasa a ser de ${escapeHtml(amount)} por mes ${when}. Lo que ya pagaste no cambia.<br/><br/>Si no querés seguir, podés cancelar la suscripción cuando quieras y vas a seguir con Pro hasta el final del período pago.<br/><br/>${button(billingUrl, 'Ver mi plan')}`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Future: transactional providers (Resend, SendGrid, Postmark).
|
// Future: transactional providers (Resend, SendGrid, Postmark).
|
||||||
|
|||||||
17
apps/backend/src/lib/public-origin.ts
Normal file
17
apps/backend/src/lib/public-origin.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
const DEFAULT_API_ORIGIN = 'http://localhost:4000';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Public origin of this API, as the billing providers reach it. Mercado Pago
|
||||||
|
* refuses a non-public `back_url` and `notification_url` (localhost), so in local development it is the
|
||||||
|
* ngrok tunnel. Falls back to `BETTER_AUTH_URL`, which is the API's base URL
|
||||||
|
* (in production the same origin as the web, since nginx proxies `/api`).
|
||||||
|
*/
|
||||||
|
export function getApiPublicOrigin(env: Record<string, string | undefined> = process.env): string {
|
||||||
|
const configured = env.API_PUBLIC_URL?.trim() || env.BETTER_AUTH_URL?.trim();
|
||||||
|
if (!configured) return DEFAULT_API_ORIGIN;
|
||||||
|
try {
|
||||||
|
return new URL(configured).origin;
|
||||||
|
} catch {
|
||||||
|
return DEFAULT_API_ORIGIN;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
|
import type { AdminAccountDetail, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { exceedsLimits, getGraceDays, isBillingEnforced, toBillingChargeDto } from '@/modules/billing/lib';
|
import {
|
||||||
|
exceedsLimits,
|
||||||
|
getGraceDays,
|
||||||
|
isBillingEnforced,
|
||||||
|
type PlanCatalogReader,
|
||||||
|
planCatalog,
|
||||||
|
toBillingChargeDto,
|
||||||
|
} from '@/modules/billing/lib';
|
||||||
import { accountPlan, toAccountListItem } from '../../lib';
|
import { accountPlan, toAccountListItem } from '../../lib';
|
||||||
|
|
||||||
const RECENT_CHARGES = 12;
|
const RECENT_CHARGES = 12;
|
||||||
@@ -13,6 +20,7 @@ type GetAccountDeps = {
|
|||||||
enforced?: boolean;
|
enforced?: boolean;
|
||||||
graceDays?: number;
|
graceDays?: number;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** One professor's account: plan, links, groups and the latest Pro charges. */
|
/** One professor's account: plan, links, groups and the latest Pro charges. */
|
||||||
@@ -65,18 +73,16 @@ export class GetAccount {
|
|||||||
const { graceUntil } = accountPlan(user, context);
|
const { graceUntil } = accountPlan(user, context);
|
||||||
const enforced = this.deps.enforced ?? isBillingEnforced();
|
const enforced = this.deps.enforced ?? isBillingEnforced();
|
||||||
const subscription = user.subscription;
|
const subscription = user.subscription;
|
||||||
|
// Same rule as the PlanGuard: an account without a plan is held to Free.
|
||||||
|
const limits = await (this.deps.catalog ?? planCatalog).getLimits(summary.plan ?? 'FREE');
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
...summary,
|
...summary,
|
||||||
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
|
planSelectedAt: user.planSelectedAt?.toISOString() ?? null,
|
||||||
graceUntil: graceUntil?.toISOString() ?? null,
|
graceUntil: graceUntil?.toISOString() ?? null,
|
||||||
// Same rule as the PlanGuard: an account without a plan is held to Free.
|
|
||||||
readOnly:
|
readOnly:
|
||||||
enforced
|
enforced && exceedsLimits(limits, { groups: usage.groupsCount, attendees: usage.attendeesCount }),
|
||||||
&& exceedsLimits(PLAN_LIMITS[summary.plan ?? 'FREE'], {
|
limits,
|
||||||
groups: usage.groupsCount,
|
|
||||||
attendees: usage.attendeesCount,
|
|
||||||
}),
|
|
||||||
subscription:
|
subscription:
|
||||||
summary.subscription && subscription
|
summary.subscription && subscription
|
||||||
? {
|
? {
|
||||||
|
|||||||
12
apps/backend/src/modules/admin/features/get-plans/route.ts
Normal file
12
apps/backend/src/modules/admin/features/get-plans/route.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { GetPlans } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get('/plans', async (c) => {
|
||||||
|
const result = await new GetPlans().execute();
|
||||||
|
return resultJson(c, result);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { AdminPlansDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { billingProviderForCountry, COUNTRY_CURRENCY, countryCodeSchema, ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { MAX_PRICE_CHANGE_ATTEMPTS } from '@/modules/billing/jobs';
|
||||||
|
import { type PlanCatalogReader, planCatalog } from '@/modules/billing/lib';
|
||||||
|
|
||||||
|
/** The subscriptions "apply to existing" moves: live, with a provider subscription. */
|
||||||
|
export const LIVE_SUBSCRIPTION_STATUSES = ['AUTHORIZED', 'PAUSED'] as const;
|
||||||
|
|
||||||
|
type GetPlansDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'planPrice' | 'billingSubscription'>;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Limits of both plans and, per country, the price of Pro and how it reached live subscriptions. */
|
||||||
|
export class GetPlans {
|
||||||
|
constructor(private readonly deps: GetPlansDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(): Promise<Result<AdminPlansDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const catalog = await (this.deps.catalog ?? planCatalog).snapshot();
|
||||||
|
|
||||||
|
const [priceRows, live] = await Promise.all([
|
||||||
|
db.planPrice.findMany({ select: { country: true, updatedAt: true } }),
|
||||||
|
db.billingSubscription.findMany({
|
||||||
|
where: { status: { in: [...LIVE_SUBSCRIPTION_STATUSES] }, externalId: { not: null } },
|
||||||
|
select: { country: true, amount: true, pendingAmount: true, priceChangeAttempts: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const updatedAt = new Map(priceRows.map((row) => [row.country, row.updatedAt]));
|
||||||
|
|
||||||
|
const prices = countryCodeSchema.options.map((country) => {
|
||||||
|
const amount = catalog.proPrices[country];
|
||||||
|
const rows = live.filter((row) => row.country === country);
|
||||||
|
const queued = rows.filter((row) => row.pendingAmount !== null);
|
||||||
|
const failed = queued.filter((row) => row.priceChangeAttempts >= MAX_PRICE_CHANGE_ATTEMPTS);
|
||||||
|
return {
|
||||||
|
country,
|
||||||
|
amount,
|
||||||
|
currency: COUNTRY_CURRENCY[country],
|
||||||
|
provider: billingProviderForCountry(country),
|
||||||
|
updatedAt: updatedAt.get(country)?.toISOString() ?? null,
|
||||||
|
liveSubscriptions: rows.length,
|
||||||
|
atOtherPrice: rows.filter(
|
||||||
|
(row) => Number((row.pendingAmount ?? row.amount).toString()) !== amount,
|
||||||
|
).length,
|
||||||
|
pendingChanges: queued.length - failed.length,
|
||||||
|
failedChanges: failed.length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return ok({ limits: catalog.limits, prices });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import type { PlanLimitsImpactQuery } from '@gruperly/shared';
|
||||||
|
import { PlanLimitsImpactQuerySchema, planSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { PlanLimitsImpact } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
route.get(
|
||||||
|
'/plans/:plan/impact',
|
||||||
|
validate.param(z.object({ plan: planSchema })),
|
||||||
|
validate.query(PlanLimitsImpactQuerySchema),
|
||||||
|
async (c) => {
|
||||||
|
const { plan } = c.req.valid('param');
|
||||||
|
const query = c.req.valid('query') as PlanLimitsImpactQuery;
|
||||||
|
const result = await new PlanLimitsImpact().execute(plan, query);
|
||||||
|
return resultJson(c, result);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { Plan, PlanLimitsImpactDto, PlanLimitsImpactQuery, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { getGraceDays, proSubscriptionWhere } from '@/modules/billing/lib';
|
||||||
|
|
||||||
|
type PlanLimitsImpactDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'group' | 'person' | 'user'>;
|
||||||
|
graceDays?: number;
|
||||||
|
now?: () => Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many accounts on a plan would exceed new limits, i.e. become read only
|
||||||
|
* as soon as they are saved (limits apply at once). Usage is the PlanGuard's:
|
||||||
|
* groups owned, and people with at least one ACTIVE membership.
|
||||||
|
*/
|
||||||
|
export class PlanLimitsImpact {
|
||||||
|
constructor(private readonly deps: PlanLimitsImpactDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(plan: Plan, query: PlanLimitsImpactQuery): Promise<Result<PlanLimitsImpactDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const now = this.deps.now?.() ?? new Date();
|
||||||
|
const graceDays = this.deps.graceDays ?? getGraceDays();
|
||||||
|
|
||||||
|
const [overGroups, overAttendees] = await Promise.all([
|
||||||
|
query.maxGroups === null
|
||||||
|
? []
|
||||||
|
: db.group.groupBy({
|
||||||
|
by: ['createdById'],
|
||||||
|
having: { id: { _count: { gt: query.maxGroups } } },
|
||||||
|
}),
|
||||||
|
query.maxAttendees === null
|
||||||
|
? []
|
||||||
|
: db.person.groupBy({
|
||||||
|
by: ['createdById'],
|
||||||
|
where: { attendees: { some: { status: 'ACTIVE' } } },
|
||||||
|
having: { id: { _count: { gt: query.maxAttendees } } },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const candidates = [...new Set([...overGroups, ...overAttendees].map((row) => row.createdById))];
|
||||||
|
if (candidates.length === 0) return ok({ affectedAccounts: 0 });
|
||||||
|
|
||||||
|
// Same split as the PlanGuard: anyone without a live Pro is held to Free.
|
||||||
|
const isPro: Prisma.UserWhereInput = { subscription: { is: proSubscriptionWhere(now, graceDays) } };
|
||||||
|
const affectedAccounts = await db.user.count({
|
||||||
|
where: { id: { in: candidates }, ...(plan === 'PRO' ? isPro : { NOT: isPro }) },
|
||||||
|
});
|
||||||
|
return ok({ affectedAccounts });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { UpdatePlanLimitsInput } from '@gruperly/shared';
|
||||||
|
import { planSchema, UpdatePlanLimitsInputSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { UpdatePlanLimits } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/plans/:plan/limits',
|
||||||
|
validate.param(z.object({ plan: planSchema })),
|
||||||
|
validate.json(UpdatePlanLimitsInputSchema),
|
||||||
|
async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const { plan } = c.req.valid('param');
|
||||||
|
const input = c.req.valid('json') as UpdatePlanLimitsInput;
|
||||||
|
const result = await new UpdatePlanLimits().execute(plan, input, user.id);
|
||||||
|
return resultJson(c, result);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { Plan, PlanLimits, ProblemDetails, Result, UpdatePlanLimitsInput } from '@gruperly/shared';
|
||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
|
||||||
|
|
||||||
|
type UpdatePlanLimitsDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'planConfig'>;
|
||||||
|
catalog?: Pick<PlanCatalog, 'invalidate'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** New limits for a plan. They apply at once to every account on it. */
|
||||||
|
export class UpdatePlanLimits {
|
||||||
|
constructor(private readonly deps: UpdatePlanLimitsDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
plan: Plan,
|
||||||
|
input: UpdatePlanLimitsInput,
|
||||||
|
adminId: string,
|
||||||
|
): Promise<Result<PlanLimits, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const data = { ...input, updatedById: adminId };
|
||||||
|
await db.planConfig.upsert({ where: { plan }, create: { plan, ...data }, update: data });
|
||||||
|
(this.deps.catalog ?? planCatalog).invalidate();
|
||||||
|
logger.info({ plan, adminId, limits: input }, 'Plan limits updated');
|
||||||
|
return ok(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { UpdatePlanPriceInput } from '@gruperly/shared';
|
||||||
|
import { countryCodeSchema, UpdatePlanPriceInputSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { BackendEnv } from '@/http/env';
|
||||||
|
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||||
|
import { validate } from '@/http/validate';
|
||||||
|
import { runPriceChanges } from '@/modules/billing/jobs';
|
||||||
|
import { UpdatePlanPrice } from './use-case';
|
||||||
|
|
||||||
|
const route = new Hono<BackendEnv>();
|
||||||
|
|
||||||
|
route.put(
|
||||||
|
'/plans/prices/:country',
|
||||||
|
validate.param(z.object({ country: countryCodeSchema })),
|
||||||
|
validate.json(UpdatePlanPriceInputSchema),
|
||||||
|
async (c) => {
|
||||||
|
const user = c.get('user');
|
||||||
|
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||||
|
const { country } = c.req.valid('param');
|
||||||
|
const input = c.req.valid('json') as UpdatePlanPriceInput;
|
||||||
|
const result = await new UpdatePlanPrice({ applyQueued: runPriceChanges }).execute(country, input, user.id);
|
||||||
|
return resultJson(c, result);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import type { CountryCode, ProblemDetails, Result, UpdatePlanPriceInput, UpdatePlanPriceResultDto } from '@gruperly/shared';
|
||||||
|
import { COUNTRY_CURRENCY, ok } from '@gruperly/shared';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { type PlanCatalog, planCatalog } from '@/modules/billing/lib';
|
||||||
|
import { LIVE_SUBSCRIPTION_STATUSES } from '../get-plans/use-case';
|
||||||
|
|
||||||
|
type UpdatePlanPriceDeps = {
|
||||||
|
db?: Pick<PrismaClient, '$transaction'>;
|
||||||
|
catalog?: Pick<PlanCatalog, 'invalidate' | 'getProPrice'>;
|
||||||
|
/** Kicks the job that pushes queued prices to the providers. */
|
||||||
|
applyQueued?: () => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* New monthly price of Pro in a country. New subscriptions take it right away.
|
||||||
|
* With `applyToExisting`, the country's live subscriptions are queued to move
|
||||||
|
* to it (`pending_amount`); the job tells each provider to charge it from the
|
||||||
|
* next charge on, and emails the professor.
|
||||||
|
*
|
||||||
|
* PENDING subscriptions are left alone: a checkout half done keeps its amount,
|
||||||
|
* and trying again starts a new one at the new price.
|
||||||
|
*/
|
||||||
|
export class UpdatePlanPrice {
|
||||||
|
constructor(private readonly deps: UpdatePlanPriceDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(
|
||||||
|
country: CountryCode,
|
||||||
|
input: UpdatePlanPriceInput,
|
||||||
|
adminId: string,
|
||||||
|
): Promise<Result<UpdatePlanPriceResultDto, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const catalog = this.deps.catalog ?? planCatalog;
|
||||||
|
catalog.invalidate();
|
||||||
|
const previousAmount = await catalog.getProPrice(country);
|
||||||
|
const currency = COUNTRY_CURRENCY[country];
|
||||||
|
|
||||||
|
const queued = await db.$transaction(async (tx) => {
|
||||||
|
await tx.planPrice.upsert({
|
||||||
|
where: { country },
|
||||||
|
create: { country, amount: input.amount, updatedById: adminId },
|
||||||
|
update: { amount: input.amount, updatedById: adminId },
|
||||||
|
});
|
||||||
|
const change = await tx.planPriceChange.create({
|
||||||
|
data: {
|
||||||
|
country,
|
||||||
|
previousAmount,
|
||||||
|
newAmount: input.amount,
|
||||||
|
currency,
|
||||||
|
applyToExisting: input.applyToExisting,
|
||||||
|
createdById: adminId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (!input.applyToExisting) return 0;
|
||||||
|
|
||||||
|
// Rows already at the new price (or already moving to it) are not touched.
|
||||||
|
const moved = await tx.billingSubscription.updateMany({
|
||||||
|
where: {
|
||||||
|
country,
|
||||||
|
status: { in: [...LIVE_SUBSCRIPTION_STATUSES] },
|
||||||
|
externalId: { not: null },
|
||||||
|
OR: [
|
||||||
|
{ pendingAmount: null, amount: { not: input.amount } },
|
||||||
|
{ pendingAmount: { not: null, notIn: [input.amount] } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
pendingAmount: input.amount,
|
||||||
|
priceChangeId: change.id,
|
||||||
|
priceChangeAttempts: 0,
|
||||||
|
priceChangeError: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await tx.planPriceChange.update({ where: { id: change.id }, data: { queued: moved.count } });
|
||||||
|
return moved.count;
|
||||||
|
});
|
||||||
|
|
||||||
|
catalog.invalidate();
|
||||||
|
logger.info({ country, adminId, amount: input.amount, queued }, 'Pro price updated');
|
||||||
|
|
||||||
|
if (queued > 0 && this.deps.applyQueued) {
|
||||||
|
// In the background: the providers are slow, and the cron retries anyway.
|
||||||
|
void this.deps.applyQueued();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok({ country, amount: input.amount, queued });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import getAccountRoute from './features/get-account/route';
|
import getAccountRoute from './features/get-account/route';
|
||||||
|
import getPlansRoute from './features/get-plans/route';
|
||||||
import listAccountsRoute from './features/list-accounts/route';
|
import listAccountsRoute from './features/list-accounts/route';
|
||||||
import meRoute from './features/me/route';
|
import meRoute from './features/me/route';
|
||||||
|
import planLimitsImpactRoute from './features/plan-limits-impact/route';
|
||||||
|
import updatePlanLimitsRoute from './features/update-plan-limits/route';
|
||||||
|
import updatePlanPriceRoute from './features/update-plan-price/route';
|
||||||
import { adminOnlyMiddleware } from './lib';
|
import { adminOnlyMiddleware } from './lib';
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
@@ -11,7 +15,13 @@ routes.route('/', meRoute);
|
|||||||
// Everything below `/me` is the backoffice itself.
|
// Everything below `/me` is the backoffice itself.
|
||||||
routes.use('/accounts', adminOnlyMiddleware());
|
routes.use('/accounts', adminOnlyMiddleware());
|
||||||
routes.use('/accounts/*', adminOnlyMiddleware());
|
routes.use('/accounts/*', adminOnlyMiddleware());
|
||||||
|
routes.use('/plans', adminOnlyMiddleware());
|
||||||
|
routes.use('/plans/*', adminOnlyMiddleware());
|
||||||
routes.route('/', listAccountsRoute);
|
routes.route('/', listAccountsRoute);
|
||||||
routes.route('/', getAccountRoute);
|
routes.route('/', getAccountRoute);
|
||||||
|
routes.route('/', getPlansRoute);
|
||||||
|
routes.route('/', planLimitsImpactRoute);
|
||||||
|
routes.route('/', updatePlanLimitsRoute);
|
||||||
|
routes.route('/', updatePlanPriceRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
|
|||||||
16
apps/backend/src/modules/billing/features/plans/route.ts
Normal file
16
apps/backend/src/modules/billing/features/plans/route.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { ok } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { resultJson } from '@/http/problem-details';
|
||||||
|
import { planCatalog, toPlanCatalogDto } from '../../lib';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What each plan allows and what Pro costs in every country. The onboarding
|
||||||
|
* asks before the professor's country is stored, so it gets all of them.
|
||||||
|
*/
|
||||||
|
route.get('/plans', async (c) => {
|
||||||
|
return resultJson(c, ok(toPlanCatalogDto(await planCatalog.snapshot())));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
19
apps/backend/src/modules/billing/features/return/route.ts
Normal file
19
apps/backend/src/modules/billing/features/return/route.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { billingReturnToSchema } from '@gruperly/shared';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { getWebOrigin } from '@/modules/mp/lib';
|
||||||
|
import { buildSubscriptionReturnUrl } from '../../lib';
|
||||||
|
|
||||||
|
const route = new Hono();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `back_url` of the Pro checkout (Mercado Pago and Stripe). Public: the
|
||||||
|
* browser comes from the provider, maybe through a tunnel without the session
|
||||||
|
* cookie. It only redirects to a fixed page of the web, so whatever the
|
||||||
|
* provider appends to the query is dropped and nothing can steer the redirect.
|
||||||
|
*/
|
||||||
|
route.get('/return', (c) => {
|
||||||
|
const parsed = billingReturnToSchema.safeParse(c.req.query('to'));
|
||||||
|
return c.redirect(buildSubscriptionReturnUrl(getWebOrigin(), parsed.success ? parsed.data : 'billing'));
|
||||||
|
});
|
||||||
|
|
||||||
|
export default route;
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
import type { BillingStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
|
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
|
||||||
import { notFoundResourceProblem } from '@/http/problem-builders';
|
import { notFoundResourceProblem } from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { countryOf, PlanGuard, SyncSubscription } from '../../lib';
|
import { countryOf, type PlanCatalogReader, PlanGuard, planCatalog, SyncSubscription } from '../../lib';
|
||||||
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
|
import { type BillingProviderResolver, getBillingProvider } from '../../providers';
|
||||||
|
|
||||||
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
|
/** A PENDING subscription is re-read from Mercado Pago at most this often. */
|
||||||
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
|
const PENDING_SYNC_INTERVAL_MS = 30 * 1000;
|
||||||
|
|
||||||
type GetBillingStatusDeps = {
|
type GetBillingStatusDeps = {
|
||||||
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
db?: Pick<PrismaClient, 'user' | 'billingSubscription' | 'billingCharge'>;
|
||||||
guard?: PlanGuard;
|
guard?: PlanGuard;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
sync?: Pick<SyncSubscription, 'execute'>;
|
sync?: Pick<SyncSubscription, 'execute'>;
|
||||||
providers?: BillingProviderResolver;
|
providers?: BillingProviderResolver;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
@@ -54,6 +55,24 @@ export class GetBillingStatus {
|
|||||||
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
|
live && live.status !== 'PENDING' ? live.provider : billingProviderForCountry(country),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const priceAmount = live
|
||||||
|
? Number(live.amount.toString())
|
||||||
|
: await (this.deps.catalog ?? planCatalog).getProPrice(country);
|
||||||
|
|
||||||
|
// A price change from the backoffice applies from the next charge: show it
|
||||||
|
// while it is queued, and after it reached the provider until it is charged.
|
||||||
|
let nextPriceAmount: number | null = null;
|
||||||
|
if (live?.pendingAmount) {
|
||||||
|
nextPriceAmount = Number(live.pendingAmount.toString());
|
||||||
|
} else if (live?.status === 'AUTHORIZED') {
|
||||||
|
const lastCharge = await db.billingCharge.findFirst({
|
||||||
|
where: { subscriptionId: live.id, status: 'approved' },
|
||||||
|
orderBy: { paidAt: 'desc' },
|
||||||
|
select: { amount: true },
|
||||||
|
});
|
||||||
|
if (lastCharge && Number(lastCharge.amount.toString()) !== priceAmount) nextPriceAmount = priceAmount;
|
||||||
|
}
|
||||||
|
|
||||||
return ok({
|
return ok({
|
||||||
plan: entitlements.plan,
|
plan: entitlements.plan,
|
||||||
status: subscription?.status ?? null,
|
status: subscription?.status ?? null,
|
||||||
@@ -65,7 +84,8 @@ export class GetBillingStatus {
|
|||||||
? (subscription.nextPaymentDate?.toISOString() ?? null)
|
? (subscription.nextPaymentDate?.toISOString() ?? null)
|
||||||
: null,
|
: null,
|
||||||
payerEmail: subscription?.payerEmail ?? null,
|
payerEmail: subscription?.payerEmail ?? null,
|
||||||
priceAmount: live ? Number(live.amount.toString()) : PRO_PRICE_BY_COUNTRY[country],
|
priceAmount,
|
||||||
|
nextPriceAmount,
|
||||||
currency: live ? live.currency : COUNTRY_CURRENCY[country],
|
currency: live ? live.currency : COUNTRY_CURRENCY[country],
|
||||||
country,
|
country,
|
||||||
provider: provider.id,
|
provider: provider.id,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { PrismaClient } from '@generated/prisma/client';
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
|
import type { ProblemDetails, Result, SubscribeInput, SubscribeResultDto } from '@gruperly/shared';
|
||||||
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared';
|
import { billingProviderForCountry, COUNTRY_CURRENCY, err, ok } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
billingNotAvailableProblem,
|
billingNotAvailableProblem,
|
||||||
notFoundResourceProblem,
|
notFoundResourceProblem,
|
||||||
@@ -9,15 +9,20 @@ import {
|
|||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { getWebOrigin } from '@/modules/mp/lib';
|
import {
|
||||||
import { buildSubscriptionBackUrl, countryOf, subscriptionRefOf } from '../../lib';
|
buildSubscriptionBackUrl,
|
||||||
|
countryOf,
|
||||||
|
getApiPublicOrigin,
|
||||||
|
type PlanCatalogReader, planCatalog, subscriptionRefOf } from '../../lib';
|
||||||
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
|
import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers';
|
||||||
|
|
||||||
type SubscribeDeps = {
|
type SubscribeDeps = {
|
||||||
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
db?: Pick<PrismaClient, 'user' | 'billingSubscription'>;
|
||||||
providers?: BillingProviderResolver;
|
providers?: BillingProviderResolver;
|
||||||
webOrigin?: string;
|
/** Public origin of the API, where the provider sends the browser back. */
|
||||||
|
apiOrigin?: string;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -60,7 +65,7 @@ export class Subscribe {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const amount = PRO_PRICE_BY_COUNTRY[country];
|
const amount = await (this.deps.catalog ?? planCatalog).getProPrice(country);
|
||||||
const currency = COUNTRY_CURRENCY[country];
|
const currency = COUNTRY_CURRENCY[country];
|
||||||
const fields = {
|
const fields = {
|
||||||
country,
|
country,
|
||||||
@@ -82,6 +87,10 @@ export class Subscribe {
|
|||||||
checkoutRef: null,
|
checkoutRef: null,
|
||||||
authorizedAt: null,
|
authorizedAt: null,
|
||||||
nextPaymentDate: null,
|
nextPaymentDate: null,
|
||||||
|
pendingAmount: null,
|
||||||
|
priceChangeId: null,
|
||||||
|
priceChangeAttempts: 0,
|
||||||
|
priceChangeError: null,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -97,7 +106,7 @@ export class Subscribe {
|
|||||||
amount,
|
amount,
|
||||||
currency,
|
currency,
|
||||||
payerEmail: input.payerEmail ?? null,
|
payerEmail: input.payerEmail ?? null,
|
||||||
backUrl: buildSubscriptionBackUrl(this.deps.webOrigin ?? getWebOrigin(), input.returnTo),
|
backUrl: buildSubscriptionBackUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), input.returnTo),
|
||||||
startDate,
|
startDate,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
117
apps/backend/src/modules/billing/jobs/apply-price-changes.ts
Normal file
117
apps/backend/src/modules/billing/jobs/apply-price-changes.ts
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { COUNTRY_TIME_ZONES } from '@gruperly/shared';
|
||||||
|
import type { EmailProvider } from '@/lib/email';
|
||||||
|
import { emailProvider } from '@/lib/email';
|
||||||
|
import prisma from '@/lib/prisma';
|
||||||
|
import { logger } from '@/logger';
|
||||||
|
import { getWebOrigin } from '@/modules/mp/lib';
|
||||||
|
import { formatAmount } from '@/modules/whatsapp/lib/format';
|
||||||
|
import { countryOf } from '../lib';
|
||||||
|
import {
|
||||||
|
BillingProviderNotConfigured,
|
||||||
|
type BillingProviderResolver,
|
||||||
|
getBillingProvider,
|
||||||
|
} from '../providers';
|
||||||
|
|
||||||
|
const BATCH_SIZE = 20;
|
||||||
|
/** After this many refusals the change stays visible as failed in the backoffice. */
|
||||||
|
export const MAX_PRICE_CHANGE_ATTEMPTS = 5;
|
||||||
|
|
||||||
|
type ApplyPriceChangesDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'billingSubscription'>;
|
||||||
|
providers?: BillingProviderResolver;
|
||||||
|
email?: Pick<EmailProvider, 'sendProPriceChanged'>;
|
||||||
|
webOrigin?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ApplyPriceChangesTotals = { applied: number; failed: number; dropped: number };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pushes the prices the backoffice queued (`pending_amount`) to each live
|
||||||
|
* subscription's provider, from its next charge on, and tells the professor.
|
||||||
|
*
|
||||||
|
* The provider call is idempotent (it sets an amount), so two instances racing
|
||||||
|
* over a row are harmless: only the one whose conditional update moves
|
||||||
|
* `pending_amount` into `amount` sends the email.
|
||||||
|
*/
|
||||||
|
export class ApplyPriceChanges {
|
||||||
|
constructor(private readonly deps: ApplyPriceChangesDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(): Promise<ApplyPriceChangesTotals> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const providers = this.deps.providers ?? getBillingProvider;
|
||||||
|
const totals: ApplyPriceChangesTotals = { applied: 0, failed: 0, dropped: 0 };
|
||||||
|
|
||||||
|
const rows = await db.billingSubscription.findMany({
|
||||||
|
where: { pendingAmount: { not: null }, priceChangeAttempts: { lt: MAX_PRICE_CHANGE_ATTEMPTS } },
|
||||||
|
include: { user: { select: { name: true, email: true, country: true } } },
|
||||||
|
orderBy: { updatedAt: 'asc' },
|
||||||
|
take: BATCH_SIZE,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const pendingAmount = row.pendingAmount;
|
||||||
|
if (!pendingAmount) continue;
|
||||||
|
const unchanged = { id: row.id, pendingAmount };
|
||||||
|
|
||||||
|
// Cancelled (or never completed) meanwhile: nothing left to reprice.
|
||||||
|
if (row.status === 'CANCELLED' || row.status === 'PENDING' || !row.externalId) {
|
||||||
|
await db.billingSubscription.updateMany({
|
||||||
|
where: unchanged,
|
||||||
|
data: { pendingAmount: null, priceChangeId: null, priceChangeAttempts: 0, priceChangeError: null },
|
||||||
|
});
|
||||||
|
totals.dropped += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const amount = Number(pendingAmount.toString());
|
||||||
|
const country = countryOf({ country: row.country });
|
||||||
|
try {
|
||||||
|
await providers(row.provider).updateAmount(
|
||||||
|
{ country, externalId: row.externalId, checkoutRef: row.checkoutRef },
|
||||||
|
amount,
|
||||||
|
row.currency,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
// Never the provider's message: it can echo what we sent.
|
||||||
|
const reason = error instanceof BillingProviderNotConfigured ? 'not_configured' : 'provider_error';
|
||||||
|
logger.warn({ subscriptionId: row.id, provider: row.provider, reason }, 'Could not apply a Pro price change');
|
||||||
|
await db.billingSubscription.updateMany({
|
||||||
|
where: unchanged,
|
||||||
|
data: { priceChangeAttempts: { increment: 1 }, priceChangeError: reason },
|
||||||
|
});
|
||||||
|
totals.failed += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const moved = await db.billingSubscription.updateMany({
|
||||||
|
where: unchanged,
|
||||||
|
data: { amount: pendingAmount, pendingAmount: null, priceChangeAttempts: 0, priceChangeError: null },
|
||||||
|
});
|
||||||
|
if (moved.count !== 1) continue;
|
||||||
|
totals.applied += 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await (this.deps.email ?? emailProvider).sendProPriceChanged({
|
||||||
|
email: row.user.email,
|
||||||
|
name: row.user.name,
|
||||||
|
amount: formatAmount(amount, row.currency, country),
|
||||||
|
nextPaymentDate: row.nextPaymentDate
|
||||||
|
? new Intl.DateTimeFormat('es-AR', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
year: 'numeric',
|
||||||
|
timeZone: COUNTRY_TIME_ZONES[country],
|
||||||
|
}).format(row.nextPaymentDate)
|
||||||
|
: null,
|
||||||
|
billingUrl: `${this.deps.webOrigin ?? getWebOrigin()}/billing`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// The price already changed; a lost email is not worth a retry loop.
|
||||||
|
logger.warn({ err: error, subscriptionId: row.id }, 'Could not email a Pro price change');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return totals;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
|
export { ApplyPriceChanges, type ApplyPriceChangesTotals, MAX_PRICE_CHANGE_ATTEMPTS } from './apply-price-changes';
|
||||||
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
|
export { ReconcileSubscriptions, type ReconcileTotals } from './reconcile-subscriptions';
|
||||||
export { startBillingJobs } from './schedule';
|
export { runPriceChanges, startBillingJobs } from './schedule';
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
|
import { ApplyPriceChanges } from './apply-price-changes';
|
||||||
import { ReconcileSubscriptions } from './reconcile-subscriptions';
|
import { ReconcileSubscriptions } from './reconcile-subscriptions';
|
||||||
|
|
||||||
const RECONCILE_CRON = '*/30 * * * *';
|
const RECONCILE_CRON = '*/30 * * * *';
|
||||||
|
const PRICE_CHANGES_CRON = '*/5 * * * *';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Registers the billing background jobs. Called once from `server.ts`, with the
|
* Registers the billing background jobs. Called once from `server.ts`, with the
|
||||||
@@ -21,4 +23,27 @@ export function startBillingJobs(): void {
|
|||||||
},
|
},
|
||||||
{ tz: 'UTC' },
|
{ tz: 'UTC' },
|
||||||
).unref();
|
).unref();
|
||||||
|
|
||||||
|
Bun.cron(
|
||||||
|
PRICE_CHANGES_CRON,
|
||||||
|
async () => {
|
||||||
|
await runPriceChanges();
|
||||||
|
},
|
||||||
|
{ tz: 'UTC' },
|
||||||
|
).unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies the Pro price changes queued by the backoffice. Also called right
|
||||||
|
* after a save, so the change does not wait for the next tick. Never throws.
|
||||||
|
*/
|
||||||
|
export async function runPriceChanges(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const totals = await new ApplyPriceChanges().execute();
|
||||||
|
if (totals.applied + totals.failed + totals.dropped > 0) {
|
||||||
|
logger.info(totals, 'Pro price changes applied');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error({ err: error }, 'Applying Pro price changes failed');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
108
apps/backend/src/modules/billing/lib/catalog.ts
Normal file
108
apps/backend/src/modules/billing/lib/catalog.ts
Normal file
@@ -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<Plan, PlanLimits>;
|
||||||
|
/** Monthly price of Pro, in the currency of each country. */
|
||||||
|
proPrices: Record<CountryCode, number>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function defaultPlanCatalog(): PlanCatalogSnapshot {
|
||||||
|
return {
|
||||||
|
limits: { FREE: { ...PLAN_LIMITS.FREE }, PRO: { ...PLAN_LIMITS.PRO } },
|
||||||
|
proPrices: { ...PRO_PRICE_BY_COUNTRY },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type PlanCatalogDeps = {
|
||||||
|
db?: Pick<PrismaClient, 'planConfig' | 'planPrice'>;
|
||||||
|
ttlMs?: number;
|
||||||
|
now?: () => number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What each plan allows and what Pro costs, as edited from the backoffice
|
||||||
|
* (`plan_configs`, `plan_prices`). A missing row falls back to the defaults in
|
||||||
|
* shared (`PLAN_LIMITS`, `PRO_PRICE_BY_COUNTRY`), which also seed the tables.
|
||||||
|
*
|
||||||
|
* Cached in memory for a few seconds; the backoffice invalidates it on save, so
|
||||||
|
* the instance that saved sees the change at once and the others within the TTL.
|
||||||
|
*/
|
||||||
|
export class PlanCatalog {
|
||||||
|
private cached: { snapshot: PlanCatalogSnapshot; at: number } | null = null;
|
||||||
|
|
||||||
|
constructor(private readonly deps: PlanCatalogDeps = {}) {}
|
||||||
|
|
||||||
|
invalidate(): void {
|
||||||
|
this.cached = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async snapshot(): Promise<PlanCatalogSnapshot> {
|
||||||
|
const now = this.deps.now?.() ?? Date.now();
|
||||||
|
const ttl = this.deps.ttlMs ?? CACHE_TTL_MS;
|
||||||
|
if (this.cached && now - this.cached.at < ttl) return this.cached.snapshot;
|
||||||
|
|
||||||
|
const snapshot = defaultPlanCatalog();
|
||||||
|
try {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
const [configs, prices] = await Promise.all([db.planConfig.findMany(), db.planPrice.findMany()]);
|
||||||
|
for (const config of configs) {
|
||||||
|
snapshot.limits[config.plan] = {
|
||||||
|
maxGroups: config.maxGroups,
|
||||||
|
maxAttendees: config.maxAttendees,
|
||||||
|
whatsappAutomations: config.whatsappAutomations,
|
||||||
|
mpCharges: config.mpCharges,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for (const price of prices) {
|
||||||
|
const country = countryCodeSchema.safeParse(price.country);
|
||||||
|
if (country.success) snapshot.proPrices[country.data] = Number(price.amount.toString());
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// The defaults keep the guards working; not cached, so the next call retries.
|
||||||
|
logger.warn({ err: error }, 'Could not read the plan catalog, using the defaults');
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cached = { snapshot, at: now };
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLimits(plan: Plan): Promise<PlanLimits> {
|
||||||
|
return (await this.snapshot()).limits[plan];
|
||||||
|
}
|
||||||
|
|
||||||
|
async getProPrice(country: CountryCode): Promise<number> {
|
||||||
|
return (await this.snapshot()).proPrices[country];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The catalog every use-case shares, so an invalidation reaches all of them. */
|
||||||
|
export const planCatalog = new PlanCatalog();
|
||||||
|
|
||||||
|
/** A fixed catalog, for tests and callers that already hold a snapshot. */
|
||||||
|
export function staticPlanCatalog(snapshot: PlanCatalogSnapshot = defaultPlanCatalog()): PlanCatalogReader {
|
||||||
|
return {
|
||||||
|
snapshot: async () => snapshot,
|
||||||
|
getLimits: async (plan) => snapshot.limits[plan],
|
||||||
|
getProPrice: async (country) => snapshot.proPrices[country],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PlanCatalogReader = Pick<PlanCatalog, 'snapshot' | 'getLimits' | 'getProPrice'>;
|
||||||
|
|
||||||
|
export function toPlanCatalogDto(snapshot: PlanCatalogSnapshot): PlanCatalogDto {
|
||||||
|
const proPrices = Object.fromEntries(
|
||||||
|
countryCodeSchema.options.map((country) => [
|
||||||
|
country,
|
||||||
|
{ amount: snapshot.proPrices[country], currency: COUNTRY_CURRENCY[country] },
|
||||||
|
]),
|
||||||
|
) as PlanCatalogDto['proPrices'];
|
||||||
|
return { limits: snapshot.limits, proPrices };
|
||||||
|
}
|
||||||
@@ -14,3 +14,5 @@ export function getGraceDays(env: Record<string, string | undefined> = process.e
|
|||||||
const value = Number(env.BILLING_GRACE_DAYS);
|
const value = Number(env.BILLING_GRACE_DAYS);
|
||||||
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
|
return Number.isInteger(value) && value >= 0 ? value : DEFAULT_GRACE_DAYS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export { getApiPublicOrigin } from '@/lib/public-origin';
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
import type { Prisma, PrismaClient, SubscriptionStatus } from '@generated/prisma/client';
|
||||||
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
|
import type { Plan, PlanFeature, PlanLimits, ProblemDetails, Result } from '@gruperly/shared';
|
||||||
import { err, ok, PLAN_LIMITS } from '@gruperly/shared';
|
import { err, ok } from '@gruperly/shared';
|
||||||
import {
|
import {
|
||||||
planFeatureRequiredProblem,
|
planFeatureRequiredProblem,
|
||||||
planLimitReachedProblem,
|
planLimitReachedProblem,
|
||||||
planReadOnlyProblem,
|
planReadOnlyProblem,
|
||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { type PlanCatalogReader, planCatalog } from './catalog';
|
||||||
import { getGraceDays, isBillingEnforced } from './config';
|
import { getGraceDays, isBillingEnforced } from './config';
|
||||||
|
|
||||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||||
@@ -90,6 +91,7 @@ type PlanGuardDeps = {
|
|||||||
enforced?: boolean;
|
enforced?: boolean;
|
||||||
graceDays?: number;
|
graceDays?: number;
|
||||||
now?: () => Date;
|
now?: () => Date;
|
||||||
|
catalog?: PlanCatalogReader;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -123,7 +125,7 @@ export class PlanGuard {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
const resolution = resolvePlan(subscription, now, this.deps.graceDays ?? getGraceDays());
|
||||||
const limits = PLAN_LIMITS[resolution.plan];
|
const limits = await (this.deps.catalog ?? planCatalog).getLimits(resolution.plan);
|
||||||
const usage = { groups, attendees };
|
const usage = { groups, attendees };
|
||||||
const enforced = this.enforced;
|
const enforced = this.enforced;
|
||||||
|
|
||||||
|
|||||||
@@ -19,8 +19,18 @@ export function countryOf(user: { country: string | null } | null): CountryCode
|
|||||||
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
|
return parsed.success ? parsed.data : DEFAULT_COUNTRY;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Where the billing provider sends the professor after authorizing (or abandoning). */
|
/**
|
||||||
export function buildSubscriptionBackUrl(webOrigin: string, returnTo: BillingReturnTo): string {
|
* Where the billing provider sends the professor after authorizing (or
|
||||||
|
* abandoning): a public API route that bounces to the web
|
||||||
|
* (`GET /billing/return`), because Mercado Pago refuses a `back_url` on
|
||||||
|
* localhost and the web is not tunneled in local development.
|
||||||
|
*/
|
||||||
|
export function buildSubscriptionBackUrl(apiOrigin: string, returnTo: BillingReturnTo): string {
|
||||||
|
return `${apiOrigin}/api/v1/billing/return?to=${returnTo}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The web page the professor lands on after the provider's checkout. */
|
||||||
|
export function buildSubscriptionReturnUrl(webOrigin: string, returnTo: BillingReturnTo): string {
|
||||||
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
|
return `${webOrigin}/${returnTo === 'onboarding' ? 'onboarding' : 'billing'}?sub=return`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
export { getGraceDays, isBillingEnforced } from './config';
|
export {
|
||||||
|
defaultPlanCatalog,
|
||||||
|
PlanCatalog,
|
||||||
|
type PlanCatalogReader,
|
||||||
|
type PlanCatalogSnapshot,
|
||||||
|
planCatalog,
|
||||||
|
staticPlanCatalog,
|
||||||
|
toPlanCatalogDto,
|
||||||
|
} from './catalog';
|
||||||
|
export { getApiPublicOrigin, getGraceDays, isBillingEnforced } from './config';
|
||||||
export {
|
export {
|
||||||
type Entitlements,
|
type Entitlements,
|
||||||
exceedsLimits,
|
exceedsLimits,
|
||||||
@@ -9,5 +18,5 @@ export {
|
|||||||
resolvePlan,
|
resolvePlan,
|
||||||
type SubscriptionSnapshot,
|
type SubscriptionSnapshot,
|
||||||
} from './entitlements';
|
} from './entitlements';
|
||||||
export { buildSubscriptionBackUrl, countryOf, toBillingChargeDto } from './helpers';
|
export { buildSubscriptionBackUrl, buildSubscriptionReturnUrl, countryOf, toBillingChargeDto } from './helpers';
|
||||||
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';
|
export { SyncSubscription, type SyncSubscriptionDeps, subscriptionRefOf } from './sync';
|
||||||
|
|||||||
@@ -105,6 +105,8 @@ export interface BillingProvider {
|
|||||||
/** `null` while the professor has not completed the checkout. */
|
/** `null` while the professor has not completed the checkout. */
|
||||||
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
|
fetch(ref: SubscriptionRef): Promise<ProviderSubscription | null>;
|
||||||
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
|
listCharges(ref: SubscriptionRef & { externalId: string }): Promise<ProviderCharge[]>;
|
||||||
|
/** New monthly amount from the next charge on; what was already charged stays. */
|
||||||
|
updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void>;
|
||||||
/** Stops the monthly charge, or voids a checkout never completed. */
|
/** Stops the monthly charge, or voids a checkout never completed. */
|
||||||
cancel(ref: SubscriptionRef): Promise<void>;
|
cancel(ref: SubscriptionRef): Promise<void>;
|
||||||
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;
|
parseWebhook(request: BillingWebhookRequest): Promise<Result<BillingWebhookHint, BillingWebhookFailure>>;
|
||||||
|
|||||||
@@ -137,6 +137,13 @@ export class MercadoPagoBillingProvider implements BillingProvider {
|
|||||||
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
|
await this.client.cancelPreapproval(this.tokenFor(ref.country), ref.externalId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
|
||||||
|
await this.client.updatePreapprovalAmount(this.tokenFor(ref.country), ref.externalId, {
|
||||||
|
amount,
|
||||||
|
currencyId: currency,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One URL per country, because each country is a different Gruperly account
|
* One URL per country, because each country is a different Gruperly account
|
||||||
* with its own secret. Mercado Pago signs a manifest of the notified id, the
|
* with its own secret. Mercado Pago signs a manifest of the notified id, the
|
||||||
|
|||||||
@@ -129,6 +129,23 @@ export async function cancelPreapproval(accessToken: string, id: string): Promis
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Changes the monthly amount of a live preapproval. Mercado Pago applies it to
|
||||||
|
* the debits that follow; the ones already made are untouched.
|
||||||
|
*/
|
||||||
|
export async function updatePreapprovalAmount(
|
||||||
|
accessToken: string,
|
||||||
|
id: string,
|
||||||
|
input: { amount: number; currencyId: string },
|
||||||
|
): Promise<MpPreapproval> {
|
||||||
|
return toPreapproval(
|
||||||
|
await request(accessToken, `/preapproval/${encodeURIComponent(id)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: { auto_recurring: { transaction_amount: input.amount, currency_id: input.currencyId } },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
|
function toAuthorizedPayment(payload: Record<string, unknown>): MpAuthorizedPayment {
|
||||||
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
|
const payment = (payload.payment ?? null) as Record<string, unknown> | null;
|
||||||
return {
|
return {
|
||||||
@@ -181,6 +198,7 @@ export type PreapprovalClient = {
|
|||||||
createPreapproval: typeof createPreapproval;
|
createPreapproval: typeof createPreapproval;
|
||||||
getPreapproval: typeof getPreapproval;
|
getPreapproval: typeof getPreapproval;
|
||||||
cancelPreapproval: typeof cancelPreapproval;
|
cancelPreapproval: typeof cancelPreapproval;
|
||||||
|
updatePreapprovalAmount: typeof updatePreapprovalAmount;
|
||||||
getAuthorizedPayment: typeof getAuthorizedPayment;
|
getAuthorizedPayment: typeof getAuthorizedPayment;
|
||||||
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
searchAuthorizedPayments: typeof searchAuthorizedPayments;
|
||||||
};
|
};
|
||||||
@@ -189,6 +207,7 @@ export const mpPreapprovalClient: PreapprovalClient = {
|
|||||||
createPreapproval,
|
createPreapproval,
|
||||||
getPreapproval,
|
getPreapproval,
|
||||||
cancelPreapproval,
|
cancelPreapproval,
|
||||||
|
updatePreapprovalAmount,
|
||||||
getAuthorizedPayment,
|
getAuthorizedPayment,
|
||||||
searchAuthorizedPayments,
|
searchAuthorizedPayments,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -214,6 +214,39 @@ export class StripeBillingProvider implements BillingProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the subscription to a new monthly amount from its next invoice on:
|
||||||
|
* the item gets a new inline price on the same product, without proration,
|
||||||
|
* so the period already paid is not touched.
|
||||||
|
*/
|
||||||
|
async updateAmount(ref: SubscriptionRef & { externalId: string }, amount: number, currency: string): Promise<void> {
|
||||||
|
const request = this.request;
|
||||||
|
const path = `/subscriptions/${encodeURIComponent(ref.externalId)}`;
|
||||||
|
const subscription = await request(path);
|
||||||
|
const item = objectOf((objectOf(subscription.items)?.data as unknown[] | undefined)?.[0]);
|
||||||
|
const itemId = idOf(item?.id);
|
||||||
|
const product = idOf(objectOf(item?.price)?.product);
|
||||||
|
if (!itemId || !product) throw new Error('Stripe subscription came back without its item');
|
||||||
|
|
||||||
|
await request(path, {
|
||||||
|
method: 'POST',
|
||||||
|
form: {
|
||||||
|
proration_behavior: 'none',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: itemId,
|
||||||
|
price_data: {
|
||||||
|
currency: currency.toLowerCase(),
|
||||||
|
unit_amount: toStripeUnitAmount(amount, currency),
|
||||||
|
recurring: { interval: 'month' },
|
||||||
|
product,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** A single endpoint for the whole account; the event id is the dedupe key. */
|
/** A single endpoint for the whole account; the event id is the dedupe key. */
|
||||||
async parseWebhook(
|
async parseWebhook(
|
||||||
request: BillingWebhookRequest,
|
request: BillingWebhookRequest,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import cancelRoute from './features/cancel/route';
|
import cancelRoute from './features/cancel/route';
|
||||||
import chargesRoute from './features/charges/route';
|
import chargesRoute from './features/charges/route';
|
||||||
|
import plansRoute from './features/plans/route';
|
||||||
|
import returnRoute from './features/return/route';
|
||||||
import statusRoute from './features/status/route';
|
import statusRoute from './features/status/route';
|
||||||
import subscribeRoute from './features/subscribe/route';
|
import subscribeRoute from './features/subscribe/route';
|
||||||
import webhookRoute from './features/webhook/route';
|
import webhookRoute from './features/webhook/route';
|
||||||
@@ -11,6 +13,8 @@ routes.route('/', statusRoute);
|
|||||||
routes.route('/', subscribeRoute);
|
routes.route('/', subscribeRoute);
|
||||||
routes.route('/', cancelRoute);
|
routes.route('/', cancelRoute);
|
||||||
routes.route('/', chargesRoute);
|
routes.route('/', chargesRoute);
|
||||||
|
routes.route('/', plansRoute);
|
||||||
|
routes.route('/', returnRoute);
|
||||||
routes.route('/', webhookRoute);
|
routes.route('/', webhookRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
|
|||||||
@@ -25,8 +25,14 @@ route.get('/', validate.query(MpCallbackQuerySchema), async (c) => {
|
|||||||
return c.redirect(new URL('/login', getWebOrigin()).toString());
|
return c.redirect(new URL('/login', getWebOrigin()).toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
const useCase = new CompleteMpAuthorization();
|
let result: Awaited<ReturnType<CompleteMpAuthorization['execute']>>;
|
||||||
const result = await useCase.execute({ code, state, error });
|
try {
|
||||||
|
result = await new CompleteMpAuthorization().execute({ code, state, error, userId: user.id });
|
||||||
|
} catch (unexpected) {
|
||||||
|
// A broken deployment (e.g. TOKEN_ENCRYPTION_KEY) still lands back in the app.
|
||||||
|
logger.error({ err: unexpected }, 'Mercado Pago callback crashed');
|
||||||
|
return c.redirect(buildMpReturnUrl(getWebOrigin(), 'settings', { kind: 'error', reason: 'mp_error' }));
|
||||||
|
}
|
||||||
|
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ export class CompleteMpAuthorization {
|
|||||||
code?: string;
|
code?: string;
|
||||||
state?: string;
|
state?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
|
/** The signed-in teacher; has to be the one who started the flow. */
|
||||||
|
userId: string;
|
||||||
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
|
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
|
||||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||||
try {
|
try {
|
||||||
@@ -70,6 +72,14 @@ export class CompleteMpAuthorization {
|
|||||||
|
|
||||||
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
|
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
|
||||||
|
|
||||||
|
// A state started by someone else (a link sent to this teacher) would attach
|
||||||
|
// this teacher's Mercado Pago account to the other account. Not burned: it
|
||||||
|
// is not this session's to spend.
|
||||||
|
if (stored.ownerId !== input.userId) {
|
||||||
|
logger.warn('Mercado Pago callback with a state from another account');
|
||||||
|
return failure('invalid_state', returnTo);
|
||||||
|
}
|
||||||
|
|
||||||
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
|
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
|
||||||
// means someone replayed a state we already consumed.
|
// means someone replayed a state we already consumed.
|
||||||
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
||||||
|
|||||||
39
apps/backend/src/modules/mp/lib/callback-origin.ts
Normal file
39
apps/backend/src/modules/mp/lib/callback-origin.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import type { MiddlewareHandler } from 'hono';
|
||||||
|
|
||||||
|
type Env = Record<string, string | undefined>;
|
||||||
|
|
||||||
|
function hostOf(value: string | undefined): string | null {
|
||||||
|
if (!value?.trim()) return null;
|
||||||
|
try {
|
||||||
|
return new URL(value.trim()).host;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a callback that arrived through the public tunnel has to be replayed,
|
||||||
|
* or `null` when it is already on the origin that holds the session.
|
||||||
|
*
|
||||||
|
* In local development Mercado Pago only accepts an HTTPS Redirect URL, so it
|
||||||
|
* comes back through ngrok, while the session cookie belongs to the API on
|
||||||
|
* localhost (`BETTER_AUTH_URL`). In production both are the same host and this
|
||||||
|
* never fires, so it cannot loop behind the proxy.
|
||||||
|
*/
|
||||||
|
export function mpCallbackBounceUrl(requestUrl: string, requestHost: string | undefined, env: Env = process.env): string | null {
|
||||||
|
const tunnelHost = hostOf(env.MP_REDIRECT_URI);
|
||||||
|
const sessionOrigin = env.BETTER_AUTH_URL?.trim();
|
||||||
|
const sessionHost = hostOf(sessionOrigin);
|
||||||
|
if (!tunnelHost || !sessionOrigin || !sessionHost || tunnelHost === sessionHost) return null;
|
||||||
|
if (requestHost !== tunnelHost) return null;
|
||||||
|
|
||||||
|
const url = new URL(requestUrl);
|
||||||
|
return `${new URL(sessionOrigin).origin}${url.pathname}${url.search}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs before the session middleware, which would answer 401 on the tunnel. */
|
||||||
|
export const mpCallbackOriginMiddleware: MiddlewareHandler = async (c, next) => {
|
||||||
|
const target = mpCallbackBounceUrl(c.req.url, c.req.header('x-forwarded-host') ?? c.req.header('host'));
|
||||||
|
if (target) return c.redirect(target);
|
||||||
|
await next();
|
||||||
|
};
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
export { mpCallbackBounceUrl, mpCallbackOriginMiddleware } from './callback-origin';
|
||||||
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
|
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
|
||||||
export {
|
export {
|
||||||
codeChallengeFromVerifier,
|
codeChallengeFromVerifier,
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export type MpCreatePreferenceInput = {
|
|||||||
externalReference: string;
|
externalReference: string;
|
||||||
/** Where the buyer lands after paying (pending/success/failure). */
|
/** Where the buyer lands after paying (pending/success/failure). */
|
||||||
backUrl: string;
|
backUrl: string;
|
||||||
|
/** Where Mercado Pago notifies the payment (`POST /payments/webhooks/mp/:id`). */
|
||||||
|
notificationUrl?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type MpPreference = {
|
export type MpPreference = {
|
||||||
@@ -21,6 +23,21 @@ export type MpPreference = {
|
|||||||
sandboxInitPoint: string | null;
|
sandboxInitPoint: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mercado Pago refuses `auto_return` (`invalid_auto_return`) and notification
|
||||||
|
* URLs unless they are public HTTPS. In local development the web is on
|
||||||
|
* localhost: the buyer then gets MP's "back to the site" button instead of the
|
||||||
|
* automatic redirect, and without a tunnel only the polling confirms payments.
|
||||||
|
*/
|
||||||
|
export function isPublicHttpsUrl(value: string): boolean {
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
return url.protocol === 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a Checkout Pro preference in the seller's account. This is a payment
|
* Creates a Checkout Pro preference in the seller's account. This is a payment
|
||||||
* *link*: nothing is charged, and creating it again after a lost connection is
|
* *link*: nothing is charged, and creating it again after a lost connection is
|
||||||
@@ -50,7 +67,10 @@ export async function createCheckoutPreference(
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
external_reference: input.externalReference,
|
external_reference: input.externalReference,
|
||||||
auto_return: 'approved',
|
...(isPublicHttpsUrl(input.backUrl) ? { auto_return: 'approved' } : {}),
|
||||||
|
...(input.notificationUrl && isPublicHttpsUrl(input.notificationUrl)
|
||||||
|
? { notification_url: input.notificationUrl }
|
||||||
|
: {}),
|
||||||
back_urls: {
|
back_urls: {
|
||||||
success: input.backUrl,
|
success: input.backUrl,
|
||||||
pending: input.backUrl,
|
pending: input.backUrl,
|
||||||
@@ -120,9 +140,10 @@ export async function searchMpPaymentByExternalReference(
|
|||||||
|
|
||||||
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
|
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
|
||||||
const results = payload?.results ?? [];
|
const results = payload?.results ?? [];
|
||||||
const match = results.find(
|
// A rejected attempt and a later approved one share the reference: the
|
||||||
(payment) => payment.external_reference === externalReference,
|
// approved one wins, whatever order Mercado Pago lists them in.
|
||||||
);
|
const ours = results.filter((payment) => payment.external_reference === externalReference);
|
||||||
|
const match = ours.find((payment) => payment.status === 'approved') ?? ours[0];
|
||||||
if (!match) {
|
if (!match) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,17 +15,20 @@ import {
|
|||||||
notFoundResourceProblem,
|
notFoundResourceProblem,
|
||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { getApiPublicOrigin } from '@/lib/public-origin';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
import { getMpAccessToken } from '@/modules/mp';
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
|
||||||
import { CHECKOUT_BACK_PATH } from '../../lib';
|
import { CHECKOUT_BACK_PATH, paymentNotificationUrl } from '../../lib';
|
||||||
|
|
||||||
type BatchDeps = {
|
type BatchDeps = {
|
||||||
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
|
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
|
||||||
createPreference?: typeof createCheckoutPreference;
|
createPreference?: typeof createCheckoutPreference;
|
||||||
getToken?: typeof getMpAccessToken;
|
getToken?: typeof getMpAccessToken;
|
||||||
webOrigin?: string;
|
webOrigin?: string;
|
||||||
|
/** Public origin of the API, where Mercado Pago notifies the payment. */
|
||||||
|
apiOrigin?: string;
|
||||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -128,6 +131,7 @@ export class CreatePaymentBatch {
|
|||||||
currencyId: currency,
|
currencyId: currency,
|
||||||
externalReference: payment.id,
|
externalReference: payment.id,
|
||||||
backUrl,
|
backUrl,
|
||||||
|
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
|
||||||
});
|
});
|
||||||
link = preference;
|
link = preference;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -8,17 +8,20 @@ import {
|
|||||||
notFoundResourceProblem,
|
notFoundResourceProblem,
|
||||||
} from '@/http/problem-builders';
|
} from '@/http/problem-builders';
|
||||||
import prisma from '@/lib/prisma';
|
import prisma from '@/lib/prisma';
|
||||||
|
import { getApiPublicOrigin } from '@/lib/public-origin';
|
||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
import { PlanGuard } from '@/modules/billing/lib/entitlements';
|
||||||
import { getMpAccessToken } from '@/modules/mp';
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
|
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 = {
|
type RenewDeps = {
|
||||||
db?: Pick<PrismaClient, 'payment' | 'user'>;
|
db?: Pick<PrismaClient, 'payment' | 'user'>;
|
||||||
createPreference?: typeof createCheckoutPreference;
|
createPreference?: typeof createCheckoutPreference;
|
||||||
getToken?: typeof getMpAccessToken;
|
getToken?: typeof getMpAccessToken;
|
||||||
webOrigin?: string;
|
webOrigin?: string;
|
||||||
|
/** Public origin of the API, where Mercado Pago notifies the payment. */
|
||||||
|
apiOrigin?: string;
|
||||||
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
planGuard?: Pick<PlanGuard, 'requireFeature'>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -94,6 +97,7 @@ export class RenewPaymentLink {
|
|||||||
currencyId: currency,
|
currencyId: currency,
|
||||||
externalReference: payment.id,
|
externalReference: payment.id,
|
||||||
backUrl,
|
backUrl,
|
||||||
|
notificationUrl: paymentNotificationUrl(this.deps.apiOrigin ?? getApiPublicOrigin(), payment.id),
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
|
|||||||
17
apps/backend/src/modules/payments/features/webhook/route.ts
Normal file
17
apps/backend/src/modules/payments/features/webhook/route.ts
Normal file
@@ -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;
|
||||||
@@ -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<PrismaClient, 'payment'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MpPaymentNotificationOutcome = ConfirmMpPaymentOutcome | 'ignored';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mercado Pago says something happened to the payment of one of our links. The
|
||||||
|
* body is not read: the payment id in the URL picks the row, and the owner's
|
||||||
|
* account says whether it was approved (`confirmMpPayment`), so a forged or
|
||||||
|
* repeated notification costs one lookup and changes nothing.
|
||||||
|
*/
|
||||||
|
export class HandleMpPaymentNotification {
|
||||||
|
constructor(private readonly deps: HandleMpPaymentNotificationDeps = {}) {}
|
||||||
|
|
||||||
|
async execute(paymentId: string): Promise<Result<{ outcome: MpPaymentNotificationOutcome }, ProblemDetails>> {
|
||||||
|
const db = this.deps.db ?? prisma;
|
||||||
|
|
||||||
|
// OVERDUE too: a student can still pay a link after its due date.
|
||||||
|
const payment = await db.payment.findFirst({
|
||||||
|
where: { id: paymentId, status: { in: ['PENDING', 'OVERDUE'] }, checkoutUrl: { not: null } },
|
||||||
|
select: { id: true, group: { select: { createdById: true } } },
|
||||||
|
});
|
||||||
|
if (!payment) return ok({ outcome: 'ignored' });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const outcome = await confirmMpPayment(db, { id: payment.id, ownerId: payment.group.createdById }, this.deps);
|
||||||
|
return ok({ outcome });
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof MpApiError)) throw error;
|
||||||
|
// Not a 2xx, so Mercado Pago retries; the polling job is the fallback anyway.
|
||||||
|
logger.warn({ paymentId: payment.id, status: error.status }, 'Could not confirm a notified Mercado Pago payment');
|
||||||
|
return err(mpProviderErrorProblem());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,15 +3,13 @@ import prisma from '@/lib/prisma';
|
|||||||
import { logger } from '@/logger';
|
import { logger } from '@/logger';
|
||||||
import { getMpAccessToken } from '@/modules/mp';
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
||||||
|
import { confirmMpPayment } from '../lib';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pulls payments from Mercado Pago instead of trusting a webhook. A payment
|
* Pulls payments from Mercado Pago. The notification
|
||||||
* link is just a preference until someone pays it; this job asks the seller's
|
* (`POST /payments/webhooks/mp/:id`) confirms them right away; this job is the
|
||||||
* account for our `external_reference` and marks approved payments as PAID.
|
* fallback for links created before it existed and for lost notifications.
|
||||||
*
|
* Both go through `confirmMpPayment`.
|
||||||
* This is the stopgap and the source of truth: if a webhook is ever added it
|
|
||||||
* gives you the confirmation, but this job is what keeps the Cobros screen
|
|
||||||
* correct even when a notification is lost.
|
|
||||||
*/
|
*/
|
||||||
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
|
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
|
||||||
const BATCH_LIMIT = 50;
|
const BATCH_LIMIT = 50;
|
||||||
@@ -51,34 +49,21 @@ export class ReconcilePayments {
|
|||||||
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
|
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
|
||||||
|
|
||||||
for (const payment of awaiting) {
|
for (const payment of awaiting) {
|
||||||
const token = await getToken(payment.group.createdById);
|
|
||||||
if (!token.ok) {
|
|
||||||
// No usable token (not linked, or needs re-auth). Not a payment problem:
|
|
||||||
// the row stays PENDING and the account notice tells the professor what to do.
|
|
||||||
totals.skipped += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const found = await search(token.value.accessToken, payment.id);
|
const outcome = await confirmMpPayment(
|
||||||
if (found && found.status === 'approved' && found.externalReference === payment.id) {
|
db,
|
||||||
await db.payment.update({
|
{ id: payment.id, ownerId: payment.group.createdById },
|
||||||
where: { id: payment.id },
|
{ getToken, search },
|
||||||
data: {
|
);
|
||||||
status: 'PAID',
|
// No usable token is not a payment problem: the row stays PENDING and
|
||||||
mpPaymentId: found.id,
|
// the account notice tells the professor what to do.
|
||||||
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
|
if (outcome === 'no_token') totals.skipped += 1;
|
||||||
},
|
if (outcome === 'paid') totals.paid += 1;
|
||||||
});
|
|
||||||
totals.paid += 1;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof MpApiError) {
|
if (!(error instanceof MpApiError)) {
|
||||||
totals.failed += 1;
|
|
||||||
} else {
|
|
||||||
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
|
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
|
||||||
totals.failed += 1;
|
|
||||||
}
|
}
|
||||||
|
totals.failed += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
45
apps/backend/src/modules/payments/lib/confirm-mp-payment.ts
Normal file
45
apps/backend/src/modules/payments/lib/confirm-mp-payment.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import type { PrismaClient } from '@generated/prisma/client';
|
||||||
|
import { getMpAccessToken } from '@/modules/mp';
|
||||||
|
import { searchMpPaymentByExternalReference } from '@/modules/mp/lib';
|
||||||
|
|
||||||
|
export type ConfirmMpPaymentDeps = {
|
||||||
|
getToken?: typeof getMpAccessToken;
|
||||||
|
search?: typeof searchMpPaymentByExternalReference;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** `no_token`: the owner has no usable Mercado Pago link (not linked, or needs re-auth). */
|
||||||
|
export type ConfirmMpPaymentOutcome = 'paid' | 'unpaid' | 'no_token';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asks the owner's Mercado Pago account whether this payment was approved and,
|
||||||
|
* if so, marks it PAID. The only rule for a Checkout Pro payment, shared by the
|
||||||
|
* polling job and the notification: whatever triggered it is never trusted, the
|
||||||
|
* owner's account is. Throws `MpApiError` when Mercado Pago cannot answer.
|
||||||
|
*/
|
||||||
|
export async function confirmMpPayment(
|
||||||
|
db: Pick<PrismaClient, 'payment'>,
|
||||||
|
payment: { id: string; ownerId: string },
|
||||||
|
deps: ConfirmMpPaymentDeps = {},
|
||||||
|
): Promise<ConfirmMpPaymentOutcome> {
|
||||||
|
const token = await (deps.getToken ?? getMpAccessToken)(payment.ownerId);
|
||||||
|
if (!token.ok) return 'no_token';
|
||||||
|
|
||||||
|
const found = await (deps.search ?? searchMpPaymentByExternalReference)(token.value.accessToken, payment.id);
|
||||||
|
if (found?.status !== 'approved' || found.externalReference !== payment.id) return 'unpaid';
|
||||||
|
|
||||||
|
await db.payment.update({
|
||||||
|
where: { id: payment.id },
|
||||||
|
data: {
|
||||||
|
status: 'PAID',
|
||||||
|
mpPaymentId: found.id,
|
||||||
|
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return 'paid';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where Mercado Pago notifies a payment of this link (public: see `isPublicApiRequest`). */
|
||||||
|
export function paymentNotificationUrl(apiOrigin: string, paymentId: string): string {
|
||||||
|
// `source_news=webhooks`: only the webhook format, not the legacy IPN copy.
|
||||||
|
return `${apiOrigin}/api/v1/payments/webhooks/mp/${encodeURIComponent(paymentId)}?source_news=webhooks`;
|
||||||
|
}
|
||||||
@@ -1 +1,7 @@
|
|||||||
|
export {
|
||||||
|
type ConfirmMpPaymentDeps,
|
||||||
|
type ConfirmMpPaymentOutcome,
|
||||||
|
confirmMpPayment,
|
||||||
|
paymentNotificationUrl,
|
||||||
|
} from './confirm-mp-payment';
|
||||||
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';
|
export { CHECKOUT_BACK_PATH, type PaymentRecord, toPaymentDto } from './helpers';
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import getAllRoute from './features/get-all/route';
|
|||||||
import renewRoute from './features/renew/route';
|
import renewRoute from './features/renew/route';
|
||||||
import reportedRoute from './features/reported/route';
|
import reportedRoute from './features/reported/route';
|
||||||
import transferDetailsRoute from './features/transfer-details/route';
|
import transferDetailsRoute from './features/transfer-details/route';
|
||||||
|
import webhookRoute from './features/webhook/route';
|
||||||
|
|
||||||
const routes = new Hono();
|
const routes = new Hono();
|
||||||
|
|
||||||
@@ -10,5 +11,6 @@ routes.route('/', getAllRoute);
|
|||||||
routes.route('/', reportedRoute);
|
routes.route('/', reportedRoute);
|
||||||
routes.route('/', transferDetailsRoute);
|
routes.route('/', transferDetailsRoute);
|
||||||
routes.route('/', renewRoute);
|
routes.route('/', renewRoute);
|
||||||
|
routes.route('/', webhookRoute);
|
||||||
|
|
||||||
export default routes;
|
export default routes;
|
||||||
@@ -114,6 +114,25 @@ describe('admin access', () => {
|
|||||||
expect(db.user.findUnique).not.toHaveBeenCalled();
|
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 () => {
|
it('asks for a session without a user', async () => {
|
||||||
const response = await makeApp(null).request('/admin/accounts');
|
const response = await makeApp(null).request('/admin/accounts');
|
||||||
expect(response.status).toBe(401);
|
expect(response.status).toBe(401);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { describe, expect, it, mock } from 'bun:test';
|
import { describe, expect, it, mock } from 'bun:test';
|
||||||
|
import { staticPlanCatalog } from '@/modules/billing/lib/catalog';
|
||||||
import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements';
|
import { PlanGuard, resolvePlan } from '@/modules/billing/lib/entitlements';
|
||||||
|
|
||||||
const now = new Date('2026-10-22T12:00:00.000Z');
|
const now = new Date('2026-10-22T12:00:00.000Z');
|
||||||
@@ -18,7 +19,7 @@ function makeDb(params: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function makeGuard(db: ReturnType<typeof makeDb>, enforced = true) {
|
function makeGuard(db: ReturnType<typeof makeDb>, 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', () => {
|
describe('resolvePlan', () => {
|
||||||
|
|||||||
266
apps/backend/test/billing-plan-catalog.test.ts
Normal file
266
apps/backend/test/billing-plan-catalog.test.ts
Normal file
@@ -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<string, unknown> = {}) {
|
||||||
|
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<string, string>;
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
55
apps/backend/test/billing-return.test.ts
Normal file
55
apps/backend/test/billing-return.test.ts
Normal file
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||||
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
|
import { CancelSubscription } from '@/modules/billing/features/cancel/use-case';
|
||||||
import { Subscribe } from '@/modules/billing/features/subscribe/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 type { BillingProvider } from '@/modules/billing/providers';
|
||||||
import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago';
|
import { MercadoPagoBillingProvider, type PreapprovalClient } from '@/modules/billing/providers/mercado-pago';
|
||||||
|
|
||||||
@@ -53,7 +54,7 @@ function subscribe(db: ReturnType<typeof makeDb>, client = makeClient()) {
|
|||||||
return {
|
return {
|
||||||
client,
|
client,
|
||||||
run: (returnTo: 'billing' | 'onboarding' = 'billing') =>
|
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,
|
userId,
|
||||||
{ payerEmail: 'profe@mail.com', returnTo },
|
{ payerEmail: 'profe@mail.com', returnTo },
|
||||||
),
|
),
|
||||||
@@ -79,7 +80,7 @@ describe('Subscribe', () => {
|
|||||||
payerEmail: 'profe@mail.com',
|
payerEmail: 'profe@mail.com',
|
||||||
amount: 15000,
|
amount: 15000,
|
||||||
currencyId: 'ARS',
|
currencyId: 'ARS',
|
||||||
backUrl: 'http://web/billing?sub=return',
|
backUrl: 'https://api/api/v1/billing/return?to=billing',
|
||||||
startDate: undefined,
|
startDate: undefined,
|
||||||
});
|
});
|
||||||
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
expect(db.billingSubscription.update).toHaveBeenCalledWith({
|
||||||
@@ -93,7 +94,7 @@ describe('Subscribe', () => {
|
|||||||
await run('onboarding');
|
await run('onboarding');
|
||||||
|
|
||||||
expect((client.createPreapproval as ReturnType<typeof mock>).mock.calls[0]?.[1]).toMatchObject({
|
expect((client.createPreapproval as ReturnType<typeof mock>).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 db = makeDb(null, 'AR');
|
||||||
const client = makeClient();
|
const client = makeClient();
|
||||||
const provider = new MercadoPagoBillingProvider({ client, credentials: () => null });
|
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',
|
payerEmail: 'profe@mail.com',
|
||||||
returnTo: 'billing',
|
returnTo: 'billing',
|
||||||
});
|
});
|
||||||
@@ -224,13 +225,13 @@ describe('Subscribe outside Argentina (Stripe)', () => {
|
|||||||
const stripe = fakeStripe();
|
const stripe = fakeStripe();
|
||||||
const resolved: string[] = [];
|
const resolved: string[] = [];
|
||||||
|
|
||||||
const result = await new Subscribe({
|
const result = await new Subscribe({ catalog: staticPlanCatalog(),
|
||||||
db: db as never,
|
db: db as never,
|
||||||
providers: (id) => {
|
providers: (id) => {
|
||||||
resolved.push(id);
|
resolved.push(id);
|
||||||
return stripe;
|
return stripe;
|
||||||
},
|
},
|
||||||
webOrigin: 'http://web',
|
apiOrigin: 'https://api',
|
||||||
now: () => now,
|
now: () => now,
|
||||||
}).execute(userId, { returnTo: 'billing' });
|
}).execute(userId, { returnTo: 'billing' });
|
||||||
|
|
||||||
@@ -242,7 +243,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
|
|||||||
amount: 199,
|
amount: 199,
|
||||||
currency: 'MXN',
|
currency: 'MXN',
|
||||||
payerEmail: null,
|
payerEmail: null,
|
||||||
backUrl: 'http://web/billing?sub=return',
|
backUrl: 'https://api/api/v1/billing/return?to=billing',
|
||||||
startDate: undefined,
|
startDate: undefined,
|
||||||
});
|
});
|
||||||
expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record<string, unknown> }])[0].create).toMatchObject({
|
expect((db.billingSubscription.upsert.mock.calls[0] as unknown as [{ create: Record<string, unknown> }])[0].create).toMatchObject({
|
||||||
@@ -261,10 +262,10 @@ describe('Subscribe outside Argentina (Stripe)', () => {
|
|||||||
const mp = mpProvider(client);
|
const mp = mpProvider(client);
|
||||||
const stripe = fakeStripe();
|
const stripe = fakeStripe();
|
||||||
|
|
||||||
await new Subscribe({
|
await new Subscribe({ catalog: staticPlanCatalog(),
|
||||||
db: db as never,
|
db: db as never,
|
||||||
providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe),
|
providers: (id) => (id === 'MERCADO_PAGO' ? mp : stripe),
|
||||||
webOrigin: 'http://web',
|
apiOrigin: 'https://api',
|
||||||
now: () => now,
|
now: () => now,
|
||||||
}).execute(userId, { returnTo: 'billing' });
|
}).execute(userId, { returnTo: 'billing' });
|
||||||
|
|
||||||
@@ -275,7 +276,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
|
|||||||
const db = makeDb(null, 'CL');
|
const db = makeDb(null, 'CL');
|
||||||
const stripe = fakeStripe({ isAvailable: () => false });
|
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',
|
returnTo: 'billing',
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -288,7 +289,7 @@ describe('Subscribe outside Argentina (Stripe)', () => {
|
|||||||
const db = makeDb(null, 'AR');
|
const db = makeDb(null, 'AR');
|
||||||
const provider = mpProvider(makeClient());
|
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',
|
returnTo: 'billing',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
78
apps/backend/test/mp-preference.test.ts
Normal file
78
apps/backend/test/mp-preference.test.ts
Normal file
@@ -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<string, unknown> = {};
|
||||||
|
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' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -27,6 +27,7 @@ import prisma from '@/lib/prisma';
|
|||||||
import { getMpAccessToken, mpRoutes } from '@/modules/mp';
|
import { getMpAccessToken, mpRoutes } from '@/modules/mp';
|
||||||
import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens';
|
import { RefreshExpiringMpTokens } from '@/modules/mp/jobs/refresh-expiring-mp-tokens';
|
||||||
import { RefreshMpAccount } from '@/modules/mp/jobs/refresh-mp-account';
|
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 { codeChallengeFromVerifier, openToken, sealToken } from '@/modules/mp/lib/crypto';
|
||||||
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
|
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
|
||||||
|
|
||||||
@@ -579,6 +580,17 @@ describe('modules/mp', () => {
|
|||||||
expect(location.href).not.toContain(storedState.codeVerifier);
|
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 () => {
|
it('sends a teacher without a session to the login screen', async () => {
|
||||||
const res = await makeApp(null).request(callbackUrl('?code=code&state=state-abc'));
|
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 });
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ function batchUseCase() {
|
|||||||
initPoint: 'https://mp.link/pay-1',
|
initPoint: 'https://mp.link/pay-1',
|
||||||
sandboxInitPoint: null,
|
sandboxInitPoint: null,
|
||||||
}));
|
}));
|
||||||
return new CreatePaymentBatch({ getToken, createPreference, webOrigin });
|
return new CreatePaymentBatch({ getToken, createPreference, webOrigin, apiOrigin: 'https://api' });
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('create payments batch', () => {
|
describe('create payments batch', () => {
|
||||||
@@ -143,6 +143,7 @@ describe('create payments batch', () => {
|
|||||||
currencyId: 'ARS',
|
currencyId: 'ARS',
|
||||||
externalReference: 'pay-1',
|
externalReference: 'pay-1',
|
||||||
backUrl: `${webOrigin}/student/payments`,
|
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');
|
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',
|
'group-1',
|
||||||
userId,
|
userId,
|
||||||
{ dueDate: '2026-10-05T12:00:00.000Z' },
|
{ dueDate: '2026-10-05T12:00:00.000Z' },
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ describe('renew payment link', () => {
|
|||||||
sandboxInitPoint: null,
|
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',
|
'pay-1',
|
||||||
userId,
|
userId,
|
||||||
);
|
);
|
||||||
@@ -102,6 +102,7 @@ describe('renew payment link', () => {
|
|||||||
currencyId: 'ARS',
|
currencyId: 'ARS',
|
||||||
externalReference: 'pay-1',
|
externalReference: 'pay-1',
|
||||||
backUrl: `${webOrigin}/student/payments`,
|
backUrl: `${webOrigin}/student/payments`,
|
||||||
|
notificationUrl: 'https://api/api/v1/payments/webhooks/mp/pay-1?source_news=webhooks',
|
||||||
});
|
});
|
||||||
expect(prisma.payment.update).toHaveBeenCalledWith({
|
expect(prisma.payment.update).toHaveBeenCalledWith({
|
||||||
where: { id: 'pay-1' },
|
where: { id: 'pay-1' },
|
||||||
|
|||||||
103
apps/backend/test/payments-webhook.test.ts
Normal file
103
apps/backend/test/payments-webhook.test.ts
Normal file
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,8 +3,10 @@
|
|||||||
# Con el proxy, el navegador pega siempre al mismo origen: la cookie de sesión
|
# Con el proxy, el navegador pega siempre al mismo origen: la cookie de sesión
|
||||||
# es first-party y el CORS del backend queda como red de seguridad.
|
# es first-party y el CORS del backend queda como red de seguridad.
|
||||||
|
|
||||||
# DNS interno de Docker: resuelve `api` en cada request, así el proxy sobrevive
|
# DNS interno de Docker: resuelve `gruperly-api` en cada request, así el proxy
|
||||||
# a un recreate del contenedor (que cambia la IP).
|
# sobrevive a un recreate del contenedor (que cambia la IP). Es un alias que el
|
||||||
|
# compose define solo en la red propia del stack; `api` también existe en
|
||||||
|
# dokploy-network y con dev y prod en el mismo server resolvería a cualquiera.
|
||||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||||
|
|
||||||
server {
|
server {
|
||||||
@@ -18,7 +20,7 @@ server {
|
|||||||
|
|
||||||
# ── API ────────────────────────────────────────────────────────────────────
|
# ── API ────────────────────────────────────────────────────────────────────
|
||||||
location /api/ {
|
location /api/ {
|
||||||
set $api http://api:4000;
|
set $api http://gruperly-api:4000;
|
||||||
proxy_pass $api$request_uri;
|
proxy_pass $api$request_uri;
|
||||||
|
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { forwardRef, type ButtonHTMLAttributes } from 'react'
|
|||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
export type ButtonVariant = 'primary' | 'ghost' | 'outline'
|
export type ButtonVariant = 'primary' | 'ghost' | 'outline'
|
||||||
export type ButtonSize = 'sm' | 'md' | 'icon'
|
export type ButtonSize = 'sm' | 'md' | 'lg' | 'icon'
|
||||||
|
|
||||||
export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
|
export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||||
variant?: ButtonVariant
|
variant?: ButtonVariant
|
||||||
@@ -18,6 +18,8 @@ const variants: Record<ButtonVariant, string> = {
|
|||||||
const sizes: Record<ButtonSize, string> = {
|
const sizes: Record<ButtonSize, string> = {
|
||||||
sm: 'h-8 px-3 text-sm',
|
sm: 'h-8 px-3 text-sm',
|
||||||
md: 'h-10 px-4 text-sm',
|
md: 'h-10 px-4 text-sm',
|
||||||
|
// Acciones principales de un flujo en mobile: 48px, cómodo para el pulgar.
|
||||||
|
lg: 'h-12 px-5 text-sm',
|
||||||
icon: 'size-9',
|
icon: 'size-9',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import type { AdminAccountDetail } from '@gruperly/shared'
|
import type { AdminAccountDetail } from '@gruperly/shared'
|
||||||
import { PLAN_LIMITS } from '@gruperly/shared'
|
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ArrowLeft, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Loader2 } from 'lucide-react'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
@@ -60,7 +59,7 @@ export function AdminAccountDetailView() {
|
|||||||
|
|
||||||
function AccountDetail({ account }: { account: AdminAccountDetail }) {
|
function AccountDetail({ account }: { account: AdminAccountDetail }) {
|
||||||
const subscription = account.subscription
|
const subscription = account.subscription
|
||||||
const limits = PLAN_LIMITS[account.plan ?? 'FREE']
|
const limits = account.limits
|
||||||
const { t } = useTranslation(['admin', 'common', 'billing'])
|
const { t } = useTranslation(['admin', 'common', 'billing'])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import { ArrowLeft } from 'lucide-react'
|
|||||||
import { ThemeToggle } from '../../components/layout/ThemeToggle'
|
import { ThemeToggle } from '../../components/layout/ThemeToggle'
|
||||||
import { useTranslation } from 'react-i18next'
|
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
|
/* Layout propio del backoffice: sin la navegación del profesor y pensado para
|
||||||
escritorio, aunque en móvil se lee igual (columna única). */
|
escritorio, aunque en móvil se lee igual (columna única). */
|
||||||
export function AdminLayout({ children }: { children: ReactNode }) {
|
export function AdminLayout({ children }: { children: ReactNode }) {
|
||||||
@@ -12,9 +15,25 @@ export function AdminLayout({ children }: { children: ReactNode }) {
|
|||||||
<div className="min-h-dvh bg-background">
|
<div className="min-h-dvh bg-background">
|
||||||
<header className="sticky top-0 z-30 border-b border-border bg-surface/90 backdrop-blur">
|
<header className="sticky top-0 z-30 border-b border-border bg-surface/90 backdrop-blur">
|
||||||
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4 lg:px-8">
|
<div className="mx-auto flex h-14 max-w-6xl items-center justify-between gap-3 px-4 lg:px-8">
|
||||||
<Link to="/admin" className="text-base font-bold text-primary">
|
<div className="flex min-w-0 items-center gap-4">
|
||||||
Gruperly <span className="font-medium text-foreground/50">· {t('brand')}</span>
|
<Link to="/admin" className="shrink-0 text-base font-bold text-primary">
|
||||||
|
Gruperly <span className="hidden font-medium text-foreground/50 sm:inline">· {t('brand')}</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
<nav className="flex items-center gap-1 text-sm">
|
||||||
|
{/* exact: /admin no queda activo dentro de /admin/plans */}
|
||||||
|
<Link
|
||||||
|
to="/admin"
|
||||||
|
activeOptions={{ exact: true }}
|
||||||
|
className={navLinkClass}
|
||||||
|
activeProps={{ className: activeNavLinkClass }}
|
||||||
|
>
|
||||||
|
{t('accounts')}
|
||||||
|
</Link>
|
||||||
|
<Link to="/admin/plans" className={navLinkClass} activeProps={{ className: activeNavLinkClass }}>
|
||||||
|
{t('plans.title')}
|
||||||
|
</Link>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
95
apps/web/src/features/admin/AdminPlansProvider.tsx
Normal file
95
apps/web/src/features/admin/AdminPlansProvider.tsx
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
import type { AdminPlansDto, CountryCode, Plan, UpdatePlanLimitsInput, UpdatePlanPriceInput } from '@gruperly/shared'
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { createContext, useContext } from 'react'
|
||||||
|
import { useToast } from '../../components/ui'
|
||||||
|
import { getAdminPlans, updatePlanLimits, updatePlanPrice } from '../../lib/api'
|
||||||
|
import { errorMessage as apiErrorMessage } from '../../i18n'
|
||||||
|
import { i18n } from '../../i18n/instance'
|
||||||
|
|
||||||
|
const adminPlansQueryKey = ['admin', 'plans'] as const
|
||||||
|
|
||||||
|
type AdminPlansContextValue = {
|
||||||
|
plans: AdminPlansDto | null
|
||||||
|
isPending: boolean
|
||||||
|
isError: boolean
|
||||||
|
errorMessage: string | null
|
||||||
|
retry: () => void
|
||||||
|
saveLimits: (plan: Plan, input: UpdatePlanLimitsInput) => Promise<boolean>
|
||||||
|
isSavingLimits: boolean
|
||||||
|
savePrice: (country: CountryCode, input: UpdatePlanPriceInput) => Promise<boolean>
|
||||||
|
isSavingPrice: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const AdminPlansContext = createContext<AdminPlansContextValue | null>(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<unknown>) => {
|
||||||
|
try {
|
||||||
|
await mutation()
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdminPlansContext.Provider
|
||||||
|
value={{
|
||||||
|
plans: plansQuery.data ?? null,
|
||||||
|
isPending: plansQuery.isPending,
|
||||||
|
isError: plansQuery.isError,
|
||||||
|
errorMessage: plansQuery.isError
|
||||||
|
? apiErrorMessage(plansQuery.error, i18n.t('admin:plans.loadError'))
|
||||||
|
: null,
|
||||||
|
retry: () => 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}
|
||||||
|
</AdminPlansContext.Provider>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAdminPlans(): AdminPlansContextValue {
|
||||||
|
const context = useContext(AdminPlansContext)
|
||||||
|
if (!context) throw new Error('useAdminPlans must be used inside AdminPlansProvider')
|
||||||
|
return context
|
||||||
|
}
|
||||||
61
apps/web/src/features/admin/AdminPlansView.tsx
Normal file
61
apps/web/src/features/admin/AdminPlansView.tsx
Normal file
@@ -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 (
|
||||||
|
<section>
|
||||||
|
<h1 className="text-2xl font-bold text-primary">{t('plans.title')}</h1>
|
||||||
|
<p className="mt-1 text-sm text-foreground/60">{t('plans.subtitle')}</p>
|
||||||
|
|
||||||
|
{isPending ? (
|
||||||
|
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||||
|
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||||
|
<span className="sr-only">{t('plans.loading')}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{isError ? (
|
||||||
|
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
|
<p>{errorMessage}</p>
|
||||||
|
<Button variant="outline" size="sm" onClick={retry}>
|
||||||
|
{t('common:actions.retry')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{plans ? (
|
||||||
|
<div className="mt-6 space-y-8">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-sm font-semibold uppercase tracking-wide text-foreground/50">
|
||||||
|
{t('plans.limits.title')}
|
||||||
|
</h2>
|
||||||
|
<p className="mt-1 text-xs text-foreground/50">{t('plans.limits.hint')}</p>
|
||||||
|
<div className="mt-3 grid gap-4 sm:grid-cols-2">
|
||||||
|
<PlanLimitsCard plan="FREE" limits={plans.limits.FREE} />
|
||||||
|
<PlanLimitsCard plan="PRO" limits={plans.limits.PRO} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h2 className="text-sm font-semibold uppercase tracking-wide text-foreground/50">
|
||||||
|
{t('plans.prices.title')}
|
||||||
|
</h2>
|
||||||
|
<p className="mt-1 text-xs text-foreground/50">{t('plans.prices.hint')}</p>
|
||||||
|
<ul className="mt-3 divide-y divide-border rounded-xl border border-border bg-surface">
|
||||||
|
{plans.prices.map((price) => (
|
||||||
|
<PlanPriceRow key={price.country} price={price} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
52
apps/web/src/features/admin/LimitInput.tsx
Normal file
52
apps/web/src/features/admin/LimitInput.tsx
Normal file
@@ -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 (
|
||||||
|
<div>
|
||||||
|
<label htmlFor={id} className="mb-1.5 block text-sm font-medium text-primary">
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Input
|
||||||
|
id={id}
|
||||||
|
type="number"
|
||||||
|
inputMode="numeric"
|
||||||
|
min={0}
|
||||||
|
step={1}
|
||||||
|
autoFocus={autoFocus}
|
||||||
|
disabled={unlimited}
|
||||||
|
value={unlimited ? '' : value}
|
||||||
|
placeholder={unlimited ? t('plans.limits.unlimited') : undefined}
|
||||||
|
onChange={(event) => {
|
||||||
|
const parsed = Number.parseInt(event.target.value, 10)
|
||||||
|
onChange(Number.isNaN(parsed) ? 0 : Math.max(0, parsed))
|
||||||
|
}}
|
||||||
|
className="max-w-32"
|
||||||
|
/>
|
||||||
|
<span className="flex items-center gap-2 text-sm text-foreground/70">
|
||||||
|
<Switch
|
||||||
|
checked={unlimited}
|
||||||
|
onCheckedChange={(checked) => onChange(checked ? null : 0)}
|
||||||
|
aria-label={t('plans.limits.unlimitedFor', { label })}
|
||||||
|
/>
|
||||||
|
{t('plans.limits.unlimited')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
131
apps/web/src/features/admin/PlanLimitsCard.tsx
Normal file
131
apps/web/src/features/admin/PlanLimitsCard.tsx
Normal file
@@ -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<PlanLimits | null>(null)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border border-border bg-surface p-4">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<h3 className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</h3>
|
||||||
|
{draft ? null : (
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setDraft(limits)}>
|
||||||
|
<Pencil className="size-3.5" aria-hidden="true" />
|
||||||
|
{t('plans.edit')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{draft ? (
|
||||||
|
<form
|
||||||
|
className="mt-4 space-y-4"
|
||||||
|
onSubmit={async (event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
if (await saveLimits(plan, draft)) setDraft(null)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LimitInput
|
||||||
|
id={`${plan}-max-groups`}
|
||||||
|
label={t('plans.limits.maxGroups')}
|
||||||
|
value={draft.maxGroups}
|
||||||
|
onChange={(maxGroups) => setDraft({ ...draft, maxGroups })}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<LimitInput
|
||||||
|
id={`${plan}-max-attendees`}
|
||||||
|
label={t('plans.limits.maxAttendees')}
|
||||||
|
value={draft.maxAttendees}
|
||||||
|
onChange={(maxAttendees) => setDraft({ ...draft, maxAttendees })}
|
||||||
|
/>
|
||||||
|
<FeatureSwitch
|
||||||
|
label={t('plans.limits.mpCharges')}
|
||||||
|
checked={draft.mpCharges}
|
||||||
|
onChange={(mpCharges) => setDraft({ ...draft, mpCharges })}
|
||||||
|
/>
|
||||||
|
<FeatureSwitch
|
||||||
|
label={t('plans.limits.whatsappAutomations')}
|
||||||
|
checked={draft.whatsappAutomations}
|
||||||
|
onChange={(whatsappAutomations) => setDraft({ ...draft, whatsappAutomations })}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<LimitsImpact plan={plan} draft={draft} current={limits} />
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="ghost" onClick={() => setDraft(null)} disabled={isSavingLimits}>
|
||||||
|
{t('plans.cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button variant="primary" type="submit" disabled={isSavingLimits}>
|
||||||
|
{isSavingLimits ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null}
|
||||||
|
{t('plans.save')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<ul className="mt-3 space-y-1.5 text-sm">
|
||||||
|
{planFeatureList(limits).map((feature) => (
|
||||||
|
<li key={feature.label} className={feature.included ? 'text-primary' : 'text-foreground/40 line-through'}>
|
||||||
|
{feature.label}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function FeatureSwitch({ label, checked, onChange }: { label: string; checked: boolean; onChange: (value: boolean) => void }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-between gap-3 text-sm text-primary">
|
||||||
|
<span>{label}</span>
|
||||||
|
<Switch checked={checked} onCheckedChange={onChange} aria-label={label} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<p className="flex items-start gap-2 rounded-xl bg-warning-soft px-3 py-2 text-xs text-warning">
|
||||||
|
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
|
||||||
|
{t('plans.limits.impact', { count: impactQuery.data.affectedAccounts })}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
}
|
||||||
118
apps/web/src/features/admin/PlanPriceRow.tsx
Normal file
118
apps/web/src/features/admin/PlanPriceRow.tsx
Normal file
@@ -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<string | null>(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 (
|
||||||
|
<li className="px-4 py-3">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-sm font-medium text-primary">
|
||||||
|
{countryLabel(price.country)}{' '}
|
||||||
|
<span className="font-normal text-foreground/50">· {BILLING_PROVIDER_NAMES[price.provider]}</span>
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
|
{t('plans.prices.live', { count: price.liveSubscriptions })}
|
||||||
|
{price.atOtherPrice > 0 ? ` · ${t('plans.prices.atOtherPrice', { count: price.atOtherPrice })}` : ''}
|
||||||
|
{updatedAt ? ` · ${t('plans.prices.updatedAt', { date: updatedAt })}` : ''}
|
||||||
|
</p>
|
||||||
|
{price.pendingChanges > 0 || price.failedChanges > 0 ? (
|
||||||
|
<div className="mt-1 flex flex-wrap gap-1.5">
|
||||||
|
{price.pendingChanges > 0 ? (
|
||||||
|
<Badge variant="info">{t('plans.prices.pending', { count: price.pendingChanges })}</Badge>
|
||||||
|
) : null}
|
||||||
|
{price.failedChanges > 0 ? (
|
||||||
|
<Badge variant="danger">{t('plans.prices.failed', { count: price.failedChanges })}</Badge>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="text-sm font-semibold text-primary">
|
||||||
|
{t('detail.perMonth', { price: formatPrice(price.amount, price.currency) })}
|
||||||
|
</span>
|
||||||
|
{amount === null ? (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
setAmount(String(price.amount))
|
||||||
|
setApplyToExisting(true)
|
||||||
|
}}
|
||||||
|
aria-label={t('plans.prices.editFor', { country: countryLabel(price.country) })}
|
||||||
|
>
|
||||||
|
<Pencil className="size-3.5" aria-hidden="true" />
|
||||||
|
{t('plans.edit')}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{amount !== null ? (
|
||||||
|
<form
|
||||||
|
className="mt-3 space-y-3 rounded-xl bg-background p-3"
|
||||||
|
onSubmit={async (event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
if (!valid) return
|
||||||
|
if (await savePrice(price.country, { amount: parsed, applyToExisting })) setAmount(null)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<label className="block">
|
||||||
|
<span className="mb-1.5 block text-sm font-medium text-primary">
|
||||||
|
{t('plans.prices.amount', { currency: price.currency })}
|
||||||
|
</span>
|
||||||
|
<Input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
autoFocus
|
||||||
|
value={amount}
|
||||||
|
invalid={amount !== '' && !valid}
|
||||||
|
onChange={(event) => setAmount(event.target.value)}
|
||||||
|
className="max-w-40"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="text-sm">
|
||||||
|
<p className="text-primary">{t('plans.prices.applyToExisting')}</p>
|
||||||
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
|
{t('plans.prices.applyHint', { count: price.liveSubscriptions })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={applyToExisting}
|
||||||
|
onCheckedChange={setApplyToExisting}
|
||||||
|
aria-label={t('plans.prices.applyToExisting')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="ghost" onClick={() => setAmount(null)} disabled={isSavingPrice}>
|
||||||
|
{t('plans.cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button variant="primary" type="submit" disabled={!valid || isSavingPrice}>
|
||||||
|
{isSavingPrice ? <Loader2 className="size-4 animate-spin" aria-hidden="true" /> : null}
|
||||||
|
{t('plans.save')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
) : null}
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
import { PLAN_LIMITS } from '@gruperly/shared'
|
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import { ChevronLeft, Sparkles } from 'lucide-react'
|
import { ChevronLeft, Sparkles } from 'lucide-react'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
@@ -10,6 +9,7 @@ import { ChargesList } from './ChargesList'
|
|||||||
import { PlanOptionCard } from './PlanOptionCard'
|
import { PlanOptionCard } from './PlanOptionCard'
|
||||||
import { PlanSummaryCard } from './PlanSummaryCard'
|
import { PlanSummaryCard } from './PlanSummaryCard'
|
||||||
import { SubscribeModal } from './SubscribeModal'
|
import { SubscribeModal } from './SubscribeModal'
|
||||||
|
import { usePlanCatalog } from './usePlanCatalog'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
|
||||||
export function BillingView() {
|
export function BillingView() {
|
||||||
@@ -17,6 +17,7 @@ export function BillingView() {
|
|||||||
const [isConfirmingCancel, setIsConfirmingCancel] = useState(false)
|
const [isConfirmingCancel, setIsConfirmingCancel] = useState(false)
|
||||||
const { t } = useTranslation(['billing', 'common'])
|
const { t } = useTranslation(['billing', 'common'])
|
||||||
const status = statusQuery.data
|
const status = statusQuery.data
|
||||||
|
const { catalog } = usePlanCatalog()
|
||||||
|
|
||||||
const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED'
|
const subscribed = status?.status === 'AUTHORIZED' || status?.status === 'PAUSED'
|
||||||
const pending = status?.status === 'PENDING'
|
const pending = status?.status === 'PENDING'
|
||||||
@@ -42,10 +43,10 @@ export function BillingView() {
|
|||||||
|
|
||||||
{status ? (
|
{status ? (
|
||||||
<div className="grid gap-4 sm:grid-cols-2">
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE} current={status.plan === 'FREE'} />
|
<PlanOptionCard plan="FREE" limits={catalog.limits.FREE} current={status.plan === 'FREE'} />
|
||||||
<PlanOptionCard
|
<PlanOptionCard
|
||||||
plan="PRO"
|
plan="PRO"
|
||||||
limits={PLAN_LIMITS.PRO}
|
limits={catalog.limits.PRO}
|
||||||
price={proPrice}
|
price={proPrice}
|
||||||
current={status.plan === 'PRO'}
|
current={status.plan === 'PRO'}
|
||||||
highlighted={status.plan === 'FREE'}
|
highlighted={status.plan === 'FREE'}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { Plan, PlanLimits } from '@gruperly/shared'
|
import type { Plan, PlanLimits } from '@gruperly/shared'
|
||||||
import { Check } from 'lucide-react'
|
import { Check, Lock } from 'lucide-react'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { Badge } from '../../components/ui'
|
import { Badge } from '../../components/ui'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
@@ -29,18 +29,32 @@ export function PlanOptionCard({ plan, limits, price, current, highlighted, chil
|
|||||||
>
|
>
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex items-center justify-between gap-3">
|
||||||
<p className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</p>
|
<p className="text-base font-semibold text-primary">{PLAN_NAMES[plan]}</p>
|
||||||
{current ? <Badge variant="info">{t('option.yourPlan')}</Badge> : null}
|
{current ? (
|
||||||
|
<Badge variant="info">{t('option.yourPlan')}</Badge>
|
||||||
|
) : highlighted ? (
|
||||||
|
// El destacado no puede ser solo el color del borde.
|
||||||
|
<Badge variant="info">{t('option.recommended')}</Badge>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-sm text-foreground/60">{price ?? t('option.free')}</p>
|
<p className="mt-1 text-sm text-foreground/60">{price ?? t('option.free')}</p>
|
||||||
|
|
||||||
<ul className="mt-3 flex-1 space-y-1.5">
|
<ul className="mt-3 flex-1 space-y-1.5">
|
||||||
{planFeatureList(limits).map((feature) => (
|
{planFeatureList(limits).map((feature) => (
|
||||||
<li key={feature.label} className="flex items-start gap-2 text-sm">
|
<li key={feature.label} className="flex items-start gap-2 text-sm">
|
||||||
<Check
|
{feature.included ? (
|
||||||
className={cn('mt-0.5 size-4 shrink-0', feature.included ? 'text-success' : 'text-foreground/20')}
|
<Check aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-success" />
|
||||||
/>
|
) : (
|
||||||
<span className={feature.included ? 'text-primary' : 'text-foreground/40 line-through'}>
|
<Lock aria-hidden="true" className="mt-0.5 size-4 shrink-0 text-foreground/30" />
|
||||||
|
)}
|
||||||
|
{/* Lo que el plan no trae se nombra como "en Pro" y no tachado: se
|
||||||
|
lee como lo que falta, no como un castigo. */}
|
||||||
|
<span className={feature.included ? 'text-primary' : 'text-foreground/50'}>
|
||||||
{feature.label}
|
{feature.label}
|
||||||
|
{feature.included ? null : (
|
||||||
|
<span className="ml-1.5 whitespace-nowrap text-xs font-medium text-foreground/50">
|
||||||
|
· {t('option.inPro')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -43,7 +43,12 @@ export function PlanSummaryCard() {
|
|||||||
</div>
|
</div>
|
||||||
{status.status === 'AUTHORIZED' && nextPayment ? (
|
{status.status === 'AUTHORIZED' && nextPayment ? (
|
||||||
<p className="mt-0.5 text-xs text-foreground/50">
|
<p className="mt-0.5 text-xs text-foreground/50">
|
||||||
{t('summary.next', { amount: formatPrice(status.priceAmount, status.currency), date: nextPayment })}
|
{t('summary.next', { amount: formatPrice(status.nextPriceAmount ?? status.priceAmount, status.currency), date: nextPayment })}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
{status.nextPriceAmount !== null && status.status !== 'CANCELLED' ? (
|
||||||
|
<p className="mt-1 rounded-lg bg-warning-soft px-2 py-1 text-xs text-warning">
|
||||||
|
{t('summary.nextPrice', { amount: formatPrice(status.nextPriceAmount, status.currency) })}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
{status.status === 'PENDING' ? (
|
{status.status === 'PENDING' ? (
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ export function SubscribeForm({
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
|
{error ? <p role="alert" className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
|
||||||
|
|
||||||
<div className="flex justify-end gap-3">
|
<div className="flex justify-end gap-3">
|
||||||
{onCancel ? (
|
{onCancel ? (
|
||||||
|
|||||||
@@ -18,4 +18,5 @@ export { PlanSettingsCard } from './PlanSettingsCard'
|
|||||||
export { PlanUpgradePrompt } from './PlanUpgradePrompt'
|
export { PlanUpgradePrompt } from './PlanUpgradePrompt'
|
||||||
export { SubscribeForm } from './SubscribeForm'
|
export { SubscribeForm } from './SubscribeForm'
|
||||||
export { billingStatusQueryKey, useBillingStatus } from './useBillingStatus'
|
export { billingStatusQueryKey, useBillingStatus } from './useBillingStatus'
|
||||||
|
export { planCatalogQueryKey, usePlanCatalog } from './usePlanCatalog'
|
||||||
export { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling'
|
export { useSubscriptionReturnPolling } from './useSubscriptionReturnPolling'
|
||||||
|
|||||||
23
apps/web/src/features/billing/usePlanCatalog.ts
Normal file
23
apps/web/src/features/billing/usePlanCatalog.ts
Normal file
@@ -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 }
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
import { type DefaultValues, useForm } from 'react-hook-form'
|
import { type DefaultValues, useForm } from 'react-hook-form'
|
||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
|
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
|
||||||
import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
import { COUNTRY_CURRENCY, CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
||||||
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
|
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { useId } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { sortWeekDays } from '../../lib/format'
|
import { currencySymbol, sortWeekDays } from '../../lib/format'
|
||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import { Button, FieldError, Input, Label } from '../../components/ui'
|
import { Button, FieldError, Input, Label } from '../../components/ui'
|
||||||
import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants'
|
import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants'
|
||||||
@@ -15,6 +17,8 @@ type GroupFormProps = {
|
|||||||
submitLabel: string
|
submitLabel: string
|
||||||
isSubmitting: boolean
|
isSubmitting: boolean
|
||||||
errorMessage?: string | null
|
errorMessage?: string | null
|
||||||
|
/** Una acción para salir del error (p. ej. volver a elegir el plan). */
|
||||||
|
errorAction?: ReactNode
|
||||||
/** Solo lo usa el onboarding: ahí el país ya se eligió en el paso anterior. */
|
/** Solo lo usa el onboarding: ahí el país ya se eligió en el paso anterior. */
|
||||||
country?: CountryCode
|
country?: CountryCode
|
||||||
onSubmit: (values: CreateFirstGroup) => void
|
onSubmit: (values: CreateFirstGroup) => void
|
||||||
@@ -27,7 +31,8 @@ export function GroupForm({
|
|||||||
submitLabel,
|
submitLabel,
|
||||||
isSubmitting,
|
isSubmitting,
|
||||||
errorMessage,
|
errorMessage,
|
||||||
country = DEFAULT_COUNTRY,
|
errorAction,
|
||||||
|
country,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
onBack,
|
onBack,
|
||||||
}: GroupFormProps) {
|
}: GroupFormProps) {
|
||||||
@@ -42,8 +47,13 @@ export function GroupForm({
|
|||||||
capacity: 10,
|
capacity: 10,
|
||||||
billingType: 'MONTHLY',
|
billingType: 'MONTHLY',
|
||||||
dueDay: 1,
|
dueDay: 1,
|
||||||
country,
|
country: country ?? DEFAULT_COUNTRY,
|
||||||
}
|
}
|
||||||
|
// Con país (onboarding) el símbolo sale de su moneda; sin país, del navegador,
|
||||||
|
// igual que el resto de los montos de la app.
|
||||||
|
const symbol = currencySymbol(country ? COUNTRY_CURRENCY[country] : undefined)
|
||||||
|
const daysLabelId = useId()
|
||||||
|
const billingLabelId = useId()
|
||||||
|
|
||||||
const {
|
const {
|
||||||
register,
|
register,
|
||||||
@@ -89,9 +99,13 @@ export function GroupForm({
|
|||||||
<FieldError message={errors.name?.message} />
|
<FieldError message={errors.name?.message} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<fieldset className="space-y-4">
|
||||||
|
<legend className="mb-3 text-base font-semibold text-primary">
|
||||||
|
{t('form.whenLegend')}
|
||||||
|
</legend>
|
||||||
<div>
|
<div>
|
||||||
<Label>{t('form.days')}</Label>
|
<Label id={daysLabelId}>{t('form.days')}</Label>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div role="group" aria-labelledby={daysLabelId} className="grid grid-cols-7 gap-1.5">
|
||||||
{WEEK_DAYS.map((value) => {
|
{WEEK_DAYS.map((value) => {
|
||||||
const isActive = days.includes(value)
|
const isActive = days.includes(value)
|
||||||
return (
|
return (
|
||||||
@@ -101,7 +115,7 @@ export function GroupForm({
|
|||||||
aria-pressed={isActive}
|
aria-pressed={isActive}
|
||||||
onClick={() => toggleDay(value)}
|
onClick={() => toggleDay(value)}
|
||||||
className={cn(
|
className={cn(
|
||||||
'h-9 rounded-full border px-3.5 text-sm font-medium transition-colors',
|
'h-11 rounded-xl border text-sm font-medium transition-colors',
|
||||||
isActive
|
isActive
|
||||||
? 'border-accent bg-accent text-on-accent'
|
? 'border-accent bg-accent text-on-accent'
|
||||||
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
: 'border-border bg-surface text-primary hover:bg-primary-soft',
|
||||||
@@ -126,7 +140,6 @@ export function GroupForm({
|
|||||||
<FieldError message={errors.time?.message} />
|
<FieldError message={errors.time?.message} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3">
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="capacity">{t('form.capacity')}</Label>
|
<Label htmlFor="capacity">{t('form.capacity')}</Label>
|
||||||
<Input
|
<Input
|
||||||
@@ -140,12 +153,18 @@ export function GroupForm({
|
|||||||
/>
|
/>
|
||||||
<FieldError message={errors.capacity?.message} />
|
<FieldError message={errors.capacity?.message} />
|
||||||
</div>
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset className="space-y-4">
|
||||||
|
<legend className="mb-3 text-base font-semibold text-primary">
|
||||||
|
{t('form.priceLegend')}
|
||||||
|
</legend>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="price">{t('form.price')}</Label>
|
<Label htmlFor="price">{t('form.price')}</Label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-base text-foreground/50 sm:text-sm">
|
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-base text-foreground/50 sm:text-sm">
|
||||||
$
|
{symbol}
|
||||||
</span>
|
</span>
|
||||||
<Input
|
<Input
|
||||||
id="price"
|
id="price"
|
||||||
@@ -154,18 +173,17 @@ export function GroupForm({
|
|||||||
min={0}
|
min={0}
|
||||||
step="0.01"
|
step="0.01"
|
||||||
placeholder={t('form.pricePlaceholder')}
|
placeholder={t('form.pricePlaceholder')}
|
||||||
className="pl-7"
|
className={symbol.length > 1 ? 'pl-10' : 'pl-7'}
|
||||||
invalid={!!errors.price}
|
invalid={!!errors.price}
|
||||||
{...register('price', { valueAsNumber: true })}
|
{...register('price', { valueAsNumber: true })}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<FieldError message={errors.price?.message} />
|
<FieldError message={errors.price?.message} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label>{t('form.billingType')}</Label>
|
<Label id={billingLabelId}>{t('form.billingType')}</Label>
|
||||||
<div className="grid grid-cols-2 gap-2">
|
<div role="group" aria-labelledby={billingLabelId} className="grid grid-cols-2 gap-2">
|
||||||
{BILLING_TYPES.map((value) => {
|
{BILLING_TYPES.map((value) => {
|
||||||
const isActive = billingType === value
|
const isActive = billingType === value
|
||||||
return (
|
return (
|
||||||
@@ -196,6 +214,9 @@ export function GroupForm({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* El vencimiento es de la cuota mensual: cobrando por clase no aplica (el
|
||||||
|
valor por default sigue en el form para que el esquema valide). */}
|
||||||
|
{billingType === 'MONTHLY' ? (
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor="dueDay">{t('form.dueDay')}</Label>
|
<Label htmlFor="dueDay">{t('form.dueDay')}</Label>
|
||||||
<Input
|
<Input
|
||||||
@@ -213,19 +234,24 @@ export function GroupForm({
|
|||||||
</p>
|
</p>
|
||||||
<FieldError message={errors.dueDay?.message} />
|
<FieldError message={errors.dueDay?.message} />
|
||||||
</div>
|
</div>
|
||||||
|
) : null}
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
{errorMessage ? (
|
{errorMessage ? (
|
||||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{errorMessage}</p>
|
<div role="alert" className="space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
|
<p>{errorMessage}</p>
|
||||||
|
{errorAction}
|
||||||
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
{onBack ? (
|
{onBack ? (
|
||||||
<Button variant="outline" onClick={onBack} disabled={isSubmitting}>
|
<Button variant="outline" size="lg" onClick={onBack} disabled={isSubmitting}>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
{t('common:actions.back')}
|
{t('common:actions.back')}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
<Button type="submit" variant="primary" className="flex-1" disabled={isSubmitting}>
|
<Button type="submit" variant="primary" size="lg" className="flex-1" disabled={isSubmitting}>
|
||||||
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
{isSubmitting ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
|
||||||
{isSubmitting ? t('form.submitting') : submitLabel}
|
{isSubmitting ? t('form.submitting') : submitLabel}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,80 +1,69 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import type { PendingPreRegistrations } from '@gruperly/shared'
|
import type { PendingPreRegistrations } from '@gruperly/shared'
|
||||||
import { CheckCircle2, ChevronRight, Inbox, Wallet } from 'lucide-react'
|
import { CheckCircle2, ChevronRight, Inbox, MessageCircle } from 'lucide-react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Avatar } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { getGroupsRiskOverview, getPayments } from '../../lib/api'
|
import { AlertTag } from '../attention/AlertTag'
|
||||||
import { absenceReason } from '../groups/card'
|
import { alertLabel, flaggedStudents, reminderMessage, whatsappLink } from '../attention/attention'
|
||||||
|
import { attentionQueryOptions } from '../attention/queries'
|
||||||
|
import { SeverityAvatar } from '../attention/SeverityAvatar'
|
||||||
|
|
||||||
/** How many at-risk people Home names; the rest is in each group's stats. */
|
/** Cuántas personas nombra el Inicio; el resto está a un toque, en "Requiere atención". */
|
||||||
const MAX_AT_RISK = 4
|
const MAX_STUDENTS = 4
|
||||||
|
|
||||||
/* "Para atender": what the teacher has to act on today, across all groups.
|
/* "Para atender": lo que el profe tiene que resolver, en todos sus grupos.
|
||||||
Nothing is computed here: the at-risk people are the high-risk `urgentes` of
|
Sale de la misma query que "Requiere atención" (`['attention']`), así las dos
|
||||||
`GET /groups-risk/overview` (same query key as the group list, so the cache
|
pantallas aplican la misma regla (`computeStudentAlerts`) y un "Resuelto" en
|
||||||
is shared), the overdue payments are just the total of the filtered list and
|
una se ve en la otra sin refetch. Las preinscripciones vienen con el resumen
|
||||||
the pending pre-registrations come with the Home summary. */
|
del Inicio y van primero: del otro lado alguien espera una respuesta. */
|
||||||
export function AttentionList({
|
export function AttentionList({
|
||||||
pendingPreRegistrations,
|
pendingPreRegistrations,
|
||||||
}: {
|
}: {
|
||||||
pendingPreRegistrations: PendingPreRegistrations[]
|
pendingPreRegistrations: PendingPreRegistrations[]
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation('home')
|
const { t } = useTranslation(['home', 'attention', 'common'])
|
||||||
const riskQuery = useQuery({
|
const attentionQuery = useQuery(attentionQueryOptions)
|
||||||
queryKey: ['groups-risk-overview'],
|
|
||||||
queryFn: getGroupsRiskOverview,
|
|
||||||
})
|
|
||||||
const overdueQuery = useQuery({
|
|
||||||
queryKey: ['payments', { page: 1, pageSize: 1, status: 'OVERDUE' }],
|
|
||||||
queryFn: () => getPayments({ page: 1, pageSize: 1, status: 'OVERDUE' }),
|
|
||||||
})
|
|
||||||
|
|
||||||
if (riskQuery.isPending || overdueQuery.isPending) return null
|
const students = flaggedStudents(attentionQuery.data)
|
||||||
// A failing secondary block shouldn't take Home down: it just isn't shown.
|
const shown = students.slice(0, MAX_STUDENTS)
|
||||||
if (riskQuery.isError && overdueQuery.isError) return null
|
const hidden = students.length - shown.length
|
||||||
|
const isEmpty = students.length === 0 && pendingPreRegistrations.length === 0
|
||||||
const groups = riskQuery.data?.items ?? []
|
|
||||||
const atRisk = groups
|
|
||||||
.flatMap((group) =>
|
|
||||||
group.urgentes
|
|
||||||
.filter((member) => member.level === 'riesgo_alto')
|
|
||||||
.map((member) => ({ ...member, groupId: group.groupId, groupName: group.groupName })),
|
|
||||||
)
|
|
||||||
.sort((a, b) => b.consecutiveAbsences - a.consecutiveAbsences)
|
|
||||||
const totalAtRisk = groups.reduce((total, group) => total + group.riesgoAlto, 0)
|
|
||||||
const overdue = overdueQuery.data?.pagination.total ?? 0
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<section aria-labelledby="home-attention-title">
|
||||||
<h2 className="text-lg font-bold text-primary">{t('attention.title')}</h2>
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
|
<h2 id="home-attention-title" className="text-lg font-bold text-primary">
|
||||||
|
{t('attention.title')}
|
||||||
|
</h2>
|
||||||
|
{students.length > 0 ? (
|
||||||
|
<Link
|
||||||
|
to="/groups/attention"
|
||||||
|
className="-my-2 inline-flex min-h-11 items-center text-sm font-medium text-accent-fg hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded-lg px-1"
|
||||||
|
>
|
||||||
|
{t('attention.seeAll')}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
{atRisk.length === 0 && overdue === 0 && pendingPreRegistrations.length === 0 ? (
|
{attentionQuery.isPending ? (
|
||||||
<p className="mt-3 flex items-center gap-2 rounded-xl border border-border bg-surface px-4 py-3 text-sm text-foreground/70">
|
// Reserva el lugar de dos filas: sin esto, la sección aparecía de golpe
|
||||||
|
// y empujaba los cobros.
|
||||||
|
<div aria-hidden="true" className="mt-3 h-[8.5rem] animate-pulse rounded-xl bg-primary-soft/60 motion-reduce:animate-none" />
|
||||||
|
) : attentionQuery.isError && pendingPreRegistrations.length === 0 ? (
|
||||||
|
<div role="alert" className="mt-3 flex items-center justify-between gap-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
|
<span>{t('attention.loadError')}</span>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => void attentionQuery.refetch()}>
|
||||||
|
{t('common:actions.retry')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : isEmpty ? (
|
||||||
|
<p className="mt-3 flex items-center gap-2.5 rounded-xl border border-border bg-surface px-4 py-3.5 text-sm text-foreground">
|
||||||
<CheckCircle2 className="size-4 shrink-0 text-success" aria-hidden="true" />
|
<CheckCircle2 className="size-4 shrink-0 text-success" aria-hidden="true" />
|
||||||
{t('attention.allGood')}
|
{t('attention.allGood')}
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<ul className="mt-3 divide-y divide-border overflow-hidden rounded-xl border border-border bg-surface">
|
<ul className="mt-3 divide-y divide-border overflow-hidden rounded-xl border border-border bg-surface">
|
||||||
{overdue > 0 ? (
|
|
||||||
<li>
|
|
||||||
<Link to="/payments" className={ROW_CLASS_NAME}>
|
|
||||||
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-danger-soft text-danger">
|
|
||||||
<Wallet className="size-5" aria-hidden="true" />
|
|
||||||
</span>
|
|
||||||
<span className="min-w-0 flex-1">
|
|
||||||
<span className="block text-sm font-semibold text-primary">
|
|
||||||
{t('attention.overdue', { count: overdue })}
|
|
||||||
</span>
|
|
||||||
<span className="block text-xs text-foreground/60">{t('attention.overdueHint')}</span>
|
|
||||||
</span>
|
|
||||||
<ChevronRight className="size-4 shrink-0 text-foreground/40" aria-hidden="true" />
|
|
||||||
</Link>
|
|
||||||
</li>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{/* Someone waiting for an answer goes before the at-risk list: it's
|
|
||||||
the only item where the other side is actively waiting. */}
|
|
||||||
{pendingPreRegistrations.map((group) => (
|
{pendingPreRegistrations.map((group) => (
|
||||||
<li key={group.groupId}>
|
<li key={group.groupId}>
|
||||||
<Link
|
<Link
|
||||||
@@ -83,57 +72,74 @@ export function AttentionList({
|
|||||||
search={{ section: 'pending' }}
|
search={{ section: 'pending' }}
|
||||||
className={ROW_CLASS_NAME}
|
className={ROW_CLASS_NAME}
|
||||||
>
|
>
|
||||||
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-accent-soft text-accent">
|
<span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-accent-soft text-accent-fg">
|
||||||
<Inbox className="size-5" aria-hidden="true" />
|
<Inbox className="size-5" aria-hidden="true" />
|
||||||
</span>
|
</span>
|
||||||
<span className="min-w-0 flex-1">
|
<span className="min-w-0 flex-1">
|
||||||
<span className="block text-sm font-semibold text-primary">
|
<span className="block text-sm font-semibold text-primary">
|
||||||
{t('attention.preRegistrations', { count: group.count })}
|
{t('attention.preRegistrations', { count: group.count })}
|
||||||
</span>
|
</span>
|
||||||
<span className="block truncate text-xs text-foreground/60">{group.groupName}</span>
|
<span className="block truncate text-xs text-foreground">{group.groupName}</span>
|
||||||
</span>
|
</span>
|
||||||
<ChevronRight className="size-4 shrink-0 text-foreground/40" aria-hidden="true" />
|
<ChevronRight className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||||
</Link>
|
</Link>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
{atRisk.slice(0, MAX_AT_RISK).map((member) => (
|
{shown.map((student) => {
|
||||||
<li key={member.attendeeId}>
|
const label = alertLabel(student.worst)
|
||||||
|
const isPayment = student.worst.tipo === 'pago'
|
||||||
|
const href = whatsappLink(student, isPayment ? reminderMessage(student) : undefined)
|
||||||
|
const action = isPayment ? t('attention:card.remind') : t('attention:card.contact')
|
||||||
|
return (
|
||||||
|
<li key={student.attendeeId} className="flex items-center">
|
||||||
<Link
|
<Link
|
||||||
to="/groups/$groupId/attendees/$attendeeId"
|
to="/groups/$groupId/attendees/$attendeeId"
|
||||||
params={{ groupId: member.groupId, attendeeId: member.attendeeId }}
|
params={{ groupId: student.groupId, attendeeId: student.attendeeId }}
|
||||||
className={ROW_CLASS_NAME}
|
className={`${ROW_CLASS_NAME} min-w-0 flex-1 pr-2`}
|
||||||
>
|
>
|
||||||
<Avatar name={member.fullName} className="size-10 rounded-full" />
|
<SeverityAvatar
|
||||||
|
name={student.fullName}
|
||||||
|
seed={student.attendeeId}
|
||||||
|
severity={student.worst.gravedad}
|
||||||
|
size="md"
|
||||||
|
/>
|
||||||
<span className="min-w-0 flex-1">
|
<span className="min-w-0 flex-1">
|
||||||
<span className="block truncate text-sm font-semibold text-primary">
|
<span className="block truncate text-sm font-semibold text-primary">{student.fullName}</span>
|
||||||
{member.fullName}
|
<span className="block truncate text-xs text-foreground">{student.groupName}</span>
|
||||||
</span>
|
</span>
|
||||||
<span className="block truncate text-xs text-foreground/60">
|
<AlertTag severity={student.worst.gravedad}>{label}</AlertTag>
|
||||||
{member.groupName}
|
|
||||||
{absenceReason(member) ? (
|
|
||||||
<>
|
|
||||||
{' · '}
|
|
||||||
<span className="text-danger">{absenceReason(member)}</span>
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
<ChevronRight className="size-4 shrink-0 text-foreground/40" aria-hidden="true" />
|
|
||||||
</Link>
|
</Link>
|
||||||
|
{/* El atajo del día a día: escribirle sin abrir la ficha. Va al
|
||||||
|
lado del link (no adentro) para no anidar controles. */}
|
||||||
|
{href ? (
|
||||||
|
<a
|
||||||
|
href={href}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
aria-label={t('attention:card.actionWhatsapp', { action, name: student.fullName })}
|
||||||
|
className="mr-2 flex size-11 shrink-0 items-center justify-center rounded-xl text-success transition-colors hover:bg-success-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
<MessageCircle className="size-5" aria-hidden="true" />
|
||||||
|
</a>
|
||||||
|
) : null}
|
||||||
</li>
|
</li>
|
||||||
))}
|
)
|
||||||
|
})}
|
||||||
|
|
||||||
{totalAtRisk > MAX_AT_RISK ? (
|
{hidden > 0 ? (
|
||||||
<li className="px-4 py-3 text-xs text-foreground/60">
|
<li>
|
||||||
{t('attention.moreAtRisk', { count: totalAtRisk - MAX_AT_RISK })}
|
<Link to="/groups/attention" className={`${ROW_CLASS_NAME} text-sm font-medium text-accent-fg`}>
|
||||||
|
<span className="flex-1">{t('attention.more', { count: hidden })}</span>
|
||||||
|
<ChevronRight className="size-4 shrink-0" aria-hidden="true" />
|
||||||
|
</Link>
|
||||||
</li>
|
</li>
|
||||||
) : null}
|
) : null}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</div>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const ROW_CLASS_NAME =
|
const ROW_CLASS_NAME =
|
||||||
'flex items-center gap-3 px-4 py-3 transition-colors hover:bg-primary-soft/50 active:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent'
|
'flex min-h-14 items-center gap-3 px-4 py-3 transition-colors hover:bg-primary-soft/50 active:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent'
|
||||||
|
|||||||
@@ -1,59 +1,59 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
import { useQuery } from '@tanstack/react-query'
|
||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { Loader2, Plus } from 'lucide-react'
|
import { Loader2, Plus } from 'lucide-react'
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { useAuth } from '../../context/AuthProvider'
|
import { useAuth } from '../../context/AuthProvider'
|
||||||
import { useIntlLocale } from '../../i18n'
|
import { useIntlLocale } from '../../i18n'
|
||||||
import { getClassesToday, getHomeSummary } from '../../lib/api'
|
import { getClassesToday, getHomeSummary } from '../../lib/api'
|
||||||
import { useMpStatus } from '../mp/useMpStatus'
|
|
||||||
import { AttentionList } from './AttentionList'
|
import { AttentionList } from './AttentionList'
|
||||||
import { SummaryStats } from './SummaryStats'
|
import { classState, planDay } from './day'
|
||||||
import { TodayClassCard } from './TodayClassCard'
|
|
||||||
import { NextClassHero } from './NextClassHero'
|
import { NextClassHero } from './NextClassHero'
|
||||||
import { UpcomingPaymentRow } from './UpcomingPaymentRow'
|
import { PaymentsSection } from './PaymentsSection'
|
||||||
|
import { TodayClassCard } from './TodayClassCard'
|
||||||
|
import { TodayClassRow } from './TodayClassRow'
|
||||||
|
|
||||||
|
/** Cada cuánto se recalcula qué clase va en el hero (una clase termina de estar
|
||||||
|
* "en curso" con la app abierta). */
|
||||||
|
const CLOCK_TICK_MS = 60_000
|
||||||
|
|
||||||
export function HomeView() {
|
export function HomeView() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { t } = useTranslation(['home', 'common'])
|
const { t } = useTranslation(['home', 'common'])
|
||||||
const locale = useIntlLocale()
|
const locale = useIntlLocale()
|
||||||
const { user } = useAuth()
|
const { user } = useAuth()
|
||||||
const mpStatusQuery = useMpStatus()
|
|
||||||
const firstName = user?.name?.trim().split(/\s+/)[0]
|
const firstName = user?.name?.trim().split(/\s+/)[0]
|
||||||
// "martes 27 de octubre": the date anchors "Clase de hoy" and the due dates below.
|
const now = useNow(CLOCK_TICK_MS)
|
||||||
const today = new Date().toLocaleDateString(locale, {
|
// "jueves, 5 de noviembre": ancla la clase de hoy y los vencimientos de abajo.
|
||||||
weekday: 'long',
|
const today = now.toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long' })
|
||||||
day: 'numeric',
|
|
||||||
month: 'long',
|
const summaryQuery = useQuery({ queryKey: ['home-summary'], queryFn: getHomeSummary })
|
||||||
})
|
|
||||||
const summaryQuery = useQuery({
|
|
||||||
queryKey: ['home-summary'],
|
|
||||||
queryFn: getHomeSummary,
|
|
||||||
})
|
|
||||||
const classesTodayQuery = useQuery({
|
const classesTodayQuery = useQuery({
|
||||||
queryKey: ['classes-today'],
|
queryKey: ['classes-today'],
|
||||||
queryFn: getClassesToday,
|
queryFn: getClassesToday,
|
||||||
staleTime: 60_000,
|
staleTime: 60_000,
|
||||||
})
|
})
|
||||||
const todayClasses = classesTodayQuery.data?.data ?? []
|
const { hero, rest } = planDay(classesTodayQuery.data?.data ?? [], now)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
<div>
|
<header>
|
||||||
<p className="text-sm font-medium first-letter:uppercase text-foreground/60">{today}</p>
|
<p className="text-sm font-medium text-foreground first-letter:uppercase">{today}</p>
|
||||||
<h1 className="mt-1 text-2xl font-bold text-primary">
|
<h1 className="mt-1 text-2xl font-bold text-primary">
|
||||||
{firstName ? t('greetingName', { name: firstName }) : t('greeting')}
|
{firstName ? t('greetingName', { name: firstName }) : t('greeting')}
|
||||||
</h1>
|
</h1>
|
||||||
</div>
|
</header>
|
||||||
|
|
||||||
{summaryQuery.isPending ? (
|
{summaryQuery.isPending ? (
|
||||||
<div className="mt-8 flex items-center justify-center py-16">
|
<div role="status" className="mt-8 flex items-center justify-center py-16">
|
||||||
<Loader2 className="size-6 animate-spin text-foreground/40" />
|
<Loader2 className="size-6 animate-spin text-foreground" aria-hidden="true" />
|
||||||
|
<span className="sr-only">{t('loading')}</span>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{summaryQuery.isError ? (
|
{summaryQuery.isError ? (
|
||||||
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<div role="alert" className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
<p>{t('loadError')}</p>
|
<p>{t('loadError')}</p>
|
||||||
<Button variant="outline" size="sm" onClick={() => void summaryQuery.refetch()}>
|
<Button variant="outline" size="sm" onClick={() => void summaryQuery.refetch()}>
|
||||||
{t('common:actions.retry')}
|
{t('common:actions.retry')}
|
||||||
@@ -62,79 +62,69 @@ export function HomeView() {
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{summaryQuery.isSuccess && summaryQuery.data.stats.groups === 0 ? (
|
{summaryQuery.isSuccess && summaryQuery.data.stats.groups === 0 ? (
|
||||||
<div className="mt-8 rounded-xl border border-dashed border-border bg-surface px-4 py-12 text-center">
|
<div className="mt-8 rounded-2xl border border-border bg-surface px-4 py-10 text-center">
|
||||||
<p className="font-medium text-primary">{t('empty.title')}</p>
|
<p className="font-semibold text-primary">{t('empty.title')}</p>
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
<p className="mt-1 text-sm text-foreground">{t('empty.description')}</p>
|
||||||
{t('empty.description')}
|
<Button variant="primary" size="lg" className="mt-5" onClick={() => void navigate({ to: '/groups/new' })}>
|
||||||
</p>
|
<Plus className="size-4" aria-hidden="true" />
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
className="mt-5"
|
|
||||||
onClick={() => void navigate({ to: '/groups/new' })}
|
|
||||||
>
|
|
||||||
<Plus className="size-4" />
|
|
||||||
{t('empty.cta')}
|
{t('empty.cta')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{summaryQuery.isSuccess && summaryQuery.data.stats.groups > 0 ? (
|
{summaryQuery.isSuccess && summaryQuery.data.stats.groups > 0 ? (
|
||||||
<div className="mt-6 space-y-6">
|
// En desktop, dos columnas: el día a la izquierda y lo pendiente a la
|
||||||
{todayClasses.length > 0 ? (
|
// derecha. En mobile, el mismo orden de arriba abajo.
|
||||||
<div className="space-y-3">
|
<div className="mt-6 grid grid-cols-[minmax(0,1fr)] gap-8 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] lg:items-start lg:gap-10">
|
||||||
{todayClasses.map((classItem) => (
|
<div className="space-y-4">
|
||||||
<TodayClassCard key={classItem.sessionId} item={classItem} />
|
{classesTodayQuery.isError ? (
|
||||||
))}
|
<div role="alert" className="flex items-center justify-between gap-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
</div>
|
<span>{t('today.loadError')}</span>
|
||||||
) : summaryQuery.data.nextClass ? (
|
<Button variant="outline" size="sm" onClick={() => void classesTodayQuery.refetch()}>
|
||||||
<NextClassHero nextClass={summaryQuery.data.nextClass} />
|
{t('common:actions.retry')}
|
||||||
) : (
|
|
||||||
<div className="rounded-xl border border-dashed border-border bg-surface px-4 py-8 text-center">
|
|
||||||
<p className="text-sm font-medium text-primary">{t('noClasses.title')}</p>
|
|
||||||
<p className="mt-1 text-sm text-foreground/60">
|
|
||||||
{t('noClasses.description')}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<SummaryStats summary={summaryQuery.data} />
|
|
||||||
|
|
||||||
<AttentionList pendingPreRegistrations={summaryQuery.data.pendingPreRegistrations} />
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<div className="flex items-center justify-between gap-3">
|
|
||||||
<h2 className="text-lg font-bold text-primary">{t('upcoming.title')}</h2>
|
|
||||||
<Button variant="ghost" size="sm" onClick={() => void navigate({ to: '/payments' })}>
|
|
||||||
{t('upcoming.seeAll')}
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
) : hero ? (
|
||||||
|
<TodayClassCard item={hero} state={classState(hero, now)} />
|
||||||
|
) : summaryQuery.data.nextClass ? (
|
||||||
|
<NextClassHero nextClass={summaryQuery.data.nextClass} />
|
||||||
|
) : classesTodayQuery.isSuccess && rest.length === 0 ? (
|
||||||
|
<div className="rounded-2xl border border-border bg-surface px-4 py-6">
|
||||||
|
<p className="text-sm font-semibold text-primary">{t('noClasses.title')}</p>
|
||||||
|
<p className="mt-1 text-sm text-foreground">{t('noClasses.description')}</p>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{summaryQuery.data.upcomingPayments.length > 0 ? (
|
{rest.length > 0 ? (
|
||||||
<ul className="mt-3 space-y-3">
|
<section aria-labelledby="home-today-title">
|
||||||
{summaryQuery.data.upcomingPayments.map((payment) => (
|
<h2 id="home-today-title" className="text-sm font-semibold text-primary">
|
||||||
<UpcomingPaymentRow key={payment.id} payment={payment} />
|
{t('today.listTitle')}
|
||||||
|
</h2>
|
||||||
|
<ul className="mt-2 divide-y divide-border overflow-hidden rounded-xl border border-border bg-surface">
|
||||||
|
{rest.map((item) => (
|
||||||
|
<TodayClassRow key={item.sessionId} item={item} state={classState(item, now)} />
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
) : (
|
</section>
|
||||||
<div className="mt-3 rounded-xl border border-dashed border-border bg-surface px-4 py-6 text-center text-sm text-foreground/60">
|
) : null}
|
||||||
<p>{t('upcoming.empty')}</p>
|
|
||||||
{/* The empty state says how to get out of it: without Mercado
|
|
||||||
Pago there is no way to create payment links. */}
|
|
||||||
{mpStatusQuery.data && mpStatusQuery.data.status !== 'active' ? (
|
|
||||||
<Link
|
|
||||||
to="/settings"
|
|
||||||
className="mt-2 inline-block font-medium text-accent hover:underline"
|
|
||||||
>
|
|
||||||
{t('upcoming.linkMp')}
|
|
||||||
</Link>
|
|
||||||
) : (
|
|
||||||
<p className="mt-1 text-xs">{t('upcoming.hint')}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
<div className="space-y-8">
|
||||||
|
<AttentionList pendingPreRegistrations={summaryQuery.data.pendingPreRegistrations} />
|
||||||
|
<PaymentsSection summary={summaryQuery.data} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** La hora actual, refrescada cada `intervalMs`. */
|
||||||
|
function useNow(intervalMs: number): Date {
|
||||||
|
const [now, setNow] = useState(() => new Date())
|
||||||
|
useEffect(() => {
|
||||||
|
const id = window.setInterval(() => setNow(new Date()), intervalMs)
|
||||||
|
return () => window.clearInterval(id)
|
||||||
|
}, [intervalMs])
|
||||||
|
return now
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,45 +1,37 @@
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import type { NextClassDto } from '@gruperly/shared'
|
import type { NextClassDto } from '@gruperly/shared'
|
||||||
import { CalendarClock } from 'lucide-react'
|
import { ChevronRight } from 'lucide-react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { Badge } from '../../components/ui'
|
||||||
import { formatRelativeDateTime, formatSchedule } from '../../lib/format'
|
import { formatRelativeDateTime, formatSchedule } from '../../lib/format'
|
||||||
|
|
||||||
|
/** El hero cuando hoy ya no queda ninguna clase por dar: la próxima, sea cuando sea. */
|
||||||
export function NextClassHero({ nextClass }: { nextClass: NextClassDto }) {
|
export function NextClassHero({ nextClass }: { nextClass: NextClassDto }) {
|
||||||
const navigate = useNavigate()
|
|
||||||
const { t } = useTranslation('home')
|
const { t } = useTranslation('home')
|
||||||
const hasSchedule = (nextClass.days?.length ?? 0) > 0
|
const hasSchedule = (nextClass.days?.length ?? 0) > 0
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<article className="relative overflow-hidden rounded-xl border border-accent/30 bg-surface p-5">
|
<Link
|
||||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
|
to="/groups/$groupId"
|
||||||
<div className="min-w-0">
|
params={{ groupId: nextClass.groupId }}
|
||||||
<p className="text-xs font-medium uppercase tracking-wide text-foreground/50">
|
className="group block rounded-2xl border border-border bg-surface p-5 transition-colors hover:border-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
{nextClass.isNow ? t('nextClass.now') : t('nextClass.next')}
|
>
|
||||||
</p>
|
<div className="flex items-start justify-between gap-3">
|
||||||
<h2 className="mt-1 truncate text-xl font-bold text-primary">{nextClass.name}</h2>
|
<h2 className="min-w-0 truncate text-xl font-bold text-primary">{nextClass.name}</h2>
|
||||||
{hasSchedule ? (
|
<ChevronRight
|
||||||
<div className="mt-2 flex items-center gap-2 text-sm text-foreground/70">
|
className="mt-1 size-5 shrink-0 text-foreground transition-transform group-hover:translate-x-0.5 motion-reduce:transition-none"
|
||||||
<CalendarClock className="size-4 shrink-0 text-accent" />
|
aria-hidden="true"
|
||||||
<span>{formatSchedule(nextClass.days ?? [], nextClass.time)}</span>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
<p className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[0.9375rem] font-medium text-primary">
|
||||||
</div>
|
<span>{nextClass.isNow ? t('nextClass.now') : t('nextClass.next')}</span>
|
||||||
<div className="flex shrink-0 items-center gap-2">
|
|
||||||
<Badge variant={nextClass.isNow ? 'success' : 'neutral'}>
|
<Badge variant={nextClass.isNow ? 'success' : 'neutral'}>
|
||||||
{nextClass.isNow ? t('nextClass.nowBadge') : formatRelativeDateTime(nextClass.occurrenceAt)}
|
{nextClass.isNow ? t('nextClass.nowBadge') : formatRelativeDateTime(nextClass.occurrenceAt)}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</p>
|
||||||
</div>
|
{hasSchedule ? (
|
||||||
<div className="mt-4 flex justify-end border-t border-border pt-3">
|
<p className="mt-1 text-sm text-foreground">{formatSchedule(nextClass.days ?? [], nextClass.time)}</p>
|
||||||
<Button
|
) : null}
|
||||||
variant="outline"
|
</Link>
|
||||||
size="sm"
|
|
||||||
onClick={() => void navigate({ to: `/groups/${nextClass.groupId}` })}
|
|
||||||
>
|
|
||||||
{t('nextClass.seeGroup')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</article>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
111
apps/web/src/features/home/PaymentsSection.tsx
Normal file
111
apps/web/src/features/home/PaymentsSection.tsx
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import type { HomeSummaryDto } from '@gruperly/shared'
|
||||||
|
import { Lock, Sparkles } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { useBillingStatus } from '../billing/useBillingStatus'
|
||||||
|
import { useMpStatus } from '../mp/useMpStatus'
|
||||||
|
import { formatPrice } from '../../lib/format'
|
||||||
|
import { UpcomingPaymentRow } from './UpcomingPaymentRow'
|
||||||
|
|
||||||
|
/* Filas de muestra de la vista previa de Free: nombres y montos de ejemplo, en
|
||||||
|
la moneda que formatea el navegador. Nunca son datos del profe. */
|
||||||
|
const TEASER_ROWS = [
|
||||||
|
{ name: 'teaser.sample1', amount: 15000 },
|
||||||
|
{ name: 'teaser.sample2', amount: 15000 },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Próximos cobros". Con un plan que cobra por Mercado Pago muestra los cobros
|
||||||
|
* y lo que queda por cobrar; sin él (Free), una vista previa bloqueada de cómo
|
||||||
|
* se vería, con el paso a Pro. Nunca ofrece vincular Mercado Pago a quien no
|
||||||
|
* puede cobrar con él.
|
||||||
|
*/
|
||||||
|
export function PaymentsSection({ summary }: { summary: HomeSummaryDto }) {
|
||||||
|
const { t } = useTranslation('home')
|
||||||
|
const billingQuery = useBillingStatus()
|
||||||
|
const mpStatusQuery = useMpStatus()
|
||||||
|
// Mientras no se sabe el plan no se decide nada: ni cobros ni vista previa.
|
||||||
|
if (billingQuery.isPending) return null
|
||||||
|
|
||||||
|
// Sin enforcement (o si el estado del plan no cargó) todo es Pro: se muestran
|
||||||
|
// los cobros, como hasta ahora.
|
||||||
|
const billing = billingQuery.data
|
||||||
|
const canCharge = !billing || !billing.enforced || billing.limits.mpCharges
|
||||||
|
const { pendingAmount, pendingPayments } = summary.stats
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section aria-labelledby="home-payments-title">
|
||||||
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
|
<h2 id="home-payments-title" className="text-lg font-bold text-primary">
|
||||||
|
{t('upcoming.title')}
|
||||||
|
</h2>
|
||||||
|
{canCharge ? (
|
||||||
|
<Link
|
||||||
|
to="/payments"
|
||||||
|
className="-my-2 inline-flex min-h-11 items-center rounded-lg px-1 text-sm font-medium text-accent-fg hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
{t('upcoming.seeAll')}
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!canCharge ? (
|
||||||
|
<div className="relative mt-3 overflow-hidden rounded-xl border border-border bg-surface">
|
||||||
|
<ul aria-hidden="true" className="divide-y divide-border opacity-50 blur-[1.5px] select-none">
|
||||||
|
{TEASER_ROWS.map((row) => (
|
||||||
|
<li key={row.name} className="flex items-center justify-between gap-3 px-4 py-3">
|
||||||
|
<span className="text-sm font-semibold text-primary">{t(row.name)}</span>
|
||||||
|
<span className="text-sm font-semibold tabular-nums text-primary">{formatPrice(row.amount)}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<div className="border-t border-border px-4 py-4">
|
||||||
|
<p className="flex items-start gap-2 text-sm text-primary">
|
||||||
|
<Lock className="mt-0.5 size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||||
|
{t('teaser.description')}
|
||||||
|
</p>
|
||||||
|
<Link
|
||||||
|
to="/billing"
|
||||||
|
className="mt-3 inline-flex h-11 items-center gap-2 rounded-xl bg-accent-soft px-4 text-sm font-semibold text-accent-fg transition-colors hover:bg-accent/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
<Sparkles className="size-4" aria-hidden="true" />
|
||||||
|
{t('teaser.cta')}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{pendingPayments > 0 ? (
|
||||||
|
<p className="mt-1 text-sm text-foreground">
|
||||||
|
{t('upcoming.pending', { amount: formatPrice(pendingAmount), count: pendingPayments })}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{summary.upcomingPayments.length > 0 ? (
|
||||||
|
<ul className="mt-3 divide-y divide-border overflow-hidden rounded-xl border border-border bg-surface">
|
||||||
|
{summary.upcomingPayments.map((payment) => (
|
||||||
|
<UpcomingPaymentRow key={payment.id} payment={payment} />
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<div className="mt-3 rounded-xl border border-border bg-surface px-4 py-4 text-sm">
|
||||||
|
<p className="font-medium text-primary">{t('upcoming.empty')}</p>
|
||||||
|
{/* El vacío dice cómo salir de él: sin Mercado Pago vinculado no
|
||||||
|
hay cómo crear links de cobro. */}
|
||||||
|
{mpStatusQuery.data && mpStatusQuery.data.status !== 'active' ? (
|
||||||
|
<Link
|
||||||
|
to="/settings"
|
||||||
|
className="mt-1 inline-flex min-h-11 items-center font-medium text-accent-fg hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent rounded-lg"
|
||||||
|
>
|
||||||
|
{t('upcoming.linkMp')}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<p className="mt-0.5 text-foreground">{t('upcoming.hint')}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
|
||||||
import type { HomeSummaryDto } from '@gruperly/shared'
|
|
||||||
import { UserCheck, Users, Wallet, type LucideIcon } from 'lucide-react'
|
|
||||||
import { useTranslation } from 'react-i18next'
|
|
||||||
import { cn } from '../../lib/utils'
|
|
||||||
import { formatPrice } from '../../lib/format'
|
|
||||||
|
|
||||||
type StatTarget = '/groups' | '/payments'
|
|
||||||
|
|
||||||
/* Three compact tiles in a row, also on mobile: they are reference numbers, not
|
|
||||||
the protagonists of the screen, and stacked they pushed "Próximos cobros"
|
|
||||||
below the fold. The value always goes with its label: the old tile swapped
|
|
||||||
the label for a sub-line and read "0 / 0 por cobrar". */
|
|
||||||
export function SummaryStats({ summary }: { summary: HomeSummaryDto }) {
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { t } = useTranslation('home')
|
|
||||||
const { pendingAmount, pendingPayments } = summary.stats
|
|
||||||
const stats: {
|
|
||||||
label: string
|
|
||||||
value: string
|
|
||||||
icon: LucideIcon
|
|
||||||
to: StatTarget
|
|
||||||
}[] = [
|
|
||||||
{
|
|
||||||
label: t('stats.groups', { count: summary.stats.groups }),
|
|
||||||
value: String(summary.stats.groups),
|
|
||||||
icon: Users,
|
|
||||||
to: '/groups',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: pendingPayments > 0 ? t('stats.toCollectCount', { count: pendingPayments }) : t('stats.toCollect'),
|
|
||||||
value: formatPrice(pendingAmount),
|
|
||||||
icon: Wallet,
|
|
||||||
to: '/payments',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: t('stats.students', { count: summary.stats.attendees }),
|
|
||||||
value: String(summary.stats.attendees),
|
|
||||||
icon: UserCheck,
|
|
||||||
to: '/groups',
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="grid grid-cols-3 gap-2 sm:gap-4">
|
|
||||||
{stats.map((stat) => {
|
|
||||||
const Icon = stat.icon
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={stat.to + stat.label}
|
|
||||||
type="button"
|
|
||||||
onClick={() => void navigate({ to: stat.to })}
|
|
||||||
className={cn(
|
|
||||||
'flex min-w-0 flex-col items-start gap-2 rounded-xl border border-border bg-surface p-3 text-left transition-all sm:flex-row sm:items-center sm:gap-3 sm:p-4',
|
|
||||||
'hover:border-accent/40 active:scale-[0.98] motion-reduce:active:scale-100',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-accent-soft text-accent sm:size-10">
|
|
||||||
<Icon className="size-4 sm:size-5" />
|
|
||||||
</span>
|
|
||||||
<span className="min-w-0 max-w-full">
|
|
||||||
<span className="block truncate text-lg font-bold leading-tight text-primary tabular-nums sm:text-xl">
|
|
||||||
{stat.value}
|
|
||||||
</span>
|
|
||||||
<span className="block truncate text-xs text-foreground/60">{stat.label}</span>
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,53 +1,56 @@
|
|||||||
import { Link, useNavigate } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import type { ClassTodayDto } from '@gruperly/shared'
|
import type { ClassTodayDto } from '@gruperly/shared'
|
||||||
import { CalendarClock, ChevronRight, ClipboardCheck } from 'lucide-react'
|
import { ChevronRight, ClipboardCheck } from 'lucide-react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { Badge } from '../../components/ui'
|
||||||
import { useIntlLocale } from '../../i18n'
|
import { useIntlLocale } from '../../i18n'
|
||||||
|
import { formatClockTime } from '../../lib/format'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
import type { ClassState } from './day'
|
||||||
|
|
||||||
export function TodayClassCard({ item }: { item: ClassTodayDto }) {
|
/** El hero del Inicio: la clase en curso o la próxima de hoy. */
|
||||||
const navigate = useNavigate()
|
export function TodayClassCard({ item, state }: { item: ClassTodayDto; state: ClassState }) {
|
||||||
const { t } = useTranslation('home')
|
const { t } = useTranslation('home')
|
||||||
const locale = useIntlLocale()
|
const locale = useIntlLocale()
|
||||||
const time = new Date(item.startsAt).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
|
const time = formatClockTime(item.startsAt, locale)
|
||||||
|
const isLive = state === 'live'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<article className="relative overflow-hidden rounded-xl border border-accent/30 bg-surface p-5">
|
<article className="rounded-2xl border border-accent/30 bg-surface p-5">
|
||||||
<div className="flex items-start justify-between gap-3">
|
<div className="flex items-start justify-between gap-3">
|
||||||
<p className="text-xs font-medium uppercase tracking-wide text-foreground/50">
|
|
||||||
{t('today.label')}
|
|
||||||
</p>
|
|
||||||
{/* Only the done state earns a badge: "Por tomar" repeated what the
|
|
||||||
button below already says. */}
|
|
||||||
{item.hasAttendance ? <Badge variant="success">{t('today.attendanceTaken')}</Badge> : null}
|
|
||||||
</div>
|
|
||||||
<Link
|
<Link
|
||||||
to="/groups/$groupId"
|
to="/groups/$groupId"
|
||||||
params={{ groupId: item.groupId }}
|
params={{ groupId: item.groupId }}
|
||||||
className="group mt-1 flex items-center gap-1 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
className="group -m-1 flex min-w-0 items-center gap-1 rounded-lg p-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent"
|
||||||
>
|
>
|
||||||
<h2 className="truncate text-xl font-bold text-primary">{item.groupName}</h2>
|
<h2 className="truncate text-xl font-bold text-primary">{item.groupName}</h2>
|
||||||
<ChevronRight
|
<ChevronRight
|
||||||
className="size-5 shrink-0 text-foreground/40 transition-transform group-hover:translate-x-0.5"
|
className="size-5 shrink-0 text-foreground transition-transform group-hover:translate-x-0.5 motion-reduce:transition-none"
|
||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
/>
|
/>
|
||||||
</Link>
|
</Link>
|
||||||
<div className="mt-2 flex items-center gap-2 text-sm text-foreground/70">
|
{isLive ? <Badge variant="success">{t('today.live')}</Badge> : null}
|
||||||
<CalendarClock className="size-4 shrink-0 text-accent" />
|
|
||||||
<span>{t('today.time', { time })}</span>
|
|
||||||
</div>
|
</div>
|
||||||
<p className="mt-1 text-xs text-foreground/60">
|
|
||||||
|
<p className="mt-1.5 text-[0.9375rem] font-medium tabular-nums text-primary">
|
||||||
|
{t('today.time', { time })}
|
||||||
|
</p>
|
||||||
|
<p className="mt-0.5 text-sm text-foreground">
|
||||||
{t('today.enrolled', { count: item.enrolledCount })}
|
{t('today.enrolled', { count: item.enrolledCount })}
|
||||||
{item.availableSlots != null ? ` · ${t('today.slots', { count: item.availableSlots })}` : ''}
|
{item.availableSlots != null ? ` · ${t('today.slots', { count: item.availableSlots })}` : ''}
|
||||||
</p>
|
</p>
|
||||||
<Button
|
|
||||||
variant={item.hasAttendance ? 'outline' : 'primary'}
|
<Link
|
||||||
className="mt-4 w-full"
|
to="/class/$sessionId/attendance"
|
||||||
onClick={() => void navigate({ to: `/class/${item.sessionId}/attendance` })}
|
params={{ sessionId: item.sessionId }}
|
||||||
|
className={cn(
|
||||||
|
'mt-4 inline-flex h-12 w-full items-center justify-center gap-2 rounded-xl px-5 text-sm font-medium transition-[background-color,transform] duration-150 ease-out active:scale-[0.96] motion-reduce:active:scale-100',
|
||||||
|
'bg-accent text-on-accent hover:bg-accent-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2 focus-visible:ring-offset-surface',
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
<ClipboardCheck className="size-4" />
|
<ClipboardCheck className="size-4" aria-hidden="true" />
|
||||||
{item.hasAttendance ? t('today.seeAttendance') : t('today.takeAttendance')}
|
{t('today.takeAttendance')}
|
||||||
</Button>
|
</Link>
|
||||||
</article>
|
</article>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
41
apps/web/src/features/home/TodayClassRow.tsx
Normal file
41
apps/web/src/features/home/TodayClassRow.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import type { ClassTodayDto } from '@gruperly/shared'
|
||||||
|
import { Check, ChevronRight } from 'lucide-react'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { useIntlLocale } from '../../i18n'
|
||||||
|
import { formatClockTime } from '../../lib/format'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
import type { ClassState } from './day'
|
||||||
|
|
||||||
|
/** Una clase del día fuera del hero: hora, grupo y en qué quedó la asistencia. */
|
||||||
|
export function TodayClassRow({ item, state }: { item: ClassTodayDto; state: ClassState }) {
|
||||||
|
const { t } = useTranslation('home')
|
||||||
|
const locale = useIntlLocale()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li>
|
||||||
|
<Link
|
||||||
|
to="/class/$sessionId/attendance"
|
||||||
|
params={{ sessionId: item.sessionId }}
|
||||||
|
className="flex min-h-14 items-center gap-3 px-4 py-2.5 transition-colors hover:bg-primary-soft/50 active:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
<span className="w-12 shrink-0 text-sm font-semibold tabular-nums text-primary">
|
||||||
|
{formatClockTime(item.startsAt, locale)}
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-sm font-medium text-primary">{item.groupName}</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'flex shrink-0 items-center gap-1 text-xs font-medium',
|
||||||
|
state === 'taken' && 'text-success',
|
||||||
|
state === 'missed' && 'text-accent-fg',
|
||||||
|
(state === 'upcoming' || state === 'live') && 'text-foreground',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{state === 'taken' ? <Check className="size-3.5" aria-hidden="true" /> : null}
|
||||||
|
{t(`today.state.${state}`)}
|
||||||
|
</span>
|
||||||
|
<ChevronRight className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
import type { UpcomingPaymentDto } from '@gruperly/shared'
|
import type { UpcomingPaymentDto } from '@gruperly/shared'
|
||||||
|
import { ChevronRight } from 'lucide-react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { Badge } from '../../components/ui'
|
import { Badge } from '../../components/ui'
|
||||||
import { formatPrice, formatRelativeDateTime, paymentStatusLabel } from '../../lib/format'
|
import { formatPrice, formatRelativeDateTime, paymentStatusLabel } from '../../lib/format'
|
||||||
@@ -8,19 +10,25 @@ export function UpcomingPaymentRow({ payment }: { payment: UpcomingPaymentDto })
|
|||||||
// Re-render on language change: the labels come from lib/format.
|
// Re-render on language change: the labels come from lib/format.
|
||||||
useTranslation()
|
useTranslation()
|
||||||
return (
|
return (
|
||||||
<li className="flex items-center justify-between gap-3 rounded-xl border border-border bg-surface px-4 py-3">
|
<li>
|
||||||
<div className="min-w-0">
|
<Link
|
||||||
<p className="truncate text-sm font-semibold text-primary">{payment.attendeeName}</p>
|
to="/payments"
|
||||||
<p className="mt-0.5 truncate text-xs text-foreground/60">
|
className="flex min-h-14 items-center gap-3 px-4 py-3 transition-colors hover:bg-primary-soft/50 active:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent"
|
||||||
|
>
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className="block truncate text-sm font-semibold text-primary">{payment.attendeeName}</span>
|
||||||
|
<span className="mt-0.5 block truncate text-xs text-foreground">
|
||||||
{payment.groupName} · {formatRelativeDateTime(payment.dueDate)}
|
{payment.groupName} · {formatRelativeDateTime(payment.dueDate)}
|
||||||
</p>
|
</span>
|
||||||
</div>
|
</span>
|
||||||
<div className="flex shrink-0 items-center gap-2">
|
<span className="flex shrink-0 items-center gap-2">
|
||||||
<span className="text-sm font-semibold text-primary">{formatPrice(payment.amount)}</span>
|
<span className="text-sm font-semibold tabular-nums text-primary">
|
||||||
<Badge variant={PAYMENT_BADGE_VARIANT[payment.status]}>
|
{formatPrice(payment.amount, payment.currency)}
|
||||||
{paymentStatusLabel(payment.status)}
|
</span>
|
||||||
</Badge>
|
<Badge variant={PAYMENT_BADGE_VARIANT[payment.status]}>{paymentStatusLabel(payment.status)}</Badge>
|
||||||
</div>
|
</span>
|
||||||
|
<ChevronRight className="size-4 shrink-0 text-foreground" aria-hidden="true" />
|
||||||
|
</Link>
|
||||||
</li>
|
</li>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
41
apps/web/src/features/home/day.ts
Normal file
41
apps/web/src/features/home/day.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import type { ClassTodayDto } from '@gruperly/shared'
|
||||||
|
|
||||||
|
/* El día del profe, como funciones puras: qué clase va en el hero y en qué
|
||||||
|
estado está cada una. `HomeView` las usa y `test/home-day.test.ts` las cubre. */
|
||||||
|
|
||||||
|
/** Cuánto después del inicio una clase sin asistencia sigue siendo "la de
|
||||||
|
* ahora". Pasado eso, deja el hero a la próxima y queda en la lista del día
|
||||||
|
* como pendiente. */
|
||||||
|
export const CLASS_ACTIVE_WINDOW_MS = 2 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
export type ClassState =
|
||||||
|
/** La asistencia ya está tomada. */
|
||||||
|
| 'taken'
|
||||||
|
/** Empezó hace menos de `CLASS_ACTIVE_WINDOW_MS` y falta la asistencia. */
|
||||||
|
| 'live'
|
||||||
|
/** Todavía no empezó. */
|
||||||
|
| 'upcoming'
|
||||||
|
/** Ya pasó y nadie tomó asistencia: un olvido, se ofrece tomarla igual. */
|
||||||
|
| 'missed'
|
||||||
|
|
||||||
|
export function classState(item: ClassTodayDto, now: Date): ClassState {
|
||||||
|
if (item.hasAttendance) return 'taken'
|
||||||
|
const startsAt = new Date(item.startsAt).getTime()
|
||||||
|
if (startsAt > now.getTime()) return 'upcoming'
|
||||||
|
return now.getTime() - startsAt <= CLASS_ACTIVE_WINDOW_MS ? 'live' : 'missed'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El hero es la clase en curso o la próxima de hoy que todavía no tiene
|
||||||
|
* asistencia. El resto del día va en filas compactas, en orden. Sin hero, el
|
||||||
|
* Inicio muestra la próxima clase (que puede ser de otro día).
|
||||||
|
*/
|
||||||
|
export function planDay(classes: readonly ClassTodayDto[], now: Date) {
|
||||||
|
const sorted = [...classes].sort((a, b) => a.startsAt.localeCompare(b.startsAt))
|
||||||
|
const hero =
|
||||||
|
sorted.find((item) => {
|
||||||
|
const state = classState(item, now)
|
||||||
|
return state === 'live' || state === 'upcoming'
|
||||||
|
}) ?? null
|
||||||
|
return { hero, rest: sorted.filter((item) => item !== hero) }
|
||||||
|
}
|
||||||
@@ -1,120 +1,167 @@
|
|||||||
import type { OnboardingGroupDto } from '@gruperly/shared'
|
import type { OnboardingGroupDto } from '@gruperly/shared'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { COUNTRY_CURRENCY } from '@gruperly/shared'
|
||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { ArrowRight, CheckCircle2, CreditCard, MessageCircle, Sparkles } from 'lucide-react'
|
import { ArrowRight, Copy, Loader2, Send } from 'lucide-react'
|
||||||
import { Badge, Button } from '../../components/ui'
|
import { Trans, useTranslation } from 'react-i18next'
|
||||||
|
import { Button, useToast } from '../../components/ui'
|
||||||
import { useAuth } from '../../context/AuthProvider'
|
import { useAuth } from '../../context/AuthProvider'
|
||||||
|
import { useIntlLocale } from '../../i18n'
|
||||||
|
import { getInviteToken } from '../../lib/api'
|
||||||
import { PLAN_NAMES } from '../billing'
|
import { PLAN_NAMES } from '../billing'
|
||||||
import { useMpStatus } from '../mp'
|
import { useMpStatus } from '../mp'
|
||||||
import { useWhatsappStatus } from '../whatsapp'
|
import { useWhatsappStatus } from '../whatsapp'
|
||||||
import { billingTypeLabel, formatPrice, formatSchedule } from './constants'
|
import { billingTypeLabel, formatPrice, formatSchedule } from './constants'
|
||||||
|
import { MessagePreview } from './MessagePreview'
|
||||||
import { useOnboarding } from './OnboardingProvider'
|
import { useOnboarding } from './OnboardingProvider'
|
||||||
import { Trans, useTranslation } from 'react-i18next'
|
|
||||||
|
|
||||||
type ConfirmationStepProps = {
|
type ConfirmationStepProps = {
|
||||||
group: OnboardingGroupDto
|
group: OnboardingGroupDto
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El cierre del alta. El grupo ya existe, y el momento de valor es que llegue el
|
||||||
|
* primer miembro: por eso la acción principal es mandar el link de invitación
|
||||||
|
* (con el mensaje real que se comparte), y lo que queda para Ajustes se dice en
|
||||||
|
* una sola línea.
|
||||||
|
*/
|
||||||
export function ConfirmationStep({ group }: ConfirmationStepProps) {
|
export function ConfirmationStep({ group }: ConfirmationStepProps) {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { t } = useTranslation(['onboarding', 'common', 'groups'])
|
const { t } = useTranslation(['onboarding', 'common', 'groupDetail'])
|
||||||
|
const locale = useIntlLocale()
|
||||||
|
const toast = useToast()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const { refresh } = useAuth()
|
const { refresh } = useAuth()
|
||||||
const statusQuery = useMpStatus()
|
const { selectedPlan, country } = useOnboarding()
|
||||||
const isMpConnected = statusQuery.data?.status === 'active'
|
const isMpConnected = useMpStatus().data?.status === 'active'
|
||||||
const whatsappQuery = useWhatsappStatus()
|
const isWhatsappConnected = useWhatsappStatus().data?.status === 'active'
|
||||||
const isWhatsappConnected = whatsappQuery.data?.status === 'active'
|
|
||||||
const { selectedPlan } = useOnboarding()
|
|
||||||
|
|
||||||
const goToDashboard = () => {
|
const inviteQuery = useQuery({
|
||||||
// Revalidates the cache (onboarding state, session, groups) before redirecting.
|
queryKey: ['invite-token', group.id],
|
||||||
|
queryFn: () => getInviteToken(group.id),
|
||||||
|
})
|
||||||
|
const inviteUrl = inviteQuery.data?.inviteUrl
|
||||||
|
const shareMessage = inviteUrl ? t('groupDetail:invite.message', { group: group.name, url: inviteUrl }) : ''
|
||||||
|
|
||||||
|
const copyLink = async () => {
|
||||||
|
if (!inviteUrl) return
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(inviteUrl)
|
||||||
|
toast.success(t('groupDetail:invite.linkCopied'))
|
||||||
|
} catch {
|
||||||
|
toast.error(t('groupDetail:invite.copyError'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const goHome = () => {
|
||||||
|
// Revalida todo (estado del alta, sesión, grupos) antes de salir.
|
||||||
void queryClient.invalidateQueries()
|
void queryClient.invalidateQueries()
|
||||||
void refresh()
|
void refresh()
|
||||||
void navigate({ to: '/' })
|
void navigate({ to: '/' })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isMonthly = group.billingType === 'MONTHLY'
|
||||||
|
const price = formatPrice(group.price, COUNTRY_CURRENCY[country])
|
||||||
|
const statusLine =
|
||||||
|
selectedPlan === 'FREE'
|
||||||
|
? t('done.statusFree', { plan: PLAN_NAMES.FREE })
|
||||||
|
: isMpConnected && isWhatsappConnected
|
||||||
|
? t('done.statusAllSet')
|
||||||
|
: !isMpConnected && !isWhatsappConnected
|
||||||
|
? t('done.statusPendingBoth')
|
||||||
|
: !isMpConnected
|
||||||
|
? t('done.statusPendingMp')
|
||||||
|
: t('done.statusPendingWa')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="space-y-6">
|
<section className="space-y-7">
|
||||||
<header className="space-y-2 text-center">
|
<header className="space-y-2">
|
||||||
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-success-soft">
|
<h2 className="text-[1.75rem] font-bold leading-tight tracking-tight text-primary text-balance">
|
||||||
<CheckCircle2 className="size-7 text-success" />
|
{t('done.title')}
|
||||||
</span>
|
</h2>
|
||||||
<h2 className="text-2xl font-bold text-primary">{t('done.title')}</h2>
|
<p className="text-[0.9375rem] text-foreground/70 text-pretty">{t('done.description')}</p>
|
||||||
<p className="text-sm text-foreground/60">
|
|
||||||
{t('done.description')}
|
|
||||||
</p>
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div className="rounded-xl border border-border bg-surface p-5">
|
<div className="space-y-3">
|
||||||
<div className="flex items-start justify-between gap-3">
|
<MessagePreview
|
||||||
<div className="min-w-0">
|
caption={t('done.previewCaption')}
|
||||||
<h3 className="truncate text-base font-semibold text-primary">{group.name}</h3>
|
contactName={t('done.previewContact')}
|
||||||
<p className="mt-0.5 text-sm text-foreground/60">
|
time={new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit' }).format(new Date())}
|
||||||
{formatSchedule(group.days ?? [], group.time)}
|
>
|
||||||
</p>
|
<Trans
|
||||||
</div>
|
t={t}
|
||||||
<Badge variant="success">{t('done.active')}</Badge>
|
i18nKey="groupDetail:invite.messagePreview"
|
||||||
</div>
|
values={{ group: group.name }}
|
||||||
|
components={{ strong: <strong className="font-semibold" /> }}
|
||||||
|
/>
|
||||||
|
{inviteUrl ? (
|
||||||
|
<span className="font-medium text-accent underline underline-offset-2">{inviteUrl}</span>
|
||||||
|
) : inviteQuery.isError ? null : (
|
||||||
|
<span className="inline-flex items-center gap-1.5 text-foreground/50">
|
||||||
|
<Loader2 aria-hidden="true" className="size-3.5 animate-spin" />
|
||||||
|
{t('done.linkLoading')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</MessagePreview>
|
||||||
|
|
||||||
<dl className="mt-4 divide-y divide-border text-sm">
|
{inviteQuery.isError ? (
|
||||||
<div className="flex items-center justify-between py-2.5">
|
<div role="alert" className="flex items-center justify-between gap-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
<dt className="text-foreground/60">{t('done.price')}</dt>
|
<span>{t('done.linkError')}</span>
|
||||||
<dd className="font-semibold text-primary">
|
<Button variant="outline" size="sm" onClick={() => void inviteQuery.refetch()}>
|
||||||
{formatPrice(group.price)}
|
{t('common:actions.retry')}
|
||||||
{group.billingType ? ` · ${billingTypeLabel(group.billingType)}` : ''}
|
</Button>
|
||||||
</dd>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between py-2.5">
|
|
||||||
<dt className="text-foreground/60">{t('done.capacity')}</dt>
|
|
||||||
<dd className="font-semibold text-primary">{group.capacity != null ? t('done.capacityValue', { count: group.capacity }) : '—'}</dd>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between py-2.5">
|
|
||||||
<dt className="text-foreground/60">{t('done.dueDay')}</dt>
|
|
||||||
<dd className="font-semibold text-primary">{group.dueDay != null ? t('done.dueDayValue', { day: group.dueDay }) : '—'}</dd>
|
|
||||||
</div>
|
|
||||||
</dl>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{selectedPlan ? (
|
|
||||||
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
|
|
||||||
<Sparkles className="size-4 shrink-0 text-accent" />
|
|
||||||
<p className="text-xs text-primary">
|
|
||||||
<Trans t={t} i18nKey="done.plan" values={{ plan: PLAN_NAMES[selectedPlan] }} components={{ strong: <span className="font-semibold" /> }} />
|
|
||||||
{selectedPlan === 'FREE' ? t('done.freeHint') : ''}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{/* Con Free no se cobra ni se automatiza: esos avisos son solo de Pro. */}
|
<div className="flex flex-col gap-2.5 sm:flex-row">
|
||||||
{selectedPlan === 'FREE' ? null : (
|
{/* Un <a> y no un botón con window.open: en iOS standalone es lo que
|
||||||
|
abre la app de WhatsApp sin bloqueos de pop-up. */}
|
||||||
|
<a
|
||||||
|
href={shareMessage ? `https://wa.me/?text=${encodeURIComponent(shareMessage)}` : undefined}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
aria-disabled={!shareMessage}
|
||||||
|
className="inline-flex h-12 items-center justify-center gap-2 rounded-xl bg-accent px-5 sm:flex-1 text-sm font-medium text-on-accent transition-[background-color,transform] duration-150 ease-out hover:bg-accent-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent active:scale-[0.96] aria-disabled:pointer-events-none aria-disabled:opacity-50 motion-reduce:active:scale-100"
|
||||||
|
>
|
||||||
|
<Send aria-hidden="true" className="size-4" />
|
||||||
|
{t('done.share')}
|
||||||
|
</a>
|
||||||
|
<Button variant="outline" size="lg" className="sm:flex-1" disabled={!inviteUrl} onClick={() => void copyLink()}>
|
||||||
|
<Copy aria-hidden="true" className="size-4" />
|
||||||
|
{t('done.copyLink')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-xl border border-border bg-surface px-4 py-3.5">
|
||||||
|
<p className="truncate text-sm font-semibold text-primary">{group.name}</p>
|
||||||
|
<p className="mt-0.5 text-sm text-foreground/60">{formatSchedule(group.days ?? [], group.time)}</p>
|
||||||
|
<dl className="mt-3 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-sm">
|
||||||
|
<dt className="text-foreground/60">{t('done.price')}</dt>
|
||||||
|
<dd className="text-right font-medium tabular-nums text-primary">
|
||||||
|
{price}
|
||||||
|
{group.billingType ? ` · ${billingTypeLabel(group.billingType)}` : ''}
|
||||||
|
</dd>
|
||||||
|
<dt className="text-foreground/60">{t('done.capacity')}</dt>
|
||||||
|
<dd className="text-right font-medium tabular-nums text-primary">
|
||||||
|
{group.capacity != null ? t('done.capacityValue', { count: group.capacity }) : '—'}
|
||||||
|
</dd>
|
||||||
|
{isMonthly && group.dueDay != null ? (
|
||||||
<>
|
<>
|
||||||
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
|
<dt className="text-foreground/60">{t('done.dueDay')}</dt>
|
||||||
<CreditCard className="size-4 shrink-0 text-accent" />
|
<dd className="text-right font-medium tabular-nums text-primary">
|
||||||
<p className="text-xs text-primary">
|
{t('done.dueDayValue', { day: group.dueDay })}
|
||||||
{isMpConnected ? (
|
</dd>
|
||||||
<Trans t={t} i18nKey="done.mpConnected" components={{ strong: <span className="font-semibold" /> }} />
|
|
||||||
) : (
|
|
||||||
<Trans t={t} i18nKey="done.mpPending" components={{ strong: <span className="font-semibold" /> }} />
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
|
|
||||||
<MessageCircle className="size-4 shrink-0 text-accent" />
|
|
||||||
<p className="text-xs text-primary">
|
|
||||||
{isWhatsappConnected ? (
|
|
||||||
t('done.waConnected')
|
|
||||||
) : (
|
|
||||||
<Trans t={t} i18nKey="done.waPending" components={{ strong: <span className="font-semibold" /> }} />
|
|
||||||
)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
)}
|
) : null}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Button variant="primary" className="w-full" onClick={goToDashboard}>
|
<p className="text-sm text-foreground/60 text-pretty">{statusLine}</p>
|
||||||
{t('done.goToPanel')}
|
|
||||||
<ArrowRight className="size-4" />
|
<Button variant="ghost" size="lg" className="w-full" onClick={goHome}>
|
||||||
|
{t('done.goHome')}
|
||||||
|
<ArrowRight aria-hidden="true" className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -73,11 +73,11 @@ export function CountryStep({ onNext, onBack }: CountryStepProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Button variant="outline" onClick={onBack} className="hidden lg:inline-flex">
|
<Button variant="outline" size="lg" onClick={onBack}>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
{t('common:actions.back')}
|
{t('common:actions.back')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="primary" className="flex-1 lg:flex-none" onClick={() => onNext()}>
|
<Button variant="primary" size="lg" className="flex-1" onClick={() => onNext()}>
|
||||||
{t('continue')}
|
{t('continue')}
|
||||||
<ArrowRight className="size-4" />
|
<ArrowRight className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared'
|
import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared'
|
||||||
import { useMutation } from '@tanstack/react-query'
|
import { useMutation } from '@tanstack/react-query'
|
||||||
import { createFirstGroup } from '../../lib/api'
|
import { ArrowLeft } from 'lucide-react'
|
||||||
|
import { Button } from '../../components/ui'
|
||||||
|
import { ApiError, createFirstGroup } from '../../lib/api'
|
||||||
import { errorMessage } from '../../i18n'
|
import { errorMessage } from '../../i18n'
|
||||||
import { GroupForm } from '../groups/GroupForm'
|
import { GroupForm } from '../groups/GroupForm'
|
||||||
import { useOnboarding } from './OnboardingProvider'
|
import { useOnboarding } from './OnboardingProvider'
|
||||||
@@ -12,12 +14,15 @@ type FirstGroupStepProps = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) {
|
export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) {
|
||||||
const { country } = useOnboarding()
|
const { country, goTo } = useOnboarding()
|
||||||
const { t } = useTranslation(['onboarding', 'common', 'groups'])
|
const { t } = useTranslation(['onboarding', 'common', 'groups'])
|
||||||
const create = useMutation({
|
const create = useMutation({
|
||||||
mutationFn: (values: CreateFirstGroup) => createFirstGroup(values),
|
mutationFn: (values: CreateFirstGroup) => createFirstGroup(values),
|
||||||
onSuccess: (result) => onCompleted(result.group),
|
onSuccess: (result) => onCompleted(result.group),
|
||||||
})
|
})
|
||||||
|
// Sin plan elegido el backend no deja crear el grupo: se ofrece volver a Plan.
|
||||||
|
const needsPlan =
|
||||||
|
create.error instanceof ApiError && create.error.problem?.code === 'plan_not_selected'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<GroupForm
|
<GroupForm
|
||||||
@@ -29,6 +34,14 @@ export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) {
|
|||||||
errorMessage={
|
errorMessage={
|
||||||
create.isError ? errorMessage(create.error, t('groups:create.error')) : null
|
create.isError ? errorMessage(create.error, t('groups:create.error')) : null
|
||||||
}
|
}
|
||||||
|
errorAction={
|
||||||
|
needsPlan ? (
|
||||||
|
<Button variant="outline" size="sm" onClick={() => goTo('plan')}>
|
||||||
|
<ArrowLeft className="size-4" />
|
||||||
|
{t('group.choosePlan')}
|
||||||
|
</Button>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
onSubmit={(values) => create.mutate(values)}
|
onSubmit={(values) => create.mutate(values)}
|
||||||
onBack={onBack}
|
onBack={onBack}
|
||||||
/>
|
/>
|
||||||
|
|||||||
39
apps/web/src/features/onboarding/LanguageSwitcher.tsx
Normal file
39
apps/web/src/features/onboarding/LanguageSwitcher.tsx
Normal 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>
|
||||||
|
)
|
||||||
|
}
|
||||||
55
apps/web/src/features/onboarding/MessagePreview.tsx
Normal file
55
apps/web/src/features/onboarding/MessagePreview.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { CheckCheck } from 'lucide-react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
|
|
||||||
|
type MessagePreviewProps = {
|
||||||
|
/** A quién le llega el mensaje (la cabecera del chat). */
|
||||||
|
contactName: string
|
||||||
|
/** Una línea chica arriba del chat que dice qué se está viendo. */
|
||||||
|
caption: string
|
||||||
|
/** La hora del mensaje, ya formateada. */
|
||||||
|
time: string
|
||||||
|
children: ReactNode
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Vista previa de un mensaje tal como lo recibe el miembro en su chat.
|
||||||
|
*
|
||||||
|
* Es lo que hace reconocible al onboarding: en vez de prometer "cobrá al
|
||||||
|
* instante", muestra el mensaje real que sale desde el número del profe. La
|
||||||
|
* burbuja usa los tokens de la app (no imita la marca de ningún chat) y el
|
||||||
|
* texto lo arma quien la usa, con los mismos datos que manda el backend.
|
||||||
|
*/
|
||||||
|
export function MessagePreview({ contactName, caption, time, children, className }: MessagePreviewProps) {
|
||||||
|
const initial = contactName.trim().charAt(0).toUpperCase()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<figure className={cn('space-y-2', className)}>
|
||||||
|
<figcaption className="text-sm text-foreground/60">{caption}</figcaption>
|
||||||
|
<div className="overflow-hidden rounded-2xl border border-border bg-background">
|
||||||
|
<div className="flex items-center gap-2.5 border-b border-border bg-surface px-3.5 py-2.5">
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="flex size-8 items-center justify-center rounded-full bg-primary-soft text-sm font-semibold text-primary"
|
||||||
|
>
|
||||||
|
{initial}
|
||||||
|
</span>
|
||||||
|
<span className="truncate text-sm font-semibold text-primary">{contactName}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-3.5 py-4">
|
||||||
|
<div className="ml-auto max-w-[88%] rounded-2xl rounded-tr-md bg-accent-soft px-3.5 py-2.5 shadow-[0_1px_2px_rgb(0_0_0/0.06)]">
|
||||||
|
<div className="whitespace-pre-line text-[0.9375rem] leading-snug text-primary [overflow-wrap:anywhere]">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 flex items-center justify-end gap-1 text-[0.6875rem] text-foreground/50">
|
||||||
|
<span className="tabular-nums">{time}</span>
|
||||||
|
<CheckCheck aria-hidden="true" className="size-3.5 text-accent" />
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</figure>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto, Plan } from '@gruperly/shared'
|
import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto, Plan } from '@gruperly/shared'
|
||||||
import { DEFAULT_COUNTRY } from '@gruperly/shared'
|
import { countryCodeSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
||||||
import type { UseQueryResult } from '@tanstack/react-query'
|
import type { UseQueryResult } from '@tanstack/react-query'
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useNavigate, useSearch } from '@tanstack/react-router'
|
import { useNavigate, useSearch } from '@tanstack/react-router'
|
||||||
import type { ReactNode } from 'react'
|
import type { ReactNode } from 'react'
|
||||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
|
||||||
import { useAuth } from '../../context/AuthProvider'
|
import { useAuth } from '../../context/AuthProvider'
|
||||||
import { getOnboardingStatus } from '../../lib/api'
|
import { getOnboardingStatus } from '../../lib/api'
|
||||||
import { billingStatusQueryKey } from '../billing'
|
import { billingStatusQueryKey } from '../billing'
|
||||||
@@ -12,12 +12,12 @@ import type { MpCallbackFeedback } from '../mp'
|
|||||||
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
||||||
import type { WhatsappCallbackFeedback } from '../whatsapp'
|
import type { WhatsappCallbackFeedback } from '../whatsapp'
|
||||||
import { readWhatsappCallbackFeedback, whatsappStatusQueryKey } from '../whatsapp'
|
import { readWhatsappCallbackFeedback, whatsappStatusQueryKey } from '../whatsapp'
|
||||||
import { type OnboardingStepId, resumeStep, visibleSteps } from './steps'
|
import { effectiveStep, type OnboardingStepId, parseStep, resumeStep, visibleSteps } from './steps'
|
||||||
|
|
||||||
type OnboardingContextValue = {
|
type OnboardingContextValue = {
|
||||||
step: OnboardingStepId
|
step: OnboardingStepId
|
||||||
steps: OnboardingStepId[]
|
steps: OnboardingStepId[]
|
||||||
goTo: (step: OnboardingStepId) => void
|
goTo: (step: OnboardingStepId, options?: { replace?: boolean }) => void
|
||||||
goNext: () => void
|
goNext: () => void
|
||||||
goBack: () => void
|
goBack: () => void
|
||||||
/** El país del profesor; define la moneda de los links de cobro y el precio de Pro. */
|
/** El país del profesor; define la moneda de los links de cobro y el precio de Pro. */
|
||||||
@@ -39,13 +39,34 @@ type OnboardingContextValue = {
|
|||||||
|
|
||||||
const OnboardingContext = createContext<OnboardingContextValue | null>(null)
|
const OnboardingContext = createContext<OnboardingContextValue | null>(null)
|
||||||
|
|
||||||
|
/* El país elegido se guarda en el servidor recién junto con el plan. Mientras
|
||||||
|
tanto vive en sessionStorage: con el paso en la URL, recargar en "Plan" ya no
|
||||||
|
vuelve a la bienvenida y no tiene que perder el país. */
|
||||||
|
const COUNTRY_STORAGE_KEY = 'onboarding-country'
|
||||||
|
|
||||||
|
function readStoredCountry(): CountryCode | null {
|
||||||
|
try {
|
||||||
|
const parsed = countryCodeSchema.safeParse(sessionStorage.getItem(COUNTRY_STORAGE_KEY))
|
||||||
|
return parsed.success ? parsed.data : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function storeCountry(country: CountryCode) {
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(COUNTRY_STORAGE_KEY, country)
|
||||||
|
} catch {
|
||||||
|
// Sin storage (modo privado, bloqueado): el país vive solo en memoria.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function OnboardingProvider({ children }: { children: ReactNode }) {
|
export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||||
const { user } = useAuth()
|
const { user } = useAuth()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const search = useSearch({ from: '/onboarding' })
|
const search = useSearch({ from: '/onboarding' })
|
||||||
const [step, setStep] = useState<OnboardingStepId>('welcome')
|
const [country, setCountryState] = useState<CountryCode>(() => readStoredCountry() ?? DEFAULT_COUNTRY)
|
||||||
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
|
|
||||||
const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null)
|
const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null)
|
||||||
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
|
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
|
||||||
const [waFeedback, setWaFeedback] = useState<WhatsappCallbackFeedback | null>(null)
|
const [waFeedback, setWaFeedback] = useState<WhatsappCallbackFeedback | null>(null)
|
||||||
@@ -58,16 +79,50 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
enabled: !!user,
|
enabled: !!user,
|
||||||
})
|
})
|
||||||
|
|
||||||
const steps = useMemo(() => visibleSteps(selectedPlan), [selectedPlan])
|
const setCountry = useCallback((next: CountryCode) => {
|
||||||
|
setCountryState(next)
|
||||||
|
storeCountry(next)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
/* El paso vive en `?step=`: cada avance es una entrada del historial, así el
|
||||||
|
gesto de back del dispositivo retrocede un paso en vez de salir del alta.
|
||||||
|
Lo que pide la URL pasa por `effectiveStep`, que no deja saltear el plan ni
|
||||||
|
volver al formulario con el grupo ya creado. */
|
||||||
|
const plan = selectedPlan ?? statusQuery.data?.selectedPlan ?? null
|
||||||
|
const requestedStep = parseStep(search.step) ?? 'welcome'
|
||||||
|
const step = effectiveStep(requestedStep, { plan, hasCreatedGroup: createdGroup !== null })
|
||||||
|
const steps = useMemo(() => visibleSteps(plan), [plan])
|
||||||
|
|
||||||
|
const goTo = useCallback(
|
||||||
|
(target: OnboardingStepId, options?: { replace?: boolean }) => {
|
||||||
|
void navigate({
|
||||||
|
to: '/onboarding',
|
||||||
|
search: target === 'welcome' ? {} : { step: target },
|
||||||
|
replace: options?.replace ?? false,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
[navigate],
|
||||||
|
)
|
||||||
const goNext = () => {
|
const goNext = () => {
|
||||||
const next = steps[steps.indexOf(step) + 1]
|
const next = steps[steps.indexOf(step) + 1]
|
||||||
if (next) setStep(next)
|
if (next) goTo(next)
|
||||||
}
|
}
|
||||||
|
// Reemplaza en vez de apilar: así el back del dispositivo después de "Volver"
|
||||||
|
// no rebota al paso del que se salió.
|
||||||
const goBack = () => {
|
const goBack = () => {
|
||||||
const previous = steps[steps.indexOf(step) - 1]
|
const previous = steps[steps.indexOf(step) - 1]
|
||||||
if (previous) setStep(previous)
|
if (previous) goTo(previous, { replace: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Si la URL pedía un paso que no corresponde, se corrige sin apilar historial.
|
||||||
|
// Solo con el estado del servidor ya cargado: antes no se sabe el plan.
|
||||||
|
const hasStatus = statusQuery.data !== undefined
|
||||||
|
useEffect(() => {
|
||||||
|
if (hasStatus && search.step !== undefined && requestedStep !== step) {
|
||||||
|
goTo(step, { replace: true })
|
||||||
|
}
|
||||||
|
}, [hasStatus, search.step, requestedStep, step, goTo])
|
||||||
|
|
||||||
const callbackFeedback = useMemo(
|
const callbackFeedback = useMemo(
|
||||||
() => readMpCallbackFeedback(search.mp, search.reason),
|
() => readMpCallbackFeedback(search.mp, search.reason),
|
||||||
[search.mp, search.reason],
|
[search.mp, search.reason],
|
||||||
@@ -81,15 +136,11 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
// "cambiar de cuenta" y el resumen final ya sabe que hay cuenta.
|
// "cambiar de cuenta" y el resumen final ya sabe que hay cuenta.
|
||||||
void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey })
|
void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||||
// Vuelve al paso de Cobros, que es de donde salió el flujo. Setearlo siempre
|
// Vuelve al paso de Cobros, que es de donde salió el flujo, y limpia los
|
||||||
// (y no solo desde el primer paso) evita que un `?mp=` que llega con el
|
// parámetros: si no, recargar volvería a mostrar el aviso de la vinculación
|
||||||
// proveedor recién montado salte al resumen sin mostrar la confirmación.
|
// vieja.
|
||||||
setStep('payment')
|
goTo('payment', { replace: true })
|
||||||
|
}, [callbackFeedback, goTo, queryClient])
|
||||||
// Se limpian los parámetros de la URL: si no, recargar la página volvería a
|
|
||||||
// mostrar el aviso de la vinculación vieja.
|
|
||||||
void navigate({ to: '/onboarding', search: {}, replace: true })
|
|
||||||
}, [callbackFeedback, navigate, queryClient])
|
|
||||||
|
|
||||||
const whatsappCallbackFeedback = useMemo(
|
const whatsappCallbackFeedback = useMemo(
|
||||||
() => readWhatsappCallbackFeedback(search.wa, search.reason),
|
() => readWhatsappCallbackFeedback(search.wa, search.reason),
|
||||||
@@ -104,9 +155,8 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
setWaFeedback(whatsappCallbackFeedback)
|
setWaFeedback(whatsappCallbackFeedback)
|
||||||
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||||
setStep('whatsapp')
|
goTo('whatsapp', { replace: true })
|
||||||
void navigate({ to: '/onboarding', search: {}, replace: true })
|
}, [whatsappCallbackFeedback, goTo, queryClient])
|
||||||
}, [whatsappCallbackFeedback, navigate, queryClient])
|
|
||||||
|
|
||||||
// Vuelta de Mercado Pago tras la suscripción a Pro: el paso Plan muestra si
|
// Vuelta de Mercado Pago tras la suscripción a Pro: el paso Plan muestra si
|
||||||
// quedó activa o se sigue procesando (y deja seguir igual).
|
// quedó activa o se sigue procesando (y deja seguir igual).
|
||||||
@@ -117,9 +167,8 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
setSelectedPlan('PRO')
|
setSelectedPlan('PRO')
|
||||||
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
|
void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey })
|
||||||
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||||
setStep('plan')
|
goTo('plan', { replace: true })
|
||||||
void navigate({ to: '/onboarding', search: {}, replace: true })
|
}, [search.sub, goTo, queryClient])
|
||||||
}, [search.sub, navigate, queryClient])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const status = statusQuery.data
|
const status = statusQuery.data
|
||||||
@@ -128,18 +177,24 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
|||||||
// país y el plan elegidos se recuperan del servidor.
|
// país y el plan elegidos se recuperan del servidor.
|
||||||
if (status.country) setCountry(status.country)
|
if (status.country) setCountry(status.country)
|
||||||
if (status.selectedPlan) setSelectedPlan((current) => current ?? status.selectedPlan)
|
if (status.selectedPlan) setSelectedPlan((current) => current ?? status.selectedPlan)
|
||||||
|
}, [statusQuery.data, setCountry])
|
||||||
|
|
||||||
// Retomar donde quedó, solo si recién arranca (desde la bienvenida).
|
// Retomar donde quedó, solo si la URL no pide un paso ni vuelve de un redirect
|
||||||
|
// (esos ya llevan al paso que corresponde).
|
||||||
|
const isReturningFromRedirect = Boolean(search.mp || search.wa || search.sub)
|
||||||
|
useEffect(() => {
|
||||||
|
const status = statusQuery.data
|
||||||
|
if (!status || search.step !== undefined || isReturningFromRedirect) return
|
||||||
const resumeAt = resumeStep(status)
|
const resumeAt = resumeStep(status)
|
||||||
if (resumeAt) setStep((current) => (current === 'welcome' ? resumeAt : current))
|
if (resumeAt) goTo(resumeAt, { replace: true })
|
||||||
}, [statusQuery.data])
|
}, [statusQuery.data, search.step, isReturningFromRedirect, goTo])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<OnboardingContext.Provider
|
<OnboardingContext.Provider
|
||||||
value={{
|
value={{
|
||||||
step,
|
step,
|
||||||
steps,
|
steps,
|
||||||
goTo: setStep,
|
goTo,
|
||||||
goNext,
|
goNext,
|
||||||
goBack,
|
goBack,
|
||||||
country,
|
country,
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { Loader2 } from 'lucide-react'
|
import { Loader2 } from 'lucide-react'
|
||||||
import { useEffect } from 'react'
|
import { useEffect, useLayoutEffect, useRef } from 'react'
|
||||||
import { Logo, LogoIcon } from '../../components/brand'
|
import { Logo, LogoIcon } from '../../components/brand'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
|
import { cn } from '../../lib/utils'
|
||||||
import { useAuth } from '../../context/AuthProvider'
|
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'
|
||||||
@@ -32,6 +34,32 @@ export function OnboardingView() {
|
|||||||
statusQuery,
|
statusQuery,
|
||||||
} = useOnboarding()
|
} = useOnboarding()
|
||||||
|
|
||||||
|
/* Al cambiar de paso: se sabe hacia dónde se movió (para la animación) y el
|
||||||
|
foco pasa al título del paso nuevo, así el lector de pantalla lo anuncia y
|
||||||
|
el teclado sigue desde ahí. Si el paso ya enfocó su primer campo
|
||||||
|
(`autoFocus`), se respeta. */
|
||||||
|
const stepIndex = steps.indexOf(step)
|
||||||
|
const previousIndex = useRef(stepIndex)
|
||||||
|
const direction = stepIndex < previousIndex.current ? 'back' : 'forward'
|
||||||
|
const stepContainer = useRef<HTMLDivElement>(null)
|
||||||
|
const isFirstStep = useRef(true)
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
previousIndex.current = stepIndex
|
||||||
|
}, [stepIndex])
|
||||||
|
useEffect(() => {
|
||||||
|
if (isFirstStep.current) {
|
||||||
|
isFirstStep.current = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
window.scrollTo({ top: 0 })
|
||||||
|
const container = stepContainer.current
|
||||||
|
if (!container || container.contains(document.activeElement)) return
|
||||||
|
const heading = container.querySelector<HTMLElement>('h1, h2')
|
||||||
|
if (!heading) return
|
||||||
|
heading.tabIndex = -1
|
||||||
|
heading.focus({ preventScroll: true })
|
||||||
|
}, [step])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (statusQuery.data?.completed) {
|
if (statusQuery.data?.completed) {
|
||||||
void navigate({ to: '/' })
|
void navigate({ to: '/' })
|
||||||
@@ -53,7 +81,7 @@ export function OnboardingView() {
|
|||||||
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft">
|
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft">
|
||||||
<LogoIcon className="size-8" />
|
<LogoIcon className="size-8" />
|
||||||
</span>
|
</span>
|
||||||
<h1 className="text-2xl font-bold text-primary">{t('signedOut.title')}</h1>
|
<h1 className="text-2xl font-bold text-primary text-balance">{t('signedOut.title')}</h1>
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
{t('signedOut.description')}
|
{t('signedOut.description')}
|
||||||
</p>
|
</p>
|
||||||
@@ -80,19 +108,29 @@ export function OnboardingView() {
|
|||||||
const firstName = user.name?.trim().split(/\s+/)[0] ?? t('fallbackName')
|
const firstName = user.name?.trim().split(/\s+/)[0] ?? t('fallbackName')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto flex min-h-dvh w-full max-w-md flex-col px-4 pb-12 pt-8 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
|
||||||
los pasos que se van a recorrer. */}
|
los pasos que se van a recorrer. */}
|
||||||
<Stepper
|
<Stepper
|
||||||
steps={steps.map((id) => ({ label: t(`steps.${id}`) }))}
|
steps={steps.map((id) => ({ label: t(`steps.${id}`) }))}
|
||||||
current={steps.indexOf(step)}
|
current={stepIndex}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div key={step} className="mt-8 animate-step-enter">
|
<div
|
||||||
|
key={step}
|
||||||
|
ref={stepContainer}
|
||||||
|
className={cn(
|
||||||
|
'mt-8 motion-reduce:animate-none [&_h1]:outline-none [&_h2]:outline-none',
|
||||||
|
direction === 'back' ? 'animate-step-enter-back' : 'animate-step-enter',
|
||||||
|
)}
|
||||||
|
>
|
||||||
{step === 'welcome' ? <WelcomeStep name={firstName} onNext={goNext} /> : null}
|
{step === 'welcome' ? <WelcomeStep name={firstName} onNext={goNext} /> : null}
|
||||||
{step === 'country' ? <CountryStep onNext={goNext} onBack={goBack} /> : null}
|
{step === 'country' ? <CountryStep onNext={goNext} onBack={goBack} /> : null}
|
||||||
{step === 'plan' ? <PlanStep /> : null}
|
{step === 'plan' ? <PlanStep /> : null}
|
||||||
@@ -107,7 +145,9 @@ export function OnboardingView() {
|
|||||||
onBack={goBack}
|
onBack={goBack}
|
||||||
onCompleted={(group) => {
|
onCompleted={(group) => {
|
||||||
setCreatedGroup(group)
|
setCreatedGroup(group)
|
||||||
goTo('done')
|
// Reemplaza: el formulario ya no tiene que quedar en el historial
|
||||||
|
// (volver a él crearía otro grupo).
|
||||||
|
goTo('done', { replace: true })
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
48
apps/web/src/features/onboarding/PaymentReminderPreview.tsx
Normal file
48
apps/web/src/features/onboarding/PaymentReminderPreview.tsx
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import { COUNTRY_CURRENCY, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared'
|
||||||
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { useIntlLocale } from '../../i18n'
|
||||||
|
import { formatPrice } from '../../lib/format'
|
||||||
|
import { MessagePreview } from './MessagePreview'
|
||||||
|
import { useOnboarding } from './OnboardingProvider'
|
||||||
|
|
||||||
|
type PaymentReminderPreviewProps = {
|
||||||
|
caption: string
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Día de vencimiento y hora de la muestra: valores típicos, fijos para que la
|
||||||
|
vista previa no cambie entre renders. */
|
||||||
|
const SAMPLE_DUE_DAY = 10
|
||||||
|
const SAMPLE_TIME = new Date(2026, 0, 5, 10, 0)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El recordatorio de pago semanal, con el mismo texto que arma el backend
|
||||||
|
* (`whatsapp/lib/render-message.ts`) y un ejemplo en la moneda del país elegido.
|
||||||
|
*/
|
||||||
|
export function PaymentReminderPreview({ caption, className }: PaymentReminderPreviewProps) {
|
||||||
|
const { t } = useTranslation('onboarding')
|
||||||
|
const locale = useIntlLocale()
|
||||||
|
const { country } = useOnboarding()
|
||||||
|
|
||||||
|
const now = new Date()
|
||||||
|
const dueDate = new Date(now.getFullYear(), now.getMonth() + (now.getDate() >= SAMPLE_DUE_DAY ? 1 : 0), SAMPLE_DUE_DAY)
|
||||||
|
// El precio de ejemplo es el de Pro del país: un monto realista en su moneda.
|
||||||
|
const amount = formatPrice(PRO_PRICE_BY_COUNTRY[country], COUNTRY_CURRENCY[country])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MessagePreview
|
||||||
|
caption={caption}
|
||||||
|
contactName={t('preview.sampleStudentFull')}
|
||||||
|
time={new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit' }).format(SAMPLE_TIME)}
|
||||||
|
className={className}
|
||||||
|
>
|
||||||
|
{t('preview.reminder', {
|
||||||
|
name: t('preview.sampleStudent'),
|
||||||
|
group: t('preview.sampleGroup'),
|
||||||
|
amount,
|
||||||
|
date: new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'long' }).format(dueDate),
|
||||||
|
})}{' '}
|
||||||
|
<span className="font-medium text-accent underline underline-offset-2">{t('preview.sampleLink')}</span>
|
||||||
|
</MessagePreview>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -51,7 +51,7 @@ export function PaymentStep({ feedback, onNext, onBack }: PaymentStepProps) {
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{feedback?.kind === 'error' ? (
|
{feedback?.kind === 'error' ? (
|
||||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<p role="alert" className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
{mpCallbackErrorMessage(feedback.reason)}
|
{mpCallbackErrorMessage(feedback.reason)}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -82,7 +82,8 @@ export function PaymentStep({ feedback, onNext, onBack }: PaymentStepProps) {
|
|||||||
|
|
||||||
<div className="px-4 py-3">
|
<div className="px-4 py-3">
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant={isConnected ? 'outline' : 'primary'}
|
||||||
|
size="lg"
|
||||||
className="w-full"
|
className="w-full"
|
||||||
disabled={startAuthorization.isStarting}
|
disabled={startAuthorization.isStarting}
|
||||||
onClick={() => void startAuthorization.start('onboarding')}
|
onClick={() => void startAuthorization.start('onboarding')}
|
||||||
@@ -102,17 +103,17 @@ export function PaymentStep({ feedback, onNext, onBack }: PaymentStepProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{startAuthorization.error ? (
|
{startAuthorization.error ? (
|
||||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<p role="alert" className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
{startAuthorization.error}
|
{startAuthorization.error}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Button variant="outline" onClick={onBack} className="hidden lg:inline-flex">
|
<Button variant="outline" size="lg" onClick={onBack}>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
{t('common:actions.back')}
|
{t('common:actions.back')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" className="flex-1 lg:flex-none" onClick={onNext}>
|
<Button variant={isConnected ? 'primary' : 'outline'} size="lg" className="flex-1" onClick={onNext}>
|
||||||
{isConnected ? t('continue') : t('later')}
|
{isConnected ? t('continue') : t('later')}
|
||||||
<ArrowRight className="size-4" />
|
<ArrowRight className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { SelectPlanInput } from '@gruperly/shared'
|
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 { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { ArrowLeft, ArrowRight, CheckCircle2, Clock, Loader2, Sparkles } from 'lucide-react'
|
import { ArrowLeft, ArrowRight, CheckCircle2, Clock, Loader2, Sparkles } from 'lucide-react'
|
||||||
import { type ReactNode, useEffect, useState } from 'react'
|
import { type ReactNode, useEffect, useState } from 'react'
|
||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
PlanOptionCard,
|
PlanOptionCard,
|
||||||
SubscribeForm,
|
SubscribeForm,
|
||||||
useBillingStatus,
|
useBillingStatus,
|
||||||
|
usePlanCatalog,
|
||||||
useSubscriptionReturnPolling,
|
useSubscriptionReturnPolling,
|
||||||
} from '../billing'
|
} from '../billing'
|
||||||
import { useOnboarding } from './OnboardingProvider'
|
import { useOnboarding } from './OnboardingProvider'
|
||||||
@@ -37,6 +38,7 @@ export function PlanStep() {
|
|||||||
const [proUnavailable, setProUnavailable] = useState(false)
|
const [proUnavailable, setProUnavailable] = useState(false)
|
||||||
|
|
||||||
const polling = useSubscriptionReturnPolling()
|
const polling = useSubscriptionReturnPolling()
|
||||||
|
const { catalog } = usePlanCatalog()
|
||||||
const choseProBefore = selectedPlan === 'PRO' && statusQuery.data?.subscriptionStatus != null
|
const choseProBefore = selectedPlan === 'PRO' && statusQuery.data?.subscriptionStatus != null
|
||||||
const billingQuery = useBillingStatus({
|
const billingQuery = useBillingStatus({
|
||||||
enabled: returnedFromSubscription || choseProBefore,
|
enabled: returnedFromSubscription || choseProBefore,
|
||||||
@@ -82,8 +84,23 @@ export function PlanStep() {
|
|||||||
mutation.mutate({ plan: 'PRO', country, payerEmail })
|
mutation.mutate({ plan: 'PRO', country, payerEmail })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Con Mercado Pago hay que pedir el email de la cuenta que paga; con Stripe no
|
||||||
|
// hay nada que completar (lo pide su checkout), así que se va directo.
|
||||||
|
const startPro = () => {
|
||||||
|
if (provider === 'MERCADO_PAGO') {
|
||||||
|
setError(null)
|
||||||
|
setIsEnteringEmail(true)
|
||||||
|
} else {
|
||||||
|
choosePro(undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const countryPrice = catalog.proPrices[country] ?? {
|
||||||
|
amount: PRO_PRICE_BY_COUNTRY[country],
|
||||||
|
currency: COUNTRY_CURRENCY[country],
|
||||||
|
}
|
||||||
const proPrice = t('billing:view.perMonth', {
|
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') {
|
if (subscriptionStatus === 'AUTHORIZED') {
|
||||||
@@ -93,7 +110,7 @@ export function PlanStep() {
|
|||||||
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
|
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
|
||||||
{t('plan.active')}
|
{t('plan.active')}
|
||||||
</p>
|
</p>
|
||||||
<Button variant="primary" className="w-full" onClick={() => goTo('payment')}>
|
<Button variant="primary" size="lg" className="w-full" onClick={() => goTo('payment')}>
|
||||||
{t('continue')}
|
{t('continue')}
|
||||||
<ArrowRight className="size-4" />
|
<ArrowRight className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
@@ -123,21 +140,21 @@ export function PlanStep() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
|
{error ? <p role="alert" className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
|
||||||
|
|
||||||
<div className="flex flex-col gap-3 sm:flex-row">
|
<div className="flex flex-col gap-3 sm:flex-row">
|
||||||
{returnedFromSubscription ? (
|
{returnedFromSubscription ? (
|
||||||
<Button variant="primary" className="flex-1" onClick={() => goTo('payment')}>
|
<Button variant="primary" size="lg" className="flex-1" onClick={() => goTo('payment')}>
|
||||||
{t('continue')}
|
{t('continue')}
|
||||||
<ArrowRight className="size-4" />
|
<ArrowRight className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Button variant="primary" className="flex-1" onClick={() => setIsEnteringEmail(true)}>
|
<Button variant="primary" size="lg" className="flex-1" onClick={startPro}>
|
||||||
<Sparkles className="size-4" />
|
<Sparkles className="size-4" />
|
||||||
{t('plan.retry')}
|
{t('plan.retry')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" className="flex-1" disabled={mutation.isPending} onClick={chooseFree}>
|
<Button variant="outline" size="lg" className="flex-1" disabled={mutation.isPending} onClick={chooseFree}>
|
||||||
{t('plan.stayFree')}
|
{t('plan.stayFree')}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
@@ -150,8 +167,8 @@ export function PlanStep() {
|
|||||||
return (
|
return (
|
||||||
<StepShell>
|
<StepShell>
|
||||||
<div className="grid gap-3">
|
<div className="grid gap-3">
|
||||||
<PlanOptionCard plan="FREE" limits={PLAN_LIMITS.FREE}>
|
<PlanOptionCard plan="FREE" limits={catalog.limits.FREE}>
|
||||||
<Button variant="outline" className="w-full" disabled={isLeavingToMp} onClick={chooseFree}>
|
<Button variant="outline" size="lg" className="w-full" disabled={isLeavingToMp} onClick={chooseFree}>
|
||||||
{mutation.isPending && mutation.variables?.plan === 'FREE' ? (
|
{mutation.isPending && mutation.variables?.plan === 'FREE' ? (
|
||||||
<Loader2 className="size-4 animate-spin" />
|
<Loader2 className="size-4 animate-spin" />
|
||||||
) : null}
|
) : null}
|
||||||
@@ -159,7 +176,7 @@ export function PlanStep() {
|
|||||||
</Button>
|
</Button>
|
||||||
</PlanOptionCard>
|
</PlanOptionCard>
|
||||||
|
|
||||||
<PlanOptionCard plan="PRO" limits={PLAN_LIMITS.PRO} price={proPrice} highlighted>
|
<PlanOptionCard plan="PRO" limits={catalog.limits.PRO} price={proPrice} highlighted>
|
||||||
{proUnavailable ? (
|
{proUnavailable ? (
|
||||||
<p className="text-xs text-foreground/50">{t('billing:view.unavailable')}</p>
|
<p className="text-xs text-foreground/50">{t('billing:view.unavailable')}</p>
|
||||||
) : isEnteringEmail ? (
|
) : isEnteringEmail ? (
|
||||||
@@ -167,23 +184,31 @@ export function PlanStep() {
|
|||||||
provider={provider}
|
provider={provider}
|
||||||
defaultEmail={user?.email ?? ''}
|
defaultEmail={user?.email ?? ''}
|
||||||
isPending={isLeavingToMp}
|
isPending={isLeavingToMp}
|
||||||
error={null}
|
error={error}
|
||||||
onSubmit={choosePro}
|
onSubmit={choosePro}
|
||||||
onCancel={() => setIsEnteringEmail(false)}
|
onCancel={() => setIsEnteringEmail(false)}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<Button variant="primary" className="w-full" onClick={() => setIsEnteringEmail(true)}>
|
<Button variant="primary" size="lg" className="w-full" disabled={isLeavingToMp} onClick={startPro}>
|
||||||
|
{mutation.isPending && mutation.variables?.plan === 'PRO' ? (
|
||||||
|
<Loader2 className="size-4 animate-spin" />
|
||||||
|
) : (
|
||||||
<Sparkles className="size-4" />
|
<Sparkles className="size-4" />
|
||||||
|
)}
|
||||||
{t('plan.choosePro')}
|
{t('plan.choosePro')}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</PlanOptionCard>
|
</PlanOptionCard>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{error ? <p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p> : null}
|
{/* Con el form de Pro abierto, el error se muestra adentro, junto a lo que
|
||||||
|
se acaba de enviar. */}
|
||||||
|
{error && !isEnteringEmail ? (
|
||||||
|
<p role="alert" className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{error}</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Button variant="outline" onClick={goBack} className="hidden lg:inline-flex">
|
<Button variant="outline" size="lg" onClick={goBack}>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
{t('common:actions.back')}
|
{t('common:actions.back')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -9,7 +9,10 @@ export type StepperProps = {
|
|||||||
|
|
||||||
export function Stepper({ steps, current }: StepperProps) {
|
export function Stepper({ steps, current }: StepperProps) {
|
||||||
const { t } = useTranslation('onboarding')
|
const { t } = useTranslation('onboarding')
|
||||||
|
const currentLabel = steps[current]?.label
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<div>
|
||||||
<ol aria-label={t('steps.progress')} className="flex items-center">
|
<ol aria-label={t('steps.progress')} className="flex items-center">
|
||||||
{steps.map((step, index) => {
|
{steps.map((step, index) => {
|
||||||
const isDone = index < current
|
const isDone = index < current
|
||||||
@@ -18,28 +21,27 @@ export function Stepper({ steps, current }: StepperProps) {
|
|||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
key={step.label}
|
key={step.label}
|
||||||
|
aria-current={isActive ? 'step' : undefined}
|
||||||
className={cn('flex items-center', index < steps.length - 1 ? 'flex-1' : '')}
|
className={cn('flex items-center', index < steps.length - 1 ? 'flex-1' : '')}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col items-center gap-1.5">
|
<div className="flex flex-col items-center gap-1.5">
|
||||||
<span
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex size-8 items-center justify-center rounded-full border text-sm font-semibold transition-colors',
|
'flex size-8 items-center justify-center rounded-full border text-sm font-semibold tabular-nums transition-colors',
|
||||||
isDone && 'border-accent bg-accent text-on-accent',
|
isDone && 'border-accent bg-accent text-on-accent',
|
||||||
isActive && 'border-accent text-accent ring-4 ring-accent/15',
|
isActive && 'border-accent text-accent ring-4 ring-accent/15',
|
||||||
!isDone && !isActive && 'border-border text-foreground/40',
|
!isDone && !isActive && 'border-border text-foreground/40',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{isDone ? (
|
{isDone ? <Check className="size-4" strokeWidth={3} /> : index + 1}
|
||||||
<Check className="size-4" strokeWidth={3} />
|
|
||||||
) : (
|
|
||||||
<span>{index + 1}</span>
|
|
||||||
)}
|
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
// Sin corte: con 7 pasos en max-w-md, "Tu grupo" partía en dos
|
// `sr-only` y no `hidden` en mobile: el lector de pantalla
|
||||||
// líneas. Si falta lugar, se achica la línea entre pasos.
|
// tiene que oír el nombre del paso, no solo el número. Sin
|
||||||
'hidden whitespace-nowrap text-xs font-medium sm:block',
|
// corte: con 7 pasos en max-w-md, "Tu grupo" partía en dos.
|
||||||
|
'sr-only whitespace-nowrap text-xs font-medium sm:not-sr-only',
|
||||||
isActive ? 'text-accent' : 'text-foreground/50',
|
isActive ? 'text-accent' : 'text-foreground/50',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
@@ -49,6 +51,7 @@ export function Stepper({ steps, current }: StepperProps) {
|
|||||||
|
|
||||||
{index < steps.length - 1 ? (
|
{index < steps.length - 1 ? (
|
||||||
<span
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
className={cn(
|
className={cn(
|
||||||
'mx-2 mb-0 h-px flex-1 rounded-full transition-colors sm:mb-4',
|
'mx-2 mb-0 h-px flex-1 rounded-full transition-colors sm:mb-4',
|
||||||
isDone ? 'bg-accent' : 'bg-border',
|
isDone ? 'bg-accent' : 'bg-border',
|
||||||
@@ -59,5 +62,17 @@ export function Stepper({ steps, current }: StepperProps) {
|
|||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
|
{/* En mobile los nombres no entran debajo de cada círculo: el paso actual
|
||||||
|
se nombra en una línea, para que al volver de una interrupción se sepa
|
||||||
|
dónde se está. */}
|
||||||
|
{currentLabel ? (
|
||||||
|
<p aria-hidden="true" className="mt-3 text-center text-sm text-foreground/60 sm:hidden">
|
||||||
|
{t('steps.position', { current: current + 1, total: steps.length })}
|
||||||
|
<span className="mx-1.5 text-foreground/30">·</span>
|
||||||
|
<span className="font-medium text-primary">{currentLabel}</span>
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,62 +1,49 @@
|
|||||||
import { ArrowRight, Rocket, Users, Wallet } from 'lucide-react'
|
import { ArrowRight } from 'lucide-react'
|
||||||
import { Button } from '../../components/ui'
|
import { Button } from '../../components/ui'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { PaymentReminderPreview } from './PaymentReminderPreview'
|
||||||
|
|
||||||
type WelcomeStepProps = {
|
type WelcomeStepProps = {
|
||||||
name: string
|
name: string
|
||||||
onNext: () => void
|
onNext: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const STEPS_TO_SETUP = [
|
/* El recorrido real del alta, en orden. Cobros y WhatsApp van en el medio y son
|
||||||
{
|
opcionales (y solo de Pro): la lista lo dice en vez de prometer un "cobrá al
|
||||||
icon: Wallet,
|
instante" que con Free no existe. Labels: `onboarding:welcome.arc.*`. */
|
||||||
title: 'welcome.step1Title',
|
const ARC = ['setup', 'connect', 'group'] as const
|
||||||
description: 'welcome.step1',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: Users,
|
|
||||||
title: 'welcome.step2Title',
|
|
||||||
description: 'welcome.step2',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
icon: Rocket,
|
|
||||||
title: 'welcome.step3Title',
|
|
||||||
description: 'welcome.step3',
|
|
||||||
},
|
|
||||||
] as const
|
|
||||||
|
|
||||||
export function WelcomeStep({ name, onNext }: WelcomeStepProps) {
|
export function WelcomeStep({ name, onNext }: WelcomeStepProps) {
|
||||||
const { t } = useTranslation('onboarding')
|
const { t } = useTranslation('onboarding')
|
||||||
return (
|
return (
|
||||||
<section className="space-y-6">
|
<section className="space-y-7">
|
||||||
<header className="space-y-2 text-center">
|
<header className="space-y-2">
|
||||||
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft">
|
<h1 className="text-[1.75rem] font-bold leading-tight tracking-tight text-primary text-balance">
|
||||||
<Rocket className="size-7 text-accent" />
|
{t('welcome.title', { name })}
|
||||||
</span>
|
</h1>
|
||||||
<h1 className="text-2xl font-bold text-primary">{t('welcome.title', { name })}</h1>
|
<p className="text-[0.9375rem] text-foreground/70 text-pretty">{t('welcome.description')}</p>
|
||||||
<p className="text-sm text-foreground/60">
|
|
||||||
{t('welcome.description')}
|
|
||||||
</p>
|
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
<PaymentReminderPreview caption={t('welcome.previewCaption')} />
|
||||||
|
|
||||||
<ol className="space-y-3">
|
<ol className="space-y-3">
|
||||||
{STEPS_TO_SETUP.map(({ icon: Icon, title, description }) => (
|
{ARC.map((id, index) => (
|
||||||
<li
|
<li key={id} className="flex gap-3">
|
||||||
key={title}
|
<span
|
||||||
className="flex items-center gap-3 rounded-xl border border-border bg-surface p-4"
|
aria-hidden="true"
|
||||||
|
className="mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full border border-border text-xs font-semibold tabular-nums text-foreground/60"
|
||||||
>
|
>
|
||||||
<span className="rounded-lg bg-accent-soft p-2">
|
{index + 1}
|
||||||
<Icon className="size-5 text-accent" />
|
|
||||||
</span>
|
</span>
|
||||||
<div>
|
<div className="min-w-0">
|
||||||
<p className="text-sm font-semibold text-primary">{t(title)}</p>
|
<p className="text-sm font-semibold text-primary">{t(`welcome.arc.${id}Title`)}</p>
|
||||||
<p className="text-xs text-foreground/60">{t(description)}</p>
|
<p className="text-sm text-foreground/60">{t(`welcome.arc.${id}`)}</p>
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<Button variant="primary" size="md" className="w-full" onClick={onNext}>
|
<Button variant="primary" size="lg" className="w-full" onClick={onNext}>
|
||||||
{t('welcome.start')}
|
{t('welcome.start')}
|
||||||
<ArrowRight className="size-4" />
|
<ArrowRight className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
whatsappStatusLabel,
|
whatsappStatusLabel,
|
||||||
} from '../whatsapp'
|
} from '../whatsapp'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
|
import { PaymentReminderPreview } from './PaymentReminderPreview'
|
||||||
|
|
||||||
type WhatsappStepProps = {
|
type WhatsappStepProps = {
|
||||||
/** Resultado de una vinculación por redirect, leído de `?wa=` al volver. */
|
/** Resultado de una vinculación por redirect, leído de `?wa=` al volver. */
|
||||||
@@ -46,7 +47,11 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
|||||||
</p>
|
</p>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
{feedback?.kind === 'success' || (isConnected && !feedback) ? (
|
{!isConnected ? <PaymentReminderPreview caption={t('whatsapp.previewCaption')} /> : null}
|
||||||
|
|
||||||
|
{/* El banner es la confirmación de una vinculación recién hecha. Si ya
|
||||||
|
estaba vinculado, alcanza con el estado de la tarjeta. */}
|
||||||
|
{feedback?.kind === 'success' ? (
|
||||||
<p className="flex items-start gap-2 rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
|
<p className="flex items-start gap-2 rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
|
||||||
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
|
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
|
||||||
{statusQuery.data?.displayPhoneNumber
|
{statusQuery.data?.displayPhoneNumber
|
||||||
@@ -56,7 +61,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{feedback?.kind === 'error' ? (
|
{feedback?.kind === 'error' ? (
|
||||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
<p role="alert" className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||||
{whatsappCallbackErrorMessage(feedback.reason)}
|
{whatsappCallbackErrorMessage(feedback.reason)}
|
||||||
</p>
|
</p>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -79,6 +84,13 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
|||||||
statusQuery.error instanceof ApiError ? statusQuery.error.status : null,
|
statusQuery.error instanceof ApiError ? statusQuery.error.status : null,
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
|
) : isConnected ? (
|
||||||
|
<p className="text-sm text-foreground/60">
|
||||||
|
{statusQuery.data?.displayPhoneNumber
|
||||||
|
? t('whatsapp.connectedWith', { phone: statusQuery.data.displayPhoneNumber })
|
||||||
|
: t('whatsapp.connected')}{' '}
|
||||||
|
{t('whatsapp.perGroup')}
|
||||||
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<p className="text-sm text-foreground/60">
|
<p className="text-sm text-foreground/60">
|
||||||
{usesQr
|
{usesQr
|
||||||
@@ -93,6 +105,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
|||||||
<div className="px-4 py-3">
|
<div className="px-4 py-3">
|
||||||
<Button
|
<Button
|
||||||
variant="primary"
|
variant="primary"
|
||||||
|
size="lg"
|
||||||
className="w-full"
|
className="w-full"
|
||||||
disabled={connection.isStarting || statusQuery.isError}
|
disabled={connection.isStarting || statusQuery.isError}
|
||||||
onClick={() => void connection.start('onboarding')}
|
onClick={() => void connection.start('onboarding')}
|
||||||
@@ -109,7 +122,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{connection.error ? (
|
{connection.error ? (
|
||||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
<p role="alert" className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
<WhatsappLinkModal
|
<WhatsappLinkModal
|
||||||
@@ -119,11 +132,11 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Button variant="outline" onClick={onBack} className="hidden lg:inline-flex">
|
<Button variant="outline" size="lg" onClick={onBack}>
|
||||||
<ArrowLeft className="size-4" />
|
<ArrowLeft className="size-4" />
|
||||||
{t('common:actions.back')}
|
{t('common:actions.back')}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="outline" className="flex-1 lg:flex-none" onClick={onNext}>
|
<Button variant={isConnected ? 'primary' : 'outline'} size="lg" className="flex-1" onClick={onNext}>
|
||||||
{isConnected ? t('continue') : t('later')}
|
{isConnected ? t('continue') : t('later')}
|
||||||
<ArrowRight className="size-4" />
|
<ArrowRight className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export type OnboardingStepId =
|
|||||||
|
|
||||||
/** Labels: `onboarding:steps.<id>`. */
|
/** Labels: `onboarding:steps.<id>`. */
|
||||||
|
|
||||||
const ALL_STEPS: readonly OnboardingStepId[] = [
|
export const ALL_STEPS: readonly OnboardingStepId[] = [
|
||||||
'welcome',
|
'welcome',
|
||||||
'country',
|
'country',
|
||||||
'plan',
|
'plan',
|
||||||
@@ -45,3 +45,31 @@ export function resumeStep(status: OnboardingStatusDto): OnboardingStepId | null
|
|||||||
if (status.step === 'PAYMENT_CONNECTED') return status.whatsappConnected ? 'group' : 'whatsapp'
|
if (status.step === 'PAYMENT_CONNECTED') return status.whatsappConnected ? 'group' : 'whatsapp'
|
||||||
return 'payment'
|
return 'payment'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Lee `?step=` de la URL: cualquier valor desconocido es "sin paso". */
|
||||||
|
export function parseStep(value: unknown): OnboardingStepId | undefined {
|
||||||
|
return typeof value === 'string' && (ALL_STEPS as readonly string[]).includes(value)
|
||||||
|
? (value as OnboardingStepId)
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pasos que necesitan el plan ya elegido (el backend da 409 `plan_not_selected`). */
|
||||||
|
const NEEDS_PLAN: readonly OnboardingStepId[] = ['payment', 'whatsapp', 'group', 'done']
|
||||||
|
|
||||||
|
/**
|
||||||
|
* El paso que realmente se muestra para el que pide la URL. El paso vive en
|
||||||
|
* `?step=` (así el back del dispositivo retrocede un paso), y una URL puede
|
||||||
|
* pedir uno que hoy no corresponde: sin plan no se pasa de Plan, con Free no
|
||||||
|
* hay Cobros ni WhatsApp, "Listo" sin grupo creado vuelve al formulario, y con
|
||||||
|
* el grupo ya creado no se vuelve a mostrar el formulario (crearía otro).
|
||||||
|
*/
|
||||||
|
export function effectiveStep(
|
||||||
|
requested: OnboardingStepId,
|
||||||
|
{ plan, hasCreatedGroup }: { plan: Plan | null; hasCreatedGroup: boolean },
|
||||||
|
): OnboardingStepId {
|
||||||
|
if (hasCreatedGroup) return 'done'
|
||||||
|
if (plan === null && NEEDS_PLAN.includes(requested)) return 'plan'
|
||||||
|
if (!visibleSteps(plan).includes(requested)) return 'group'
|
||||||
|
if (requested === 'done') return 'group'
|
||||||
|
return requested
|
||||||
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user