development #14
11
.env.example
11
.env.example
@@ -35,6 +35,17 @@ BETTER_AUTH_SECRET=""
|
||||
# EMAIL_SERVER_PASSWORD=""
|
||||
# EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
|
||||
# Mercado Pago (OAuth Authorization Code + PKCE). Opcionales: sin credenciales
|
||||
# GET /mp/connect responde 503 mp_not_configured y la app sigue funcionando
|
||||
# (el paso "Cobros" del onboarding es salteable).
|
||||
# Generate it with: openssl rand -base64 32 -- exactly 32 bytes once decoded.
|
||||
# TOKEN_ENCRYPTION_KEY=""
|
||||
# Redirect URL registered in the Mercado Pago panel, character for character.
|
||||
# The panel requires HTTPS (no http://localhost): local dev goes through a tunnel.
|
||||
# MP_REDIRECT_URI="https://api.gruperly.com/api/v1/mp/callback"
|
||||
# MP_CLIENT_ID=""
|
||||
# MP_CLIENT_SECRET=""
|
||||
|
||||
# Only if you want the API on another domain: it is baked into the Vite bundle
|
||||
# and forces you to drop the /api proxy from apps/web/nginx.conf. Empty = same
|
||||
# origin (recommended).
|
||||
|
||||
@@ -31,13 +31,14 @@ 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/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
|
||||
- `src/logger.ts` — pino + pino-pretty.
|
||||
- Módulos existentes: `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza.
|
||||
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `groups`, `attendees`, `payments`, `waitlist` (listados paginados `{ data, pagination }`). `group-waitlist` y `group-preregistrations` no se montan en `app.ts`: se enganchan en `modules/groups/routes.ts`. El link compartido (`Group.inviteToken`, público en `/api/v1/invitations`) **no** da de alta en `attendees`: crea una `GroupPreRegistration` (PENDING) que el dueño aprueba (`POST /groups/:gid/preregistrations/:id/approve` → attendee si hay cupo, si no waitlist) o rechaza.
|
||||
- `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/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
|
||||
|
||||
## 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`.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
52
README.md
52
README.md
@@ -67,6 +67,56 @@ En DevTools → Application: el manifest sin warnings, el service worker `activa
|
||||
1. Crea una base PostgreSQL y copia `apps/backend/.env.example` → `apps/backend/.env`, ajustando `DATABASE_URL`.
|
||||
2. Ejecuta `bun --filter @gruperly/backend db:generate` y `bun --filter @gruperly/backend db:push` (o `bun --filter @gruperly/backend db:migrate` en desarrollo).
|
||||
|
||||
## Mercado Pago (OAuth)
|
||||
|
||||
Los cobros llegan a la cuenta del profesor a través de una app de Mercado Pago en modo directo: el profesor autoriza desde el panel de MP y los pagos entran en su propia cuenta, sin comisión ni split de plataforma (`platform_id=mp`). Los links de pago, webhooks y WhatsApp quedan fuera de este módulo.
|
||||
|
||||
**Panel de Mercado Pago** (Developer panel → Tu aplicación):
|
||||
|
||||
- **Redirect URL**: el panel la exige en **HTTPS** (rechaza `http://localhost`) y tiene que coincidir carácter por carácter con `MP_REDIRECT_URI`. En local, meté un túnel delante del backend y registrá esa URL HTTPS tanto en el panel como en la env var: `ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000` (el *dev domain* de ngrok es fijo por cuenta, gratis) o un túnel nombrado de Cloudflare (`cloudflared tunnel route dns …`). `WEB_URL` y `VITE_API_URL` siguen en localhost: el túnel solo lo usa el navegador para volver desde MP. Los *quick tunnels* de cloudflared generan una URL nueva en cada arranque, así que obligan a regenerar la URL en el panel y en la env var cada reinicio.
|
||||
- **PKCE (S256)**: activado. El `code_verifier` se genera y se consume en el servidor, nunca pasa por el navegador.
|
||||
- **Permisos**: `offline_access read write`. Sin `offline_access` Mercado Pago no devuelve *refresh token* y la renovación automática no tiene con qué trabajar.
|
||||
|
||||
**Variables de entorno** (`apps/backend/.env` en local, pestaña Environment del compose en Dokploy):
|
||||
|
||||
| Variable | ¿Obligatoria? | Descripción |
|
||||
| --- | --- | --- |
|
||||
| `MP_CLIENT_ID` | para vincular | Client ID de la app de MP |
|
||||
| `MP_CLIENT_SECRET` | para vincular | Secret de la app de MP |
|
||||
| `MP_REDIRECT_URI` | para vincular | Callback registrado en el panel |
|
||||
| `TOKEN_ENCRYPTION_KEY` | para vincular | `openssl rand -base64 32`. Cifra los tokens en reposo con AES-256-GCM. Si no decodifica a 32 bytes, el backend lo rechaza al guardar la cuenta |
|
||||
|
||||
Sin las cuatro, `GET /api/v1/mp/connect` responde `503 mp_not_configured` y la app sigue funcionando: el paso "Cobros" del onboarding es **salteable**.
|
||||
|
||||
En local se usan las credenciales de **producción** de la app: no existe OAuth sandbox en MP (las credenciales de prueba del panel son solo Public Key y Access Token, sin Client ID/secret). No hay riesgo, porque el OAuth solo vincula una cuenta y no mueve dinero; se prueba con una cuenta propia y se desvincúa con `DELETE /mp/connect`. Los pagos, cuando existan, se prueban aparte con credenciales de prueba.
|
||||
|
||||
### Cómo funciona
|
||||
|
||||
```text
|
||||
onboarding/ajustes → GET /mp/connect → { authorizationUrl } (state + PKCE en la DB, 10 min)
|
||||
→ https://auth.mercadopago.com/authorization
|
||||
→ GET /mp/callback → ?code&state (se quema el state, se cambia el código)
|
||||
→ 302 a /onboarding?mp=success o /settings?mp=error&reason=…
|
||||
```
|
||||
|
||||
- La API de MP es `GET /mp/status` (`none` | `active` | `requires_reauth`) y `DELETE /mp/connect` (desvincula; conserva la fila para que la cuenta de MP quede reservada al mismo profesor).
|
||||
- Los tokens se guardan cifrados; `status` nunca devuelve tokens, scope ni el id completo de MP (solo los últimos 4 dígitos, para que el profesor confirme que vinculó la cuenta correcta).
|
||||
- Un cron diario (`17 3 * * *` UTC) renueva las cuentas que vencen en menos de 30 días, en lotes de 20 con `FOR UPDATE SKIP LOCKED`. Solo `invalid_grant` marca la cuenta como `requires_reauth`; un 5xx o un fallo de red se reintenta al día siguiente, para no bloquear a un profesor por una tarde mala de MP. `apps/backend/src/modules/mp/access-token.ts` (`getMpAccessToken`) renueva bajo demanda si el token está por vencer.
|
||||
|
||||
### Verificar a mano
|
||||
|
||||
1. `bun dev`, crear una cuenta nueva y llegar al paso "Cobros".
|
||||
2. **Vincular**: "Vincular cuenta" debe abrir el consent de MP; al aceptar se vuelve a `/onboarding` con el mensaje de cuenta vinculada, y Ajustes → Cobros muestra "Vinculada" con los últimos 4 dígitos.
|
||||
3. **Saltear**: con una cuenta nueva, "Lo hago después" deja crear el grupo igual; el resumen final ofrece vincularlo después desde Ajustes.
|
||||
4. **Denegar**: en la pantalla de consentimiento de MP, elegir no autorizar → vuelve con "No autorizaste la conexión en Mercado Pago" y el estado sigue en `none`.
|
||||
5. **Desvincular**: Ajustes → Cobros → Desvincular (pide confirmación) deja el estado en `none` y la tarjeta de cuenta conectada desaparece.
|
||||
6. **Reautenticación**: `UPDATE users SET ...` no hace falta; para forzarla, `UPDATE mp_accounts SET status = 'REQUIRES_REAUTH'` y recargar cualquier pantalla: aparece el aviso global (excepto en Ajustes, donde la tarjeta ofrece la acción).
|
||||
|
||||
```bash
|
||||
# Estado real, con la sesión del profesor:
|
||||
curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: <cookie de sesión>' | jq
|
||||
```
|
||||
|
||||
## Deploy en producción (Docker / Dokploy)
|
||||
|
||||
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).
|
||||
@@ -87,6 +137,8 @@ El compose las interpola desde el entorno. En Dokploy van en la pestaña **Envir
|
||||
| `BETTER_AUTH_SECRET` | sí | `openssl rand -base64 32` |
|
||||
| `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` | no | Login social. Si faltan, no se registra el provider |
|
||||
| `EMAIL_PROVIDER`, `EMAIL_SERVER_*`, `EMAIL_FROM` | no | Salida de emails (mismos nombres que en `apps/backend/.env.example`) |
|
||||
| `MP_CLIENT_ID`, `MP_CLIENT_SECRET`, `MP_REDIRECT_URI` | no | Vinculación con Mercado Pago. Sin ellos, `/mp/connect` responde 503 y la app anda igual (ver [Mercado Pago](#mercadopago-oauth)) |
|
||||
| `TOKEN_ENCRYPTION_KEY` | no (sí para cobrar) | `openssl rand -base64 32`. Cifra los tokens de MP en reposo |
|
||||
| `VITE_API_URL` | no | Se hornea en el bundle de web. Vacío = mismo origen. Solo si querés la API en otro dominio |
|
||||
| `RUN_MIGRATIONS` | no | `false` para arrancar sin aplicar migraciones |
|
||||
|
||||
|
||||
@@ -19,3 +19,15 @@ EMAIL_SERVER_PORT="587"
|
||||
EMAIL_SERVER_USER=""
|
||||
EMAIL_SERVER_PASSWORD=""
|
||||
EMAIL_FROM="Gruperly <no-reply@gruperly.com>"
|
||||
|
||||
# Mercado Pago (OAuth, Authorization Code + PKCE)
|
||||
MP_CLIENT_ID=""
|
||||
MP_CLIENT_SECRET=""
|
||||
# Debe coincidir exactamente con la "Redirect URL" de la app en el panel de MP.
|
||||
# El panel exige HTTPS (rechaza http://localhost): en local usá un túnel
|
||||
# (p. ej. ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000) y cargá
|
||||
# la URL del túnel acá y en el panel.
|
||||
MP_REDIRECT_URI=""
|
||||
# Clave de 32 bytes en base64 para cifrar los tokens de MP en reposo (AES-256-GCM).
|
||||
# Generar con: openssl rand -base64 32
|
||||
TOKEN_ENCRYPTION_KEY=""
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Mercado Pago OAuth (Authorization Code + PKCE). Replaces the simulated
|
||||
-- payment setup, where a fake access token was stored in plaintext.
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MpAccountStatus" AS ENUM ('ACTIVE', 'REQUIRES_REAUTH', 'REVOKED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "mp_accounts" (
|
||||
"id" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"mp_user_id" TEXT NOT NULL,
|
||||
"access_token_enc" TEXT NOT NULL,
|
||||
"refresh_token_enc" TEXT NOT NULL,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"scope" TEXT,
|
||||
"live_mode" BOOLEAN NOT NULL DEFAULT false,
|
||||
"status" "MpAccountStatus" NOT NULL DEFAULT 'ACTIVE',
|
||||
"connected_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "mp_accounts_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "mp_oauth_states" (
|
||||
"state" TEXT NOT NULL,
|
||||
"owner_id" TEXT NOT NULL,
|
||||
"code_verifier" TEXT NOT NULL,
|
||||
"return_to" TEXT NOT NULL,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "mp_oauth_states_pkey" PRIMARY KEY ("state")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "mp_accounts_status_expiresAt_idx" ON "mp_accounts"("status", "expires_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "mp_accounts_ownerId_key" ON "mp_accounts"("owner_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "mp_accounts_mpUserId_key" ON "mp_accounts"("mp_user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "mp_oauth_states_expiresAt_idx" ON "mp_oauth_states"("expires_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "mp_accounts" ADD CONSTRAINT "mp_accounts_ownerId_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "merchant_accounts";
|
||||
|
||||
-- DropEnum
|
||||
DROP TYPE "PaymentProvider";
|
||||
@@ -18,7 +18,7 @@ model User {
|
||||
orgMemberships Member[]
|
||||
orgInvitations Invitation[] @relation("InvitedBy")
|
||||
waitlist WaitlistEntry[]
|
||||
merchantAccount MerchantAccount?
|
||||
mpAccount MpAccount?
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
@@ -182,22 +182,49 @@ model GroupPreRegistration {
|
||||
@@map("group_pre_registrations")
|
||||
}
|
||||
|
||||
enum PaymentProvider {
|
||||
MERCADO_PAGO
|
||||
STRIPE
|
||||
enum MpAccountStatus {
|
||||
ACTIVE
|
||||
REQUIRES_REAUTH
|
||||
REVOKED
|
||||
}
|
||||
|
||||
model MerchantAccount {
|
||||
// Mercado Pago account linked by a teacher through OAuth (Authorization Code + PKCE).
|
||||
// Tokens are stored encrypted (AES-256-GCM); there is a single active account per
|
||||
// teacher and a Mercado Pago user cannot be linked to two teachers.
|
||||
model MpAccount {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique(map: "merchant_accounts_userId_key") @map("user_id")
|
||||
provider PaymentProvider
|
||||
accessToken String? @map("access_token")
|
||||
sandbox Boolean @default(true)
|
||||
ownerId String @unique(map: "mp_accounts_ownerId_key") @map("owner_id")
|
||||
mpUserId String @unique(map: "mp_accounts_mpUserId_key") @map("mp_user_id")
|
||||
accessTokenEnc String @map("access_token_enc")
|
||||
refreshTokenEnc String @map("refresh_token_enc")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
scope String?
|
||||
liveMode Boolean @default(false) @map("live_mode")
|
||||
status MpAccountStatus @default(ACTIVE)
|
||||
connectedAt DateTime @default(now()) @map("connected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade, map: "merchant_accounts_userId_fkey")
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade, map: "mp_accounts_ownerId_fkey")
|
||||
|
||||
@@map("merchant_accounts")
|
||||
// The daily refresh job looks for ACTIVE accounts expiring within 30 days.
|
||||
@@index([status, expiresAt], map: "mp_accounts_status_expiresAt_idx")
|
||||
@@map("mp_accounts")
|
||||
}
|
||||
|
||||
// Pending OAuth authorization: the `state` sent to Mercado Pago plus the PKCE
|
||||
// `code_verifier`. The `state` is the primary key because consuming it (deleting
|
||||
// the row) is what makes it single use.
|
||||
model MpOAuthState {
|
||||
state String @id
|
||||
ownerId String @map("owner_id")
|
||||
codeVerifier String @map("code_verifier")
|
||||
// Constrained to 'onboarding' | 'settings'; decides where the callback lands.
|
||||
returnTo String @map("return_to")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
// Expired rows are swept on every new authorization request.
|
||||
@@index([expiresAt], map: "mp_oauth_states_expiresAt_idx")
|
||||
@@map("mp_oauth_states")
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { groupsRoutes } from './modules/groups';
|
||||
import { healthCheckRoutes } from './modules/health-check';
|
||||
import { homeRoutes } from './modules/home';
|
||||
import { invitationsRoutes } from './modules/invitations';
|
||||
import { mpRoutes } from './modules/mp';
|
||||
import { onboardingRoutes } from './modules/onboarding';
|
||||
import { paymentsRoutes } from './modules/payments';
|
||||
import { waitlistRoutes } from './modules/waitlist';
|
||||
@@ -44,6 +45,7 @@ api.route('/invitations', invitationsRoutes);
|
||||
api.route('/groups', groupsRoutes);
|
||||
api.route('/home', homeRoutes);
|
||||
api.route('/onboarding', onboardingRoutes);
|
||||
api.route('/mp', mpRoutes);
|
||||
api.route('/attendees', attendeesRoutes);
|
||||
api.route('/payments', paymentsRoutes);
|
||||
api.route('/waitlist', waitlistRoutes);
|
||||
|
||||
@@ -71,13 +71,49 @@ export function notFoundResourceProblem(resourceName: string, id: string): Probl
|
||||
return notFoundProblem(`${resourceName} ${id}`);
|
||||
}
|
||||
|
||||
export function paymentNotSetupProblem(): ProblemDetails {
|
||||
export function mpNotConnectedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Vinculá una cuenta de cobro antes de crear tu primer grupo.',
|
||||
code: 'payment_not_setup',
|
||||
detail: 'No tenés una cuenta de Mercado Pago vinculada.',
|
||||
code: 'mp_not_connected',
|
||||
});
|
||||
}
|
||||
|
||||
export function mpRequiresReauthProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Tu cuenta de Mercado Pago necesita volver a vincularse.',
|
||||
code: 'mp_requires_reauth',
|
||||
});
|
||||
}
|
||||
|
||||
export function mpAccountInUseProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.',
|
||||
code: 'mp_account_in_use',
|
||||
});
|
||||
}
|
||||
|
||||
/** The server is missing MP_CLIENT_ID / MP_CLIENT_SECRET / MP_REDIRECT_URI. */
|
||||
export function mpNotConfiguredProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/mercadopago-not-configured`,
|
||||
title: 'Service Unavailable',
|
||||
status: 503,
|
||||
detail: 'La vinculación con Mercado Pago no está disponible en este momento.',
|
||||
code: 'mp_not_configured',
|
||||
};
|
||||
}
|
||||
|
||||
/** Mercado Pago refused the request, or could not be reached. */
|
||||
export function mpProviderErrorProblem(): ProblemDetails {
|
||||
return {
|
||||
type: `${PROBLEM_DOMAIN}/problems/mercadopago-unavailable`,
|
||||
title: 'Bad Gateway',
|
||||
status: 502,
|
||||
detail: 'No pudimos completar la vinculación con Mercado Pago.',
|
||||
code: 'mp_provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
export function onboardingAlreadyCompletedProblem(): ProblemDetails {
|
||||
return conflictProblem({
|
||||
detail: 'Ya completaste el onboarding de Gruperly.',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma, PrismaClient } from '@generated/prisma/client';
|
||||
import type { Prisma } from '@generated/prisma/client';
|
||||
import { Role } from '@generated/prisma/client';
|
||||
import type {
|
||||
CreateFirstGroup as CreateGroupInput,
|
||||
@@ -6,13 +6,11 @@ import type {
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { paymentNotSetupProblem } from '@/http/problem-builders';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { type GroupRecord, toGroupDto } from '../../lib';
|
||||
|
||||
type CreateGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'group' | 'groupMember' | 'merchantAccount'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
@@ -23,14 +21,8 @@ export class CreateGroup {
|
||||
data: CreateGroupInput,
|
||||
userId: string,
|
||||
): Promise<Result<CreateGroupResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const unitOfWork = this.deps.unitOfWork ?? new UnitOfWork(prisma);
|
||||
|
||||
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } });
|
||||
if (!merchantAccount) {
|
||||
return err(paymentNotSetupProblem());
|
||||
}
|
||||
|
||||
const transaction = unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const created = await tx.group.create({
|
||||
|
||||
58
apps/backend/src/modules/mp/access-token.ts
Normal file
58
apps/backend/src/modules/mp/access-token.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { mpNotConnectedProblem, mpRequiresReauthProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { RefreshMpAccount } from './jobs';
|
||||
import { openToken } from './lib';
|
||||
|
||||
export type MpTokenAccount = {
|
||||
accountId: string;
|
||||
accessToken: string;
|
||||
expiresAt: Date;
|
||||
};
|
||||
|
||||
/**
|
||||
* Below this, the on-demand path refreshes. The daily job renews much earlier
|
||||
* (30 days out), so hitting this only means the job did not run, which is exactly
|
||||
* when a payment link cannot be allowed to fail.
|
||||
*/
|
||||
const NEAR_EXPIRY_MS = 5 * 60 * 1000;
|
||||
|
||||
type GetMpAccessTokenDeps = {
|
||||
db?: Pick<PrismaClient, 'mpAccount'>;
|
||||
refresh?: RefreshMpAccount;
|
||||
};
|
||||
|
||||
/**
|
||||
* A usable access token for a teacher's Mercado Pago account.
|
||||
*
|
||||
* This is the entry point for payment links and webhook verification, so it fails
|
||||
* explicitly instead of returning something unusable: an unlinked account and an
|
||||
* account that needs re-authorization are different problems and the caller has
|
||||
* to be able to tell them apart.
|
||||
*/
|
||||
export async function getMpAccessToken(
|
||||
ownerId: string,
|
||||
deps: GetMpAccessTokenDeps = {},
|
||||
): Promise<Result<MpTokenAccount, ProblemDetails>> {
|
||||
const db = deps.db ?? prisma;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { ownerId } });
|
||||
if (!account) return err(mpNotConnectedProblem());
|
||||
if (account.status !== 'ACTIVE') return err(mpRequiresReauthProblem());
|
||||
|
||||
if (account.expiresAt.getTime() - Date.now() > NEAR_EXPIRY_MS) {
|
||||
return ok({
|
||||
accountId: account.id,
|
||||
accessToken: openToken(account.accessTokenEnc),
|
||||
expiresAt: account.expiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
const refresh = deps.refresh ?? new RefreshMpAccount();
|
||||
const refreshed = await refresh.execute(account.id);
|
||||
if (!refreshed.ok) return refreshed;
|
||||
|
||||
return ok(refreshed.value);
|
||||
}
|
||||
50
apps/backend/src/modules/mp/features/callback/route.ts
Normal file
50
apps/backend/src/modules/mp/features/callback/route.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import type { MpCallbackQuery, MpCallbackReason, ProblemDetails } from '@gruperly/shared';
|
||||
import { MpCallbackQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { validate } from '@/http/validate';
|
||||
import { logger } from '@/logger';
|
||||
import { buildMpReturnUrl, getWebOrigin } from '../../lib';
|
||||
import { CompleteMpAuthorization, type MpCallbackResult } from './use-case';
|
||||
|
||||
/**
|
||||
* The browser arrives here from Mercado Pago, so this route always answers with
|
||||
* a redirect back to the app and never renders or returns a problem body: there
|
||||
* is nothing on the other side to render a failure into.
|
||||
*/
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', validate.query(MpCallbackQuerySchema), async (c) => {
|
||||
const { code, state, error } = c.req.valid('query') as MpCallbackQuery;
|
||||
|
||||
const user = c.get('user');
|
||||
if (!user) {
|
||||
// Without a session there is nobody to credit the tokens to. The state was
|
||||
// issued to whoever was signed in when the flow started, so guessing would
|
||||
// be a way to attach somebody else's Mercado Pago account to this account.
|
||||
logger.warn('Mercado Pago callback arrived without a session');
|
||||
return c.redirect(new URL('/login', getWebOrigin()).toString());
|
||||
}
|
||||
|
||||
const useCase = new CompleteMpAuthorization();
|
||||
const result = await useCase.execute({ code, state, error });
|
||||
|
||||
if (!result.ok) {
|
||||
logger.warn(
|
||||
{ code: result.error.code, status: result.error.status },
|
||||
'Mercado Pago callback failed',
|
||||
);
|
||||
}
|
||||
|
||||
const outcome = result.ok ? result.value.outcome : problemToOutcome(result.error);
|
||||
const returnTo = result.ok ? result.value.returnTo : 'settings';
|
||||
|
||||
return c.redirect(buildMpReturnUrl(getWebOrigin(), returnTo, outcome));
|
||||
});
|
||||
|
||||
/** Reduces an internal problem to a reason code that is safe in a URL. */
|
||||
function problemToOutcome(problem: ProblemDetails): MpCallbackResult['outcome'] {
|
||||
const reason: MpCallbackReason = problem.code === 'mp_account_in_use' ? 'mp_account_in_use' : 'mp_error';
|
||||
return { kind: 'error', reason };
|
||||
}
|
||||
|
||||
export default route;
|
||||
145
apps/backend/src/modules/mp/features/callback/use-case.ts
Normal file
145
apps/backend/src/modules/mp/features/callback/use-case.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { MpCallbackReason, MpReturnTo, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
mpAccountInUseProblem,
|
||||
mpNotConfiguredProblem,
|
||||
mpProviderErrorProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import {
|
||||
exchangeAuthorizationCode,
|
||||
getMpOAuthConfig,
|
||||
type MpTokenResponse,
|
||||
sealToken,
|
||||
} from '../../lib';
|
||||
|
||||
type CompleteMpAuthorizationDeps = {
|
||||
db?: Pick<PrismaClient, 'mpOAuthState' | 'mpAccount'>;
|
||||
/** Swapped in tests; defaults to the real Mercado Pago exchange. */
|
||||
exchange?: typeof exchangeAuthorizationCode;
|
||||
};
|
||||
|
||||
export type MpCallbackResult = {
|
||||
returnTo: MpReturnTo;
|
||||
outcome: { kind: 'success' } | { kind: 'error'; reason: MpCallbackReason };
|
||||
};
|
||||
|
||||
/** Prisma's unique-constraint violation on `mp_accounts_mpUserId_key`. */
|
||||
const UNIQUE_VIOLATION = 'P2002';
|
||||
|
||||
/** Where we land if the state is gone and there is nothing to recover. */
|
||||
const DEFAULT_RETURN_TO: MpReturnTo = 'settings';
|
||||
|
||||
export class CompleteMpAuthorization {
|
||||
constructor(private readonly deps: CompleteMpAuthorizationDeps = {}) {}
|
||||
|
||||
async execute(input: {
|
||||
code?: string;
|
||||
state?: string;
|
||||
error?: string;
|
||||
}): Promise<Result<MpCallbackResult, ProblemDetails>> {
|
||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||
try {
|
||||
config = getMpOAuthConfig();
|
||||
} catch (configError) {
|
||||
logger.error({ err: configError }, 'Mercado Pago is not configured');
|
||||
return err(mpNotConfiguredProblem());
|
||||
}
|
||||
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
// The teacher closed the consent screen. There is nothing to exchange, but
|
||||
// the state is still burned so it cannot be replayed later.
|
||||
if (input.error) {
|
||||
if (input.state) {
|
||||
await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
||||
}
|
||||
return failure('mp_denied');
|
||||
}
|
||||
|
||||
if (!input.code || !input.state) {
|
||||
return failure('invalid_state');
|
||||
}
|
||||
|
||||
const stored = await db.mpOAuthState.findUnique({ where: { state: input.state } });
|
||||
if (!stored || stored.expiresAt.getTime() <= Date.now()) {
|
||||
return failure('invalid_state');
|
||||
}
|
||||
|
||||
const returnTo: MpReturnTo = stored.returnTo === 'onboarding' ? 'onboarding' : DEFAULT_RETURN_TO;
|
||||
|
||||
// Single use, and burned *before* we talk to Mercado Pago: a `count` of zero
|
||||
// means someone replayed a state we already consumed.
|
||||
const consumed = await db.mpOAuthState.deleteMany({ where: { state: input.state } });
|
||||
if (consumed.count === 0) {
|
||||
return failure('invalid_state', returnTo);
|
||||
}
|
||||
|
||||
const exchange = this.deps.exchange ?? exchangeAuthorizationCode;
|
||||
let tokens: MpTokenResponse;
|
||||
try {
|
||||
tokens = await exchange({
|
||||
clientId: config.clientId,
|
||||
clientSecret: config.clientSecret,
|
||||
redirectUri: config.redirectUri,
|
||||
code: input.code,
|
||||
codeVerifier: stored.codeVerifier,
|
||||
});
|
||||
} catch (exchangeError) {
|
||||
// `MpApiError` already logged the status and MP's own error code. Nothing
|
||||
// added here mentions the authorization code or the verifier.
|
||||
logger.error({ err: exchangeError }, 'Mercado Pago authorization could not be completed');
|
||||
return err(mpProviderErrorProblem());
|
||||
}
|
||||
|
||||
const claimed = await db.mpAccount.findUnique({ where: { mpUserId: tokens.mpUserId } });
|
||||
if (claimed && claimed.ownerId !== stored.ownerId) {
|
||||
return err(mpAccountInUseProblem());
|
||||
}
|
||||
|
||||
const encrypted = {
|
||||
accessTokenEnc: sealToken(tokens.accessToken),
|
||||
refreshTokenEnc: sealToken(tokens.refreshToken),
|
||||
expiresAt: new Date(Date.now() + tokens.expiresInSeconds * 1000),
|
||||
scope: tokens.scope,
|
||||
liveMode: tokens.liveMode,
|
||||
status: 'ACTIVE' as const,
|
||||
};
|
||||
|
||||
try {
|
||||
await db.mpAccount.upsert({
|
||||
where: { ownerId: stored.ownerId },
|
||||
create: { ownerId: stored.ownerId, mpUserId: tokens.mpUserId, ...encrypted },
|
||||
// Re-linking renews the credentials and clears a `requires_reauth`.
|
||||
update: { mpUserId: tokens.mpUserId, ...encrypted, connectedAt: new Date() },
|
||||
});
|
||||
} catch (writeError) {
|
||||
// Two teachers linked the same Mercado Pago id at the same time: the
|
||||
// unique index is the real arbiter, not the read above.
|
||||
if (isUniqueViolation(writeError)) {
|
||||
return err(mpAccountInUseProblem());
|
||||
}
|
||||
throw writeError;
|
||||
}
|
||||
|
||||
return ok({ returnTo, outcome: { kind: 'success' } });
|
||||
}
|
||||
}
|
||||
|
||||
function failure(
|
||||
reason: MpCallbackReason,
|
||||
returnTo: MpReturnTo = DEFAULT_RETURN_TO,
|
||||
): Result<MpCallbackResult, ProblemDetails> {
|
||||
return ok({ returnTo, outcome: { kind: 'error', reason } });
|
||||
}
|
||||
|
||||
function isUniqueViolation(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
(error as { code?: unknown }).code === UNIQUE_VIOLATION
|
||||
);
|
||||
}
|
||||
21
apps/backend/src/modules/mp/features/connect/route.ts
Normal file
21
apps/backend/src/modules/mp/features/connect/route.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { MpConnectQuery, MpReturnTo } from '@gruperly/shared';
|
||||
import { MpConnectQuerySchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { StartMpAuthorization } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', validate.query(MpConnectQuerySchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const { returnTo } = c.req.valid('query') as MpConnectQuery;
|
||||
|
||||
const useCase = new StartMpAuthorization();
|
||||
const result = await useCase.execute(user.id, returnTo as MpReturnTo);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
71
apps/backend/src/modules/mp/features/connect/use-case.ts
Normal file
71
apps/backend/src/modules/mp/features/connect/use-case.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type {
|
||||
MpAuthorizationUrlDto,
|
||||
MpReturnTo,
|
||||
ProblemDetails,
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { mpNotConfiguredProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import {
|
||||
buildAuthorizationUrl,
|
||||
codeChallengeFromVerifier,
|
||||
getMpOAuthConfig,
|
||||
newCodeVerifier,
|
||||
newState,
|
||||
} from '../../lib';
|
||||
|
||||
type StartMpAuthorizationDeps = { db?: Pick<PrismaClient, 'mpOAuthState'> };
|
||||
|
||||
/** The teacher has ten minutes to finish at Mercado Pago before the state dies. */
|
||||
export const STATE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export class StartMpAuthorization {
|
||||
constructor(private readonly deps: StartMpAuthorizationDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
ownerId: string,
|
||||
returnTo: MpReturnTo,
|
||||
): Promise<Result<MpAuthorizationUrlDto, ProblemDetails>> {
|
||||
let config: ReturnType<typeof getMpOAuthConfig>;
|
||||
try {
|
||||
config = getMpOAuthConfig();
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Mercado Pago is not configured');
|
||||
return err(mpNotConfiguredProblem());
|
||||
}
|
||||
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = new Date();
|
||||
|
||||
// Two jobs in one sweep: drop anything expired, and drop this teacher's
|
||||
// previous attempt so a teacher clicking twice cannot leave rows behind.
|
||||
await db.mpOAuthState.deleteMany({
|
||||
where: { OR: [{ expiresAt: { lt: now } }, { ownerId }] },
|
||||
});
|
||||
|
||||
const state = newState();
|
||||
const codeVerifier = newCodeVerifier();
|
||||
|
||||
await db.mpOAuthState.create({
|
||||
data: {
|
||||
state,
|
||||
ownerId,
|
||||
codeVerifier,
|
||||
returnTo,
|
||||
expiresAt: new Date(now.getTime() + STATE_TTL_MS),
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
authorizationUrl: buildAuthorizationUrl({
|
||||
clientId: config.clientId,
|
||||
redirectUri: config.redirectUri,
|
||||
state,
|
||||
codeChallenge: codeChallengeFromVerifier(codeVerifier),
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/mp/features/disconnect/route.ts
Normal file
16
apps/backend/src/modules/mp/features/disconnect/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { DisconnectMp } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.delete('/', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new DisconnectMp();
|
||||
const result = await useCase.execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
39
apps/backend/src/modules/mp/features/disconnect/use-case.ts
Normal file
39
apps/backend/src/modules/mp/features/disconnect/use-case.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { MpDisconnectResultDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type DisconnectMpDeps = { db?: Pick<PrismaClient, 'mpAccount'> };
|
||||
|
||||
/**
|
||||
* Mercado Pago has no seller-side token revocation endpoint for these grants, so
|
||||
* the tokens are dropped here and the row is kept as `REVOKED`. It is not
|
||||
* deleted on purpose: the Mercado Pago id stays reserved for the same teacher,
|
||||
* which stops someone else from claiming their account later.
|
||||
*/
|
||||
export class DisconnectMp {
|
||||
constructor(private readonly deps: DisconnectMpDeps = {}) {}
|
||||
|
||||
async execute(ownerId: string): Promise<Result<MpDisconnectResultDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { ownerId } });
|
||||
if (!account) {
|
||||
return ok({ disconnected: false });
|
||||
}
|
||||
|
||||
await db.mpAccount.update({
|
||||
where: { ownerId },
|
||||
data: {
|
||||
status: 'REVOKED',
|
||||
// The columns are NOT NULL, so the values are blanked rather than nulled.
|
||||
// Nothing reads them: every consumer filters on `status` first.
|
||||
accessTokenEnc: '',
|
||||
refreshTokenEnc: '',
|
||||
expiresAt: new Date(0),
|
||||
},
|
||||
});
|
||||
|
||||
return ok({ disconnected: true });
|
||||
}
|
||||
}
|
||||
16
apps/backend/src/modules/mp/features/status/route.ts
Normal file
16
apps/backend/src/modules/mp/features/status/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { GetMpStatus } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const useCase = new GetMpStatus();
|
||||
const result = await useCase.execute(user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
52
apps/backend/src/modules/mp/features/status/use-case.ts
Normal file
52
apps/backend/src/modules/mp/features/status/use-case.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { MpAccountStatus, MpStatusDto, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type GetMpStatusDeps = { db?: Pick<PrismaClient, 'mpAccount'> };
|
||||
|
||||
/** How many trailing digits of the Mercado Pago id we show, to confirm the account. */
|
||||
const SUFFIX_LENGTH = 4;
|
||||
|
||||
const NOT_LINKED: MpStatusDto = {
|
||||
status: 'none',
|
||||
liveMode: false,
|
||||
expiresAt: null,
|
||||
connectedAt: null,
|
||||
mpUserIdSuffix: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* An account the teacher unlinked stays in the table (so the Mercado Pago id
|
||||
* stays reserved for them), but from the outside it is simply "not linked".
|
||||
*/
|
||||
function toVisibleStatus(status: 'ACTIVE' | 'REQUIRES_REAUTH' | 'REVOKED'): MpAccountStatus {
|
||||
switch (status) {
|
||||
case 'ACTIVE':
|
||||
return 'active';
|
||||
case 'REQUIRES_REAUTH':
|
||||
return 'requires_reauth';
|
||||
case 'REVOKED':
|
||||
return 'none';
|
||||
}
|
||||
}
|
||||
|
||||
export class GetMpStatus {
|
||||
constructor(private readonly deps: GetMpStatusDeps = {}) {}
|
||||
|
||||
async execute(ownerId: string): Promise<Result<MpStatusDto, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { ownerId } });
|
||||
if (!account) return ok(NOT_LINKED);
|
||||
|
||||
// Deliberately no tokens and no scope in the response.
|
||||
return ok({
|
||||
status: toVisibleStatus(account.status),
|
||||
liveMode: account.liveMode,
|
||||
expiresAt: account.expiresAt.toISOString(),
|
||||
connectedAt: account.connectedAt.toISOString(),
|
||||
mpUserIdSuffix: account.mpUserId.slice(-SUFFIX_LENGTH),
|
||||
});
|
||||
}
|
||||
}
|
||||
3
apps/backend/src/modules/mp/index.ts
Normal file
3
apps/backend/src/modules/mp/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { getMpAccessToken, type MpTokenAccount } from './access-token';
|
||||
export { startMpJobs } from './jobs';
|
||||
export { default as mpRoutes } from './routes';
|
||||
7
apps/backend/src/modules/mp/jobs/index.ts
Normal file
7
apps/backend/src/modules/mp/jobs/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export {
|
||||
RENEWAL_WINDOW_DAYS,
|
||||
RefreshExpiringMpTokens,
|
||||
type RefreshExpiringMpTokensResult,
|
||||
} from './refresh-expiring-mp-tokens';
|
||||
export { type MpAccountStore, RefreshMpAccount } from './refresh-mp-account';
|
||||
export { startMpJobs } from './schedule';
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { refreshMpTokens } from '../lib';
|
||||
import { RefreshMpAccount } from './refresh-mp-account';
|
||||
|
||||
/**
|
||||
* Mercado Pago hands out access tokens valid for about six months. Renewing at
|
||||
* 30 days leaves room for the job to fail a few times before a token is at risk.
|
||||
*/
|
||||
const RENEWAL_WINDOW_DAYS = 30;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Keeps a bounded batch: the query below holds row locks for the life of the
|
||||
* transaction, which means it holds them across the calls to Mercado Pago.
|
||||
*/
|
||||
const BATCH_LIMIT = 20;
|
||||
const TRANSACTION_TIMEOUT_MS = 120_000;
|
||||
|
||||
export type RefreshExpiringMpTokensResult = {
|
||||
refreshed: number;
|
||||
requiresReauth: number;
|
||||
failed: number;
|
||||
};
|
||||
|
||||
type RefreshExpiringMpTokensDeps = {
|
||||
db?: PrismaClient;
|
||||
/** Swapped in tests; defaults to the real Mercado Pago renewal. */
|
||||
refresh?: typeof refreshMpTokens;
|
||||
};
|
||||
|
||||
type LockedAccountRow = { id: string };
|
||||
|
||||
export class RefreshExpiringMpTokens {
|
||||
constructor(private readonly deps: RefreshExpiringMpTokensDeps = {}) {}
|
||||
|
||||
async execute(): Promise<RefreshExpiringMpTokensResult> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const now = new Date();
|
||||
const totals: RefreshExpiringMpTokensResult = { refreshed: 0, requiresReauth: 0, failed: 0 };
|
||||
|
||||
await db.$transaction(
|
||||
async (tx) => {
|
||||
const horizon = new Date(now.getTime() + RENEWAL_WINDOW_DAYS * DAY_MS);
|
||||
|
||||
// FOR UPDATE SKIP LOCKED: two instances of the API never renew the same
|
||||
// account, and a row already claimed by another instance is skipped
|
||||
// instead of blocking the batch. The trade-off is that the lock stays
|
||||
// held across the HTTP calls below; if MP's latency ever became a
|
||||
// problem, this becomes an atomic `updateMany` claim on a
|
||||
// `refresh_claimed_at` column and the rows are released immediately.
|
||||
const rows = await tx.$queryRaw<LockedAccountRow[]>`
|
||||
SELECT "id"
|
||||
FROM "mp_accounts"
|
||||
WHERE "status" = 'ACTIVE' AND "expires_at" < ${horizon}
|
||||
ORDER BY "expires_at" ASC
|
||||
LIMIT ${BATCH_LIMIT}
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`;
|
||||
|
||||
for (const row of rows) {
|
||||
// Built per row with the transaction client, so the writes join the
|
||||
// transaction holding the lock. With the shared client the lock would
|
||||
// protect nothing.
|
||||
const result = await new RefreshMpAccount({ db: tx, refresh: this.deps.refresh }).execute(
|
||||
row.id,
|
||||
);
|
||||
|
||||
if (result.ok) {
|
||||
totals.refreshed += 1;
|
||||
} else if (result.error.code === 'mp_requires_reauth') {
|
||||
totals.requiresReauth += 1;
|
||||
} else {
|
||||
totals.failed += 1;
|
||||
}
|
||||
}
|
||||
},
|
||||
{ timeout: TRANSACTION_TIMEOUT_MS },
|
||||
);
|
||||
|
||||
return totals;
|
||||
}
|
||||
}
|
||||
|
||||
export { RENEWAL_WINDOW_DAYS };
|
||||
86
apps/backend/src/modules/mp/jobs/refresh-mp-account.ts
Normal file
86
apps/backend/src/modules/mp/jobs/refresh-mp-account.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import { mpProviderErrorProblem, mpRequiresReauthProblem } from '@/http/problem-builders';
|
||||
import prisma from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import type { MpTokenAccount } from '../access-token';
|
||||
import {
|
||||
getMpOAuthConfig,
|
||||
isGrantRejected,
|
||||
type MpTokenResponse,
|
||||
openToken,
|
||||
refreshMpTokens,
|
||||
sealToken,
|
||||
} from '../lib';
|
||||
|
||||
/** Either the client or a transaction client: the job runs this inside a transaction. */
|
||||
export type MpAccountStore = { mpAccount: PrismaClient['mpAccount'] };
|
||||
|
||||
export type RefreshMpAccountDeps = {
|
||||
db?: MpAccountStore;
|
||||
refresh?: typeof refreshMpTokens;
|
||||
};
|
||||
|
||||
/**
|
||||
* Renews one account's access token.
|
||||
*
|
||||
* Shared by the daily job and by the on-demand path in `getMpAccessToken`.
|
||||
*
|
||||
* Mercado Pago rotates the refresh token on every renewal, so the new one is
|
||||
* always stored: keeping the old one would make the next renewal fail.
|
||||
*
|
||||
* Only `invalid_grant` marks the account as `REQUIRES_REAUTH`. A 5xx or a network
|
||||
* failure means no decision was taken about the grant, and locking a teacher out
|
||||
* over a bad afternoon at Mercado Pago would be worse than retrying tomorrow.
|
||||
*/
|
||||
export class RefreshMpAccount {
|
||||
constructor(private readonly deps: RefreshMpAccountDeps = {}) {}
|
||||
|
||||
async execute(accountId: string): Promise<Result<MpTokenAccount, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
const refresh = this.deps.refresh ?? refreshMpTokens;
|
||||
|
||||
const account = await db.mpAccount.findUnique({ where: { id: accountId } });
|
||||
if (!account) {
|
||||
logger.warn({ accountId }, 'Mercado Pago account vanished mid-renewal');
|
||||
return err(mpRequiresReauthProblem());
|
||||
}
|
||||
|
||||
let tokens: MpTokenResponse;
|
||||
try {
|
||||
const config = getMpOAuthConfig();
|
||||
tokens = await refresh({
|
||||
...config,
|
||||
refreshToken: openToken(account.refreshTokenEnc),
|
||||
});
|
||||
} catch (error) {
|
||||
if (isGrantRejected(error)) {
|
||||
logger.warn({ accountId }, 'Mercado Pago refresh token is no longer valid');
|
||||
await db.mpAccount.update({
|
||||
where: { id: accountId },
|
||||
data: { status: 'REQUIRES_REAUTH' },
|
||||
});
|
||||
return err(mpRequiresReauthProblem());
|
||||
}
|
||||
|
||||
logger.error({ accountId, err: error }, 'Mercado Pago token renewal failed');
|
||||
return err(mpProviderErrorProblem());
|
||||
}
|
||||
|
||||
const expiresAt = new Date(Date.now() + tokens.expiresInSeconds * 1000);
|
||||
|
||||
await db.mpAccount.update({
|
||||
where: { id: accountId },
|
||||
data: {
|
||||
accessTokenEnc: sealToken(tokens.accessToken),
|
||||
refreshTokenEnc: sealToken(tokens.refreshToken),
|
||||
expiresAt,
|
||||
scope: tokens.scope ?? account.scope,
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
});
|
||||
|
||||
return ok({ accountId, accessToken: tokens.accessToken, expiresAt });
|
||||
}
|
||||
}
|
||||
33
apps/backend/src/modules/mp/jobs/schedule.ts
Normal file
33
apps/backend/src/modules/mp/jobs/schedule.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { logger } from '@/logger';
|
||||
import { RefreshExpiringMpTokens } from './refresh-expiring-mp-tokens';
|
||||
|
||||
/**
|
||||
* 03:17 UTC. Not on the hour: every instance of the API fires this job at the
|
||||
* same time, and the lock is only there to make the overlap harmless.
|
||||
*/
|
||||
const REFRESH_CRON = '17 3 * * *';
|
||||
|
||||
/**
|
||||
* Registers the background jobs. Called once from `server.ts`.
|
||||
*
|
||||
* Two things are not obvious here:
|
||||
*
|
||||
* - `try/catch` is mandatory. Bun's in-process cron follows `setTimeout` error
|
||||
* semantics: a rejected promise becomes an `unhandledRejection`, and without a
|
||||
* listener the process exits with code 1.
|
||||
* - `unref()` so the job does not keep the process alive on its own.
|
||||
*/
|
||||
export function startMpJobs(): void {
|
||||
Bun.cron(
|
||||
REFRESH_CRON,
|
||||
async () => {
|
||||
try {
|
||||
const totals = await new RefreshExpiringMpTokens().execute();
|
||||
logger.info(totals, 'Mercado Pago token renewal finished');
|
||||
} catch (error) {
|
||||
logger.error({ err: error }, 'Mercado Pago token renewal failed');
|
||||
}
|
||||
},
|
||||
{ tz: 'UTC' },
|
||||
).unref();
|
||||
}
|
||||
51
apps/backend/src/modules/mp/lib/config.ts
Normal file
51
apps/backend/src/modules/mp/lib/config.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
export type MpOAuthConfig = {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
/** Registered as the app's "Redirect URL". Mercado Pago matches it exactly. */
|
||||
redirectUri: string;
|
||||
/** Frontend origin, used to land the teacher back in the app after the callback. */
|
||||
webUrl: string;
|
||||
};
|
||||
|
||||
const DEFAULT_WEB_URL = 'http://localhost:6173';
|
||||
|
||||
export function getWebOrigin(): string {
|
||||
return process.env.WEB_URL?.trim() || DEFAULT_WEB_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the Mercado Pago credentials from the environment.
|
||||
*
|
||||
* Throws instead of returning a `Result`: these are deployment mistakes, not
|
||||
* something the teacher did wrong, so they surface as a 500 with a named
|
||||
* variable in the logs rather than as a problem the UI has to explain. The
|
||||
* names of the missing variables are safe to log; their values never are.
|
||||
*/
|
||||
export function getMpOAuthConfig(): MpOAuthConfig {
|
||||
const missing: string[] = [];
|
||||
const read = (name: string): string => {
|
||||
const value = process.env[name]?.trim();
|
||||
if (!value) {
|
||||
missing.push(name);
|
||||
return '';
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const clientId = read('MP_CLIENT_ID');
|
||||
const clientSecret = read('MP_CLIENT_SECRET');
|
||||
const redirectUri = read('MP_REDIRECT_URI');
|
||||
|
||||
if (missing.length > 0) {
|
||||
throw new Error(
|
||||
`Missing Mercado Pago environment variables: ${missing.join(', ')}. See .env.example.`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri,
|
||||
webUrl: getWebOrigin(),
|
||||
};
|
||||
}
|
||||
79
apps/backend/src/modules/mp/lib/crypto.ts
Normal file
79
apps/backend/src/modules/mp/lib/crypto.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
||||
import { nanoid } from 'nanoid';
|
||||
|
||||
/**
|
||||
* Tokens are encrypted at rest with AES-256-GCM. The payload carries a version
|
||||
* prefix so the scheme can be rotated later without a data migration: an unknown
|
||||
* version fails loudly instead of being decrypted with the wrong assumptions.
|
||||
*
|
||||
* Layout: `v1:<iv>:<tag>:<ciphertext>`, each part base64url. GCM authenticates
|
||||
* the ciphertext, so a tampered payload throws on `openToken` rather than
|
||||
* yielding garbage that would later be sent to Mercado Pago as a token.
|
||||
*/
|
||||
const PAYLOAD_VERSION = 'v1';
|
||||
const KEY_BYTES = 32;
|
||||
const IV_BYTES = 12;
|
||||
|
||||
function getKey(): Buffer {
|
||||
const raw = process.env.TOKEN_ENCRYPTION_KEY;
|
||||
if (!raw) {
|
||||
throw new Error('TOKEN_ENCRYPTION_KEY environment variable is required');
|
||||
}
|
||||
|
||||
const key = Buffer.from(raw, 'base64');
|
||||
if (key.length !== KEY_BYTES) {
|
||||
// Length only, never the value.
|
||||
throw new Error(
|
||||
`TOKEN_ENCRYPTION_KEY must decode to ${KEY_BYTES} bytes in base64, got ${key.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
export function sealToken(plaintext: string): string {
|
||||
const iv = randomBytes(IV_BYTES);
|
||||
const cipher = createCipheriv('aes-256-gcm', getKey(), iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
||||
|
||||
return [
|
||||
PAYLOAD_VERSION,
|
||||
iv.toString('base64url'),
|
||||
cipher.getAuthTag().toString('base64url'),
|
||||
ciphertext.toString('base64url'),
|
||||
].join(':');
|
||||
}
|
||||
|
||||
export function openToken(payload: string): string {
|
||||
const [version, ivPart, tagPart, ciphertextPart] = payload.split(':');
|
||||
|
||||
if (version !== PAYLOAD_VERSION || !ivPart || !tagPart || ciphertextPart === undefined) {
|
||||
throw new Error('Unsupported token payload');
|
||||
}
|
||||
|
||||
const decipher = createDecipheriv('aes-256-gcm', getKey(), Buffer.from(ivPart, 'base64url'));
|
||||
decipher.setAuthTag(Buffer.from(tagPart, 'base64url'));
|
||||
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(ciphertextPart, 'base64url')),
|
||||
decipher.final(),
|
||||
]).toString('utf8');
|
||||
}
|
||||
|
||||
/** CSRF token echoed back by Mercado Pago. 32 chars of entropy. */
|
||||
export function newState(): string {
|
||||
return nanoid(32);
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCE verifier. Mercado Pago requires 43 to 128 characters, so 32 random bytes
|
||||
* in base64url (43 chars) is the smallest value that fits.
|
||||
*/
|
||||
export function newCodeVerifier(): string {
|
||||
return randomBytes(32).toString('base64url');
|
||||
}
|
||||
|
||||
/** PKCE S256 challenge: base64url(SHA256(verifier)) — RFC 7636 section 4.2. */
|
||||
export function codeChallengeFromVerifier(codeVerifier: string): string {
|
||||
return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');
|
||||
}
|
||||
21
apps/backend/src/modules/mp/lib/index.ts
Normal file
21
apps/backend/src/modules/mp/lib/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
export { getMpOAuthConfig, getWebOrigin, type MpOAuthConfig } from './config';
|
||||
export {
|
||||
codeChallengeFromVerifier,
|
||||
newCodeVerifier,
|
||||
newState,
|
||||
openToken,
|
||||
sealToken,
|
||||
} from './crypto';
|
||||
export {
|
||||
buildAuthorizationUrl,
|
||||
exchangeAuthorizationCode,
|
||||
isGrantRejected,
|
||||
MP_AUTHORIZE_URL,
|
||||
MP_SCOPES,
|
||||
MP_TOKEN_URL,
|
||||
MpApiError,
|
||||
type MpAuthorizationUrlInput,
|
||||
type MpTokenResponse,
|
||||
refreshMpTokens,
|
||||
} from './mp-oauth';
|
||||
export { buildMpReturnUrl, type MpCallbackOutcome } from './return-url';
|
||||
170
apps/backend/src/modules/mp/lib/mp-oauth.ts
Normal file
170
apps/backend/src/modules/mp/lib/mp-oauth.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import { logger } from '@/logger';
|
||||
|
||||
export const MP_AUTHORIZE_URL = 'https://auth.mercadopago.com/authorization';
|
||||
export const MP_TOKEN_URL = 'https://api.mercadopago.com/oauth/token';
|
||||
|
||||
/**
|
||||
* `offline_access` is what makes Mercado Pago return a refresh token. Without
|
||||
* it the daily renewal job has nothing to work with.
|
||||
*/
|
||||
export const MP_SCOPES = 'offline_access read write';
|
||||
|
||||
export type MpTokenResponse = {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresInSeconds: number;
|
||||
scope: string | null;
|
||||
mpUserId: string;
|
||||
liveMode: boolean;
|
||||
};
|
||||
|
||||
export type MpAuthorizationUrlInput = {
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
state: string;
|
||||
codeChallenge: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A failure from Mercado Pago's token endpoint.
|
||||
*
|
||||
* `reason` is the safe subset of what MP returned. `error_description` is
|
||||
* deliberately dropped: it echoes back request content, and the request is the
|
||||
* authorization code.
|
||||
*/
|
||||
export class MpApiError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly reason: string | null,
|
||||
) {
|
||||
super(`Mercado Pago token request failed with status ${status}`);
|
||||
this.name = 'MpApiError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Permanent rejection of the grant: the refresh token is dead. */
|
||||
export function isGrantRejected(error: unknown): boolean {
|
||||
return error instanceof MpApiError && error.reason === 'invalid_grant';
|
||||
}
|
||||
|
||||
export function buildAuthorizationUrl({
|
||||
clientId,
|
||||
redirectUri,
|
||||
state,
|
||||
codeChallenge,
|
||||
}: MpAuthorizationUrlInput): string {
|
||||
const url = new URL(MP_AUTHORIZE_URL);
|
||||
url.searchParams.set('client_id', clientId);
|
||||
url.searchParams.set('response_type', 'code');
|
||||
// Declares this as a direct (non-marketplace) integration: the money lands in
|
||||
// the seller's own account, so no platform_id of ours and no fee split.
|
||||
url.searchParams.set('platform_id', 'mp');
|
||||
url.searchParams.set('redirect_uri', redirectUri);
|
||||
url.searchParams.set('state', state);
|
||||
url.searchParams.set('code_challenge', codeChallenge);
|
||||
url.searchParams.set('code_challenge_method', 'S256');
|
||||
url.searchParams.set('scope', MP_SCOPES);
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
type TokenRequestInput = {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirectUri: string;
|
||||
};
|
||||
|
||||
export function exchangeAuthorizationCode(
|
||||
input: TokenRequestInput & { code: string; codeVerifier: string },
|
||||
): Promise<MpTokenResponse> {
|
||||
return requestToken({
|
||||
grant_type: 'authorization_code',
|
||||
client_id: input.clientId,
|
||||
client_secret: input.clientSecret,
|
||||
code: input.code,
|
||||
redirect_uri: input.redirectUri,
|
||||
code_verifier: input.codeVerifier,
|
||||
});
|
||||
}
|
||||
|
||||
export function refreshMpTokens(
|
||||
input: TokenRequestInput & { refreshToken: string },
|
||||
): Promise<MpTokenResponse> {
|
||||
return requestToken({
|
||||
grant_type: 'refresh_token',
|
||||
client_id: input.clientId,
|
||||
client_secret: input.clientSecret,
|
||||
refresh_token: input.refreshToken,
|
||||
});
|
||||
}
|
||||
|
||||
async function requestToken(body: Record<string, string>): Promise<MpTokenResponse> {
|
||||
let response: Response;
|
||||
|
||||
try {
|
||||
response = await fetch(MP_TOKEN_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (error) {
|
||||
// Network level: no grant decision has been made, so callers must treat the
|
||||
// account as still fine.
|
||||
logger.error({ err: error }, 'Mercado Pago token endpoint unreachable');
|
||||
throw new MpApiError(0, null);
|
||||
}
|
||||
|
||||
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
|
||||
if (!response.ok) {
|
||||
const reason = typeof payload?.error === 'string' ? payload.error : null;
|
||||
// Only the status and MP's own error code. The body may echo the `code` or
|
||||
// the `code_verifier` back, and neither may reach the logs.
|
||||
logger.error({ status: response.status, reason }, 'Mercado Pago rejected the token request');
|
||||
throw new MpApiError(response.status, reason);
|
||||
}
|
||||
|
||||
return parseTokenResponse(payload);
|
||||
}
|
||||
|
||||
function parseTokenResponse(payload: Record<string, unknown> | null): MpTokenResponse {
|
||||
const accessToken = pickString(payload, 'access_token');
|
||||
const refreshToken = pickString(payload, 'refresh_token');
|
||||
const mpUserId = pickString(payload, 'user_id');
|
||||
const expiresInSeconds = pickNumber(payload, 'expires_in');
|
||||
|
||||
if (!accessToken || !refreshToken || !mpUserId || expiresInSeconds === null) {
|
||||
logger.error(
|
||||
{ received: payload ? Object.keys(payload) : null },
|
||||
'Mercado Pago token response is missing required fields',
|
||||
);
|
||||
throw new MpApiError(200, 'malformed_token_response');
|
||||
}
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresInSeconds,
|
||||
// The response omits `scope` when it matches what was requested.
|
||||
scope: pickString(payload, 'scope') ?? null,
|
||||
mpUserId,
|
||||
liveMode: payload?.live_mode === true,
|
||||
};
|
||||
}
|
||||
|
||||
function pickString(payload: Record<string, unknown> | null, key: string): string | null {
|
||||
const value = payload?.[key];
|
||||
if (typeof value === 'string' && value.length > 0) return value;
|
||||
// Mercado Pago sends `user_id` as a number.
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickNumber(payload: Record<string, unknown> | null, key: string): number | null {
|
||||
const value = payload?.[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||
if (typeof value === 'string') {
|
||||
const parsed = Number(value);
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
25
apps/backend/src/modules/mp/lib/return-url.ts
Normal file
25
apps/backend/src/modules/mp/lib/return-url.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import type { MpCallbackReason, MpReturnTo } from '@gruperly/shared';
|
||||
|
||||
export type MpCallbackOutcome =
|
||||
| { kind: 'success' }
|
||||
| { kind: 'error'; reason: MpCallbackReason };
|
||||
|
||||
/**
|
||||
* Where the OAuth callback sends the teacher back to.
|
||||
*
|
||||
* Only `mp` and a reason code ever go in the URL: the authorization code and the
|
||||
* PKCE verifier stay on the server. `returnTo` comes from a stored enum, never
|
||||
* from the request, so this cannot be turned into an open redirect.
|
||||
*/
|
||||
export function buildMpReturnUrl(
|
||||
webUrl: string,
|
||||
returnTo: MpReturnTo,
|
||||
outcome: MpCallbackOutcome,
|
||||
): string {
|
||||
const url = new URL(`/${returnTo}`, webUrl);
|
||||
url.searchParams.set('mp', outcome.kind);
|
||||
if (outcome.kind === 'error') {
|
||||
url.searchParams.set('reason', outcome.reason);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
16
apps/backend/src/modules/mp/routes.ts
Normal file
16
apps/backend/src/modules/mp/routes.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Hono } from 'hono';
|
||||
import callbackRoute from './features/callback/route';
|
||||
import connectRoute from './features/connect/route';
|
||||
import disconnectRoute from './features/disconnect/route';
|
||||
import statusRoute from './features/status/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
// `disconnectRoute` only declares `DELETE /`, so mounting it at the same path as
|
||||
// `connectRoute` gives the unlink endpoint its RESTful `DELETE /mp/connect`.
|
||||
routes.route('/connect', connectRoute);
|
||||
routes.route('/connect', disconnectRoute);
|
||||
routes.route('/callback', callbackRoute);
|
||||
routes.route('/status', statusRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -7,16 +7,13 @@ import type {
|
||||
Result,
|
||||
} from '@gruperly/shared';
|
||||
import { err, ok } from '@gruperly/shared';
|
||||
import {
|
||||
onboardingAlreadyCompletedProblem,
|
||||
paymentNotSetupProblem,
|
||||
} from '@/http/problem-builders';
|
||||
import { onboardingAlreadyCompletedProblem } from '@/http/problem-builders';
|
||||
import { problemDetails } from '@/http/problem-details';
|
||||
import { default as prisma, UnitOfWork } from '@/lib/prisma';
|
||||
import { toOnboardingGroupDto } from '../../lib';
|
||||
|
||||
type CreateFirstGroupDeps = {
|
||||
db?: Pick<PrismaClient, 'user' | 'merchantAccount'>;
|
||||
db?: Pick<PrismaClient, 'user'>;
|
||||
unitOfWork?: UnitOfWork;
|
||||
};
|
||||
|
||||
@@ -38,11 +35,6 @@ export class CreateFirstGroup {
|
||||
return err(onboardingAlreadyCompletedProblem());
|
||||
}
|
||||
|
||||
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } });
|
||||
if (!merchantAccount) {
|
||||
return err(paymentNotSetupProblem());
|
||||
}
|
||||
|
||||
const transaction = unitOfWork.executeResult(
|
||||
async (tx: Prisma.TransactionClient) => {
|
||||
const created = await tx.group.create({
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { ConnectPayment } from '@gruperly/shared';
|
||||
import { ConnectPaymentSchema } from '@gruperly/shared';
|
||||
import { Hono } from 'hono';
|
||||
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
|
||||
import { validate } from '@/http/validate';
|
||||
import { PaymentSetup } from './use-case';
|
||||
|
||||
const route = new Hono();
|
||||
|
||||
route.post('/', validate.json(ConnectPaymentSchema), async (c) => {
|
||||
const user = c.get('user');
|
||||
if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
|
||||
|
||||
const data = c.req.valid('json') as ConnectPayment;
|
||||
const useCase = new PaymentSetup();
|
||||
const result = await useCase.execute(data, user.id);
|
||||
return resultJson(c, result);
|
||||
});
|
||||
|
||||
export default route;
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { PrismaClient } from '@generated/prisma/client';
|
||||
import type { ConnectPayment, ConnectPaymentResult, ProblemDetails, Result } from '@gruperly/shared';
|
||||
import { ok } from '@gruperly/shared';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type PaymentSetupDeps = { db?: PrismaClient };
|
||||
|
||||
export class PaymentSetup {
|
||||
constructor(private readonly deps: PaymentSetupDeps = {}) {}
|
||||
|
||||
async execute(
|
||||
data: ConnectPayment,
|
||||
userId: string,
|
||||
): Promise<Result<ConnectPaymentResult, ProblemDetails>> {
|
||||
const db = this.deps.db ?? prisma;
|
||||
|
||||
await db.merchantAccount.upsert({
|
||||
where: { userId },
|
||||
create: {
|
||||
userId,
|
||||
provider: data.provider,
|
||||
accessToken: data.accessToken,
|
||||
sandbox: data.sandbox,
|
||||
},
|
||||
update: {
|
||||
provider: data.provider,
|
||||
accessToken: data.accessToken,
|
||||
sandbox: data.sandbox,
|
||||
},
|
||||
});
|
||||
|
||||
return ok({
|
||||
provider: data.provider,
|
||||
sandbox: data.sandbox,
|
||||
connected: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { err, ok } from '@gruperly/shared';
|
||||
import { problemDetails } from '@/http/problem-details';
|
||||
import prisma from '@/lib/prisma';
|
||||
|
||||
type GetOnboardingStatusDeps = { db?: PrismaClient };
|
||||
type GetOnboardingStatusDeps = { db?: Pick<PrismaClient, 'user' | 'mpAccount'> };
|
||||
|
||||
export class GetOnboardingStatus {
|
||||
constructor(private readonly deps: GetOnboardingStatusDeps = {}) {}
|
||||
@@ -28,8 +28,11 @@ export class GetOnboardingStatus {
|
||||
return ok({ step: 'COMPLETED', paymentConnected: true, completed: true });
|
||||
}
|
||||
|
||||
const merchantAccount = await db.merchantAccount.findUnique({ where: { userId } });
|
||||
if (merchantAccount) {
|
||||
// Linking Mercado Pago is optional, so `paymentConnected` here only resumes
|
||||
// the flow where the teacher left off: with a usable account, they do not
|
||||
// need to see the "Cobros" step again. A `revoked` row is not usable.
|
||||
const mpAccount = await db.mpAccount.findUnique({ where: { ownerId: userId } });
|
||||
if (mpAccount && mpAccount.status === 'ACTIVE') {
|
||||
return ok({ step: 'PAYMENT_CONNECTED', paymentConnected: true, completed: false });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { Hono } from 'hono';
|
||||
import firstGroupRoute from './features/first-group/route';
|
||||
import paymentSetupRoute from './features/payment-setup/route';
|
||||
import statusRoute from './features/status/route';
|
||||
|
||||
const routes = new Hono();
|
||||
|
||||
routes.route('/status', statusRoute);
|
||||
routes.route('/payment-setup', paymentSetupRoute);
|
||||
routes.route('/first-group', firstGroupRoute);
|
||||
|
||||
export default routes;
|
||||
@@ -1,6 +1,7 @@
|
||||
import app from '@/app';
|
||||
import { getPrismaClient } from '@/lib/prisma';
|
||||
import { logger } from '@/logger';
|
||||
import { startMpJobs } from '@/modules/mp';
|
||||
|
||||
const port = Number(process.env.PORT ?? 4000);
|
||||
|
||||
@@ -11,6 +12,8 @@ const server = Bun.serve({
|
||||
fetch: app.fetch,
|
||||
});
|
||||
|
||||
startMpJobs();
|
||||
|
||||
async function shutdown(): Promise<void> {
|
||||
server.stop(true);
|
||||
await getPrismaClient().$disconnect();
|
||||
|
||||
@@ -10,9 +10,6 @@ const db = {
|
||||
groupMember: {
|
||||
create: mock(),
|
||||
},
|
||||
merchantAccount: {
|
||||
findUnique: mock(),
|
||||
},
|
||||
};
|
||||
|
||||
mock.module('@/lib/prisma', () => ({
|
||||
@@ -171,7 +168,6 @@ describe('groups routes', () => {
|
||||
});
|
||||
|
||||
it('creates a group with billing configuration', async () => {
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'merchant-1', userId });
|
||||
prisma.group.create.mockResolvedValue({
|
||||
...group,
|
||||
days: ['MONDAY'],
|
||||
@@ -227,8 +223,16 @@ describe('groups routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects creating a group without a linked merchant account', async () => {
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue(null);
|
||||
it('creates a group without Mercado Pago linked, since linking is optional', async () => {
|
||||
prisma.group.create.mockResolvedValue({
|
||||
...group,
|
||||
days: ['MONDAY'],
|
||||
time: '09:00',
|
||||
capacity: 20,
|
||||
price: 500,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 5,
|
||||
});
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/groups', {
|
||||
method: 'POST',
|
||||
@@ -244,9 +248,8 @@ describe('groups routes', () => {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: 'payment_not_setup' });
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
expect(res.status).toBe(201);
|
||||
expect(prisma.group.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects creating a group with an invalid payload', async () => {
|
||||
|
||||
1042
apps/backend/test/mp.test.ts
Normal file
1042
apps/backend/test/mp.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -6,9 +6,8 @@ const db = {
|
||||
findUnique: mock(),
|
||||
update: mock(),
|
||||
},
|
||||
merchantAccount: {
|
||||
mpAccount: {
|
||||
findUnique: mock(),
|
||||
upsert: mock(),
|
||||
},
|
||||
group: {
|
||||
create: mock(),
|
||||
@@ -75,7 +74,7 @@ describe('onboarding routes', () => {
|
||||
describe('GET /onboarding/status', () => {
|
||||
it('returns NOT_STARTED for a user that has not started', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/status');
|
||||
|
||||
@@ -87,9 +86,9 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns PAYMENT_CONNECTED when the merchant account exists', async () => {
|
||||
it('returns PAYMENT_CONNECTED when Mercado Pago is linked and active', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId });
|
||||
prisma.mpAccount.findUnique.mockResolvedValue({ id: 'mp-1', ownerId: userId, status: 'ACTIVE' });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/status');
|
||||
|
||||
@@ -101,6 +100,24 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns NOT_STARTED when the account needs to be linked again', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.mpAccount.findUnique.mockResolvedValue({
|
||||
id: 'mp-1',
|
||||
ownerId: userId,
|
||||
status: 'REQUIRES_REAUTH',
|
||||
});
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/status');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
step: 'NOT_STARTED',
|
||||
paymentConnected: false,
|
||||
completed: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns COMPLETED when onboarding is already done', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: true });
|
||||
|
||||
@@ -122,54 +139,9 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /onboarding/payment-setup', () => {
|
||||
it('connects a merchant account in sandbox mode', async () => {
|
||||
prisma.merchantAccount.upsert.mockResolvedValue({ id: 'ma-1', userId });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/payment-setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ provider: 'MERCADO_PAGO', sandbox: true }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({
|
||||
provider: 'MERCADO_PAGO',
|
||||
sandbox: true,
|
||||
connected: true,
|
||||
});
|
||||
expect(prisma.merchantAccount.upsert).toHaveBeenCalledWith({
|
||||
where: { userId },
|
||||
create: { userId, provider: 'MERCADO_PAGO', accessToken: undefined, sandbox: true },
|
||||
update: { provider: 'MERCADO_PAGO', accessToken: undefined, sandbox: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an unknown provider', async () => {
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/payment-setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ provider: 'PAYPAL' }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects without a session', async () => {
|
||||
const res = await makeApp(null).request('/onboarding/payment-setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ provider: 'STRIPE', sandbox: true }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /onboarding/first-group', () => {
|
||||
it('creates the first group and completes onboarding', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId });
|
||||
prisma.group.create.mockResolvedValue(group);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
@@ -217,9 +189,10 @@ describe('onboarding routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects when the payment has not been set up', async () => {
|
||||
it('creates the group without Mercado Pago linked, since that step is skippable', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.mpAccount.findUnique.mockResolvedValue(null);
|
||||
prisma.group.create.mockResolvedValue(group);
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
method: 'POST',
|
||||
@@ -227,9 +200,8 @@ describe('onboarding routes', () => {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: 'payment_not_setup' });
|
||||
expect(prisma.group.create).not.toHaveBeenCalled();
|
||||
expect(res.status).toBe(201);
|
||||
expect(prisma.group.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects when onboarding is already completed', async () => {
|
||||
@@ -248,7 +220,6 @@ describe('onboarding routes', () => {
|
||||
|
||||
it('rejects invalid payloads', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue({ id: userId, onboardingCompleted: false });
|
||||
prisma.merchantAccount.findUnique.mockResolvedValue({ id: 'ma-1', userId });
|
||||
|
||||
const res = await makeApp({ id: userId }).request('/onboarding/first-group', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useLocation } from '@tanstack/react-router'
|
||||
import type { ReactNode } from 'react'
|
||||
import { ImmersiveBarHost, ImmersiveBarProvider } from '../../context/ImmersiveBarProvider'
|
||||
import { MpReauthNotice } from '../../features/mp'
|
||||
import { isImmersiveRoute } from '../../lib/immersive-routes'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { BottomNav } from './BottomNav'
|
||||
import { Header } from './Header'
|
||||
import { Sidebar } from './Sidebar'
|
||||
import { BottomNav } from './BottomNav'
|
||||
|
||||
export function RootLayout({ children }: { children: ReactNode }) {
|
||||
const immersive = useLocation({ select: (location) => isImmersiveRoute(location.pathname) })
|
||||
@@ -31,6 +32,10 @@ export function RootLayout({ children }: { children: ReactNode }) {
|
||||
)}
|
||||
>
|
||||
{immersive ? <ImmersiveBarHost /> : null}
|
||||
{/* Aviso de que Mercado Pago necesita volver a autorizarse. Va dentro
|
||||
de <main> para que fluya con el contenido y no tape la barra
|
||||
immersive ni el bottom nav; se oculta solo en Ajustes. */}
|
||||
<MpReauthNotice />
|
||||
{children}
|
||||
</main>
|
||||
</ImmersiveBarProvider>
|
||||
|
||||
51
apps/web/src/features/mp/MpReauthNotice.tsx
Normal file
51
apps/web/src/features/mp/MpReauthNotice.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { useLocation } from '@tanstack/react-router'
|
||||
import { Loader2, TriangleAlert } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { shouldShowMpReauthNotice } from './copy'
|
||||
import { useMpStatus } from './useMpStatus'
|
||||
import { useStartMpAuthorization } from './useStartMpAuthorization'
|
||||
|
||||
/**
|
||||
* Aviso global de que la cuenta de Mercado Pago necesita volver a autorizarse.
|
||||
*
|
||||
* Solo aparece con sesión iniciada y cuando el estado es `requires_reauth`: que
|
||||
* la cuenta esté sin vincular es legítimo (el paso del onboarding es
|
||||
* salteable), pero un cobro que no va a entrar hay que decirlo aunque el
|
||||
* profesor esté en cualquier pantalla. En Ajustes no se muestra porque ahí la
|
||||
* tarjeta de Cobros ya ofrece la acción, con más contexto.
|
||||
*/
|
||||
export function MpReauthNotice() {
|
||||
const { user } = useAuth()
|
||||
const statusQuery = useMpStatus({ enabled: !!user })
|
||||
const startAuthorization = useStartMpAuthorization()
|
||||
const pathname = useLocation({ select: (location) => location.pathname })
|
||||
|
||||
const status = statusQuery.data?.status
|
||||
if (!user || pathname === '/settings') return null
|
||||
if (!status || !shouldShowMpReauthNotice(status)) return null
|
||||
|
||||
return (
|
||||
<div className="mb-4 flex items-start gap-3 rounded-xl border border-warning/30 bg-warning-soft px-4 py-3">
|
||||
<TriangleAlert className="mt-0.5 size-4 shrink-0 text-warning" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium text-warning">Volvé a vincular Mercado Pago</p>
|
||||
<p className="text-xs text-warning/90">
|
||||
Tu autorización venció, así que los cobros de tus grupos no se están procesando.
|
||||
</p>
|
||||
</div>
|
||||
{startAuthorization.isStarting ? (
|
||||
<Loader2 className="size-4 shrink-0 animate-spin self-center text-warning" />
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
className="self-center"
|
||||
onClick={() => void startAuthorization.start('settings')}
|
||||
>
|
||||
Volver a vincular
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
188
apps/web/src/features/mp/MpStatusCard.tsx
Normal file
188
apps/web/src/features/mp/MpStatusCard.tsx
Normal file
@@ -0,0 +1,188 @@
|
||||
import { BadgeCheck, CreditCard, Loader2, Unlink } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Badge, Button, Modal } from '../../components/ui'
|
||||
import {
|
||||
formatMpConnectionDate,
|
||||
MP_PROVIDER_NAME,
|
||||
mpStatusBadgeVariant,
|
||||
mpStatusLabel,
|
||||
} from './copy'
|
||||
import { useDisconnectMp } from './useDisconnectMp'
|
||||
import { useMpStatus } from './useMpStatus'
|
||||
import { useStartMpAuthorization } from './useStartMpAuthorization'
|
||||
|
||||
/**
|
||||
* Estado de la cuenta de Mercado Pago en Ajustes: vincular, ver que está
|
||||
* vinculada o volver a vincularla. El mismo control vive en el paso del
|
||||
* onboarding; acá es el lugar al que se llega cuando ese paso ya pasó.
|
||||
*/
|
||||
export function MpStatusCard() {
|
||||
const statusQuery = useMpStatus()
|
||||
const startAuthorization = useStartMpAuthorization()
|
||||
const { disconnectMp: disconnect, isDisconnecting } = useDisconnectMp()
|
||||
const [isConfirmingDisconnect, setIsConfirmingDisconnect] = useState(false)
|
||||
|
||||
const status = statusQuery.data?.status ?? 'none'
|
||||
const accountIdSuffix = statusQuery.data?.mpUserIdSuffix
|
||||
const connectedAt = formatMpConnectionDate(statusQuery.data?.connectedAt ?? null)
|
||||
|
||||
if (statusQuery.isPending) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
|
||||
<Loader2 className="size-4 animate-spin text-foreground/40" />
|
||||
<p className="text-sm text-foreground/50">Consultando tu cuenta de {MP_PROVIDER_NAME}…</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||
<div className="px-4 py-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="text-sm font-medium text-primary">Cobros</p>
|
||||
<Badge variant={mpStatusBadgeVariant(status)}>{mpStatusLabel(status)}</Badge>
|
||||
</div>
|
||||
<p className="mt-0.5 text-xs text-foreground/50">
|
||||
Tu cuenta de {MP_PROVIDER_NAME} para recibir los pagos de tus grupos.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{status === 'active' && accountIdSuffix ? (
|
||||
<div className="flex items-center gap-3 px-4 py-3">
|
||||
<span className="rounded-lg bg-accent-soft p-2">
|
||||
<CreditCard className="size-4 text-accent-fg" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm text-primary">
|
||||
Cuenta terminada en <span className="font-semibold">••{accountIdSuffix}</span>
|
||||
</p>
|
||||
{connectedAt ? (
|
||||
<p className="text-xs text-foreground/50">Vinculada el {connectedAt}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsConfirmingDisconnect(true)}
|
||||
disabled={isDisconnecting}
|
||||
>
|
||||
{isDisconnecting ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Unlink className="size-4" />
|
||||
)}
|
||||
Desvincular
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{status === 'requires_reauth' ? (
|
||||
<div className="flex items-start gap-3 px-4 py-3">
|
||||
<span className="rounded-lg bg-warning-soft p-2">
|
||||
<CreditCard className="size-4 text-warning" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm text-primary">Hay que volver a vincular la cuenta</p>
|
||||
<p className="text-xs text-foreground/50">
|
||||
Mercado Pago ya no acepta la autorización anterior. Volvé a autorizar para poder
|
||||
seguir cobrando.
|
||||
</p>
|
||||
</div>
|
||||
<ConnectButton
|
||||
isStarting={startAuthorization.isStarting}
|
||||
onClick={() => void startAuthorization.start('settings')}
|
||||
>
|
||||
Volver a vincular
|
||||
</ConnectButton>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{status === 'none' ? (
|
||||
<div className="flex items-start gap-3 px-4 py-3">
|
||||
<span className="rounded-lg bg-primary-soft p-2">
|
||||
<CreditCard className="size-4 text-foreground/70" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm text-primary">Vinculá tu cuenta</p>
|
||||
<p className="text-xs text-foreground/50">
|
||||
Te llevamos a {MP_PROVIDER_NAME} para autorizar los cobros. Es gratis y lo podés
|
||||
hacer más adelante.
|
||||
</p>
|
||||
</div>
|
||||
<ConnectButton
|
||||
isStarting={startAuthorization.isStarting}
|
||||
onClick={() => void startAuthorization.start('settings')}
|
||||
>
|
||||
Vincular
|
||||
</ConnectButton>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{startAuthorization.error ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||
{startAuthorization.error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<DisconnectModal
|
||||
isOpen={isConfirmingDisconnect}
|
||||
isPending={isDisconnecting}
|
||||
onClose={() => setIsConfirmingDisconnect(false)}
|
||||
onConfirm={() => {
|
||||
setIsConfirmingDisconnect(false)
|
||||
disconnect()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type ConnectButtonProps = {
|
||||
isStarting: boolean
|
||||
onClick: () => void
|
||||
children: string
|
||||
}
|
||||
|
||||
function ConnectButton({ isStarting, onClick, children }: ConnectButtonProps) {
|
||||
return (
|
||||
<Button variant="primary" size="sm" disabled={isStarting} onClick={onClick}>
|
||||
{isStarting ? <Loader2 className="size-4 animate-spin" /> : <BadgeCheck className="size-4" />}
|
||||
{isStarting ? 'Abriendo…' : children}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
type DisconnectModalProps = {
|
||||
isOpen: boolean
|
||||
isPending: boolean
|
||||
onClose: () => void
|
||||
onConfirm: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Desvincular se puede revertir volviendo a autorizar, pero los cobros quedan
|
||||
* suspendidos mientras tanto, así que se pregunta antes.
|
||||
*/
|
||||
function DisconnectModal({ isOpen, isPending, onClose, onConfirm }: DisconnectModalProps) {
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Desvincular Mercado Pago"
|
||||
description="Tu cuenta deja de estar conectada y los cobros quedan suspendidos hasta que la vuelvas a vincular."
|
||||
maxWidth="sm"
|
||||
>
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="primary" disabled={isPending} onClick={onConfirm}>
|
||||
{isPending ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
Desvincular
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
87
apps/web/src/features/mp/copy.ts
Normal file
87
apps/web/src/features/mp/copy.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import type { MpAccountStatus, MpCallbackReason } from '@gruperly/shared'
|
||||
|
||||
/* Copy de Mercado Pago en un solo lugar: el paso del onboarding, la tarjeta de
|
||||
Ajustes y el aviso global tienen que decir exactamente lo mismo. Las funciones
|
||||
son puras para poder cubrirlas con tests sin renderizar nada. */
|
||||
|
||||
export const MP_PROVIDER_NAME = 'Mercado Pago'
|
||||
|
||||
export const MP_CONNECT_ERROR_MESSAGE =
|
||||
'No pudimos abrir Mercado Pago. Revisá tu conexión e intentá de nuevo.'
|
||||
|
||||
/** El resultado de la vinculación, tal como vuelve en `?mp=` de la URL. */
|
||||
export type MpCallbackFeedback =
|
||||
| { kind: 'success' }
|
||||
| { kind: 'error'; reason: MpCallbackReason }
|
||||
|
||||
/** Traduce `?mp=` de la URL a la retroalimentación que se muestra en pantalla. */
|
||||
export function readMpCallbackFeedback(
|
||||
mp: string | undefined,
|
||||
reason: string | undefined,
|
||||
): MpCallbackFeedback | null {
|
||||
if (mp === 'success') return { kind: 'success' }
|
||||
if (mp !== 'error') return null
|
||||
|
||||
// Un `reason` desconocido o ausente se trata como un fallo genérico: el
|
||||
// backend manda el código, nunca el mensaje.
|
||||
const known: readonly MpCallbackReason[] = [
|
||||
'invalid_state',
|
||||
'mp_denied',
|
||||
'mp_error',
|
||||
'mp_account_in_use',
|
||||
]
|
||||
return {
|
||||
kind: 'error',
|
||||
reason: known.includes(reason as MpCallbackReason) ? (reason as MpCallbackReason) : 'mp_error',
|
||||
}
|
||||
}
|
||||
|
||||
const REASON_MESSAGES: Record<MpCallbackReason, string> = {
|
||||
invalid_state: 'La vinculación venció o ya se había usado. Volvé a intentarlo.',
|
||||
mp_denied: 'No autorizaste la conexión en Mercado Pago.',
|
||||
mp_error: 'Mercado Pago no pudo completar la vinculación.',
|
||||
mp_account_in_use: 'Esa cuenta de Mercado Pago ya está vinculada a otro profesor.',
|
||||
}
|
||||
|
||||
export function mpCallbackErrorMessage(reason: MpCallbackReason): string {
|
||||
return REASON_MESSAGES[reason]
|
||||
}
|
||||
|
||||
export function mpStatusLabel(status: MpAccountStatus): string {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return 'Vinculada'
|
||||
case 'requires_reauth':
|
||||
return 'Necesita vincularse de nuevo'
|
||||
case 'none':
|
||||
return 'Sin vincular'
|
||||
}
|
||||
}
|
||||
|
||||
export function mpStatusBadgeVariant(
|
||||
status: MpAccountStatus,
|
||||
): 'success' | 'warning' | 'neutral' {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return 'success'
|
||||
case 'requires_reauth':
|
||||
return 'warning'
|
||||
case 'none':
|
||||
return 'neutral'
|
||||
}
|
||||
}
|
||||
|
||||
/** `2026-10-05T12:00:00.000Z` → `5 oct 2026`. */
|
||||
export function formatMpConnectionDate(iso: string | null): string | null {
|
||||
if (!iso) return null
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return null
|
||||
return new Intl.DateTimeFormat('es', { day: 'numeric', month: 'short', year: 'numeric' }).format(
|
||||
date,
|
||||
)
|
||||
}
|
||||
|
||||
/** Cuándo conviene avisarle al profesor que vuelva a vincular. */
|
||||
export function shouldShowMpReauthNotice(status: MpAccountStatus): boolean {
|
||||
return status === 'requires_reauth'
|
||||
}
|
||||
16
apps/web/src/features/mp/index.ts
Normal file
16
apps/web/src/features/mp/index.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
export {
|
||||
formatMpConnectionDate,
|
||||
MP_CONNECT_ERROR_MESSAGE,
|
||||
MP_PROVIDER_NAME,
|
||||
type MpCallbackFeedback,
|
||||
mpCallbackErrorMessage,
|
||||
mpStatusBadgeVariant,
|
||||
mpStatusLabel,
|
||||
readMpCallbackFeedback,
|
||||
shouldShowMpReauthNotice,
|
||||
} from './copy'
|
||||
export { MpReauthNotice } from './MpReauthNotice'
|
||||
export { MpStatusCard } from './MpStatusCard'
|
||||
export { useDisconnectMp } from './useDisconnectMp'
|
||||
export { mpStatusQueryKey, useMpStatus } from './useMpStatus'
|
||||
export { useStartMpAuthorization } from './useStartMpAuthorization'
|
||||
30
apps/web/src/features/mp/useDisconnectMp.ts
Normal file
30
apps/web/src/features/mp/useDisconnectMp.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useToast } from '../../components/ui'
|
||||
import { disconnectMp } from '../../lib/api'
|
||||
import { mpStatusQueryKey } from './useMpStatus'
|
||||
|
||||
export function useDisconnectMp() {
|
||||
const queryClient = useQueryClient()
|
||||
const toast = useToast()
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: disconnectMp,
|
||||
onSuccess: (result) => {
|
||||
if (result.disconnected) {
|
||||
toast.success('Desvinculamos tu cuenta de Mercado Pago.')
|
||||
}
|
||||
// `invalidateQueries` y no `setQueryData`: el estado real (si la fila quedó
|
||||
// reservada o no) lo responde el backend.
|
||||
void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey })
|
||||
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message || 'No pudimos desvincular la cuenta de Mercado Pago.')
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
disconnectMp: () => mutation.mutate(),
|
||||
isDisconnecting: mutation.isPending,
|
||||
}
|
||||
}
|
||||
19
apps/web/src/features/mp/useMpStatus.ts
Normal file
19
apps/web/src/features/mp/useMpStatus.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { MpStatusDto } from '@gruperly/shared'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getMpStatus } from '../../lib/api'
|
||||
|
||||
/** La misma clave en toda la app: el onboarding, Ajustes y el aviso global. */
|
||||
export const mpStatusQueryKey = ['mp', 'status'] as const
|
||||
|
||||
type UseMpStatusOptions = {
|
||||
/** `RootLayout` se renderiza sin sesión, así que la consulta se puede apagar. */
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export function useMpStatus({ enabled = true }: UseMpStatusOptions = {}) {
|
||||
return useQuery({
|
||||
queryKey: mpStatusQueryKey,
|
||||
queryFn: getMpStatus,
|
||||
enabled,
|
||||
})
|
||||
}
|
||||
33
apps/web/src/features/mp/useStartMpAuthorization.ts
Normal file
33
apps/web/src/features/mp/useStartMpAuthorization.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { MpReturnTo } from '@gruperly/shared'
|
||||
import { useState } from 'react'
|
||||
import { startMpAuthorization } from '../../lib/api'
|
||||
import { MP_CONNECT_ERROR_MESSAGE } from './copy'
|
||||
|
||||
/**
|
||||
* Empieza la vinculación de Mercado Pago.
|
||||
*
|
||||
* OAuth no se puede hacer con `fetch`: el navegador tiene que navegar a la
|
||||
* pantalla de consentimiento de Mercado Pago, y el backend devuelve el control al
|
||||
* frontend con `?mp=success` o `?mp=error&reason=…`. Por eso el botón no navega
|
||||
* con el router sino con `location.assign`.
|
||||
*/
|
||||
export function useStartMpAuthorization() {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isStarting, setIsStarting] = useState(false)
|
||||
|
||||
const start = async (returnTo: MpReturnTo) => {
|
||||
setError(null)
|
||||
setIsStarting(true)
|
||||
try {
|
||||
const { authorizationUrl } = await startMpAuthorization(returnTo)
|
||||
window.location.assign(authorizationUrl)
|
||||
} catch {
|
||||
// Perder la red contra nuestra propia API no es un error de Mercado Pago,
|
||||
// pero para el profesor el botón falló y tiene que poder reintentarlo.
|
||||
setError(MP_CONNECT_ERROR_MESSAGE)
|
||||
setIsStarting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return { start, isStarting, error }
|
||||
}
|
||||
@@ -1,20 +1,22 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import type { OnboardingGroupDto } from '@gruperly/shared'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowRight, CheckCircle2, CreditCard } from 'lucide-react'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { MP_PROVIDER_NAME, useMpStatus } from '../mp'
|
||||
import { BILLING_LABELS, formatPrice, formatSchedule } from './constants'
|
||||
|
||||
type ConfirmationStepProps = {
|
||||
group: OnboardingGroupDto
|
||||
providerName?: string
|
||||
}
|
||||
|
||||
export function ConfirmationStep({ group, providerName }: ConfirmationStepProps) {
|
||||
export function ConfirmationStep({ group }: ConfirmationStepProps) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { refresh } = useAuth()
|
||||
const statusQuery = useMpStatus()
|
||||
const isMpConnected = statusQuery.data?.status === 'active'
|
||||
|
||||
const goToDashboard = () => {
|
||||
// Revalidates the cache (onboarding state, session, groups) before redirecting.
|
||||
@@ -31,7 +33,7 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps)
|
||||
</span>
|
||||
<h2 className="text-2xl font-bold text-primary">¡Todo listo!</h2>
|
||||
<p className="text-sm text-foreground/60">
|
||||
Tu grupo se creó y ya podés empezar a cobrar a tus miembros.
|
||||
Tu grupo se creó. Ya podés invitar miembros y pasar lista.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
@@ -65,15 +67,24 @@ export function ConfirmationStep({ group, providerName }: ConfirmationStepProps)
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
{providerName ? (
|
||||
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
|
||||
<CreditCard className="size-4 shrink-0 text-accent" />
|
||||
<p className="text-xs text-primary">
|
||||
Vas a cobrar con <span className="font-semibold">{providerName}</span> en modo
|
||||
prueba.
|
||||
{isMpConnected ? (
|
||||
<>
|
||||
Vas a cobrar con <span className="font-semibold">{MP_PROVIDER_NAME}</span>. Los
|
||||
pagos entran directo en tu cuenta.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Cuando quieras cobrar, vinculá <span className="font-semibold">
|
||||
{MP_PROVIDER_NAME}
|
||||
</span>{' '}
|
||||
desde Ajustes. Tu grupo ya quedó creado.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Button variant="primary" className="w-full" onClick={goToDashboard}>
|
||||
Ir a mi Panel
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { createFirstGroup } from '../../lib/api'
|
||||
import { GroupForm } from '../groups/GroupForm'
|
||||
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
import { createContext, useContext, useEffect, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { ConnectPaymentResult, OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared'
|
||||
import type { OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared'
|
||||
import type { UseQueryResult } from '@tanstack/react-query'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate, useSearch } from '@tanstack/react-router'
|
||||
import type { ReactNode } from 'react'
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { getOnboardingStatus } from '../../lib/api'
|
||||
import { PAYMENT_PROVIDERS } from './constants'
|
||||
import type { MpCallbackFeedback } from '../mp'
|
||||
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
||||
|
||||
const WELCOME_STEP = 0
|
||||
const PAYMENT_STEP = 1
|
||||
const FIRST_GROUP_STEP = 2
|
||||
|
||||
type OnboardingContextValue = {
|
||||
step: number
|
||||
setStep: (step: number) => void
|
||||
paymentResult: ConnectPaymentResult | null
|
||||
setPaymentResult: (result: ConnectPaymentResult) => void
|
||||
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
|
||||
mpFeedback: MpCallbackFeedback | null
|
||||
createdGroup: OnboardingGroupDto | null
|
||||
setCreatedGroup: (group: OnboardingGroupDto) => void
|
||||
providerName: string | undefined
|
||||
statusQuery: UseQueryResult<OnboardingStatusDto>
|
||||
}
|
||||
|
||||
@@ -22,8 +27,11 @@ const OnboardingContext = createContext<OnboardingContextValue | null>(null)
|
||||
|
||||
export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||
const { user } = useAuth()
|
||||
const [step, setStep] = useState(0)
|
||||
const [paymentResult, setPaymentResult] = useState<ConnectPaymentResult | null>(null)
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const search = useSearch({ from: '/onboarding' })
|
||||
const [step, setStep] = useState(WELCOME_STEP)
|
||||
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
|
||||
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
|
||||
|
||||
const statusQuery = useQuery({
|
||||
@@ -32,29 +40,48 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||
enabled: !!user,
|
||||
})
|
||||
|
||||
const callbackFeedback = useMemo(
|
||||
() => readMpCallbackFeedback(search.mp, search.reason),
|
||||
[search.mp, search.reason],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!callbackFeedback) return
|
||||
|
||||
setMpFeedback(callbackFeedback)
|
||||
// La vinculación cambió el estado del servidor: el paso muestra el botón de
|
||||
// "cambiar de cuenta" y el resumen final ya sabe que hay cuenta.
|
||||
void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey })
|
||||
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||
// Vuelve al paso de Cobros, que es de donde salió el flujo. Setearlo siempre
|
||||
// (y no solo desde el primer paso) evita que un `?mp=` que llega con el
|
||||
// proveedor recién montado salte al resumen sin mostrar la confirmación.
|
||||
setStep(PAYMENT_STEP)
|
||||
|
||||
// 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])
|
||||
|
||||
useEffect(() => {
|
||||
const status = statusQuery.data
|
||||
if (!status) return
|
||||
// If they dropped out after connecting payments, we resume at the group step.
|
||||
// Si dejó el onboarding después de vincular los cobros, se retoma en el
|
||||
// grupo. Con la cuenta ya activa el paso 1 ya muestra "Cambiar de cuenta",
|
||||
// así que solo se salta desde la bienvenida.
|
||||
if (status.step === 'PAYMENT_CONNECTED') {
|
||||
setStep((current) => (current === 0 ? 2 : current))
|
||||
setStep((current) => (current === WELCOME_STEP ? FIRST_GROUP_STEP : current))
|
||||
}
|
||||
}, [statusQuery.data])
|
||||
|
||||
const providerName = paymentResult
|
||||
? PAYMENT_PROVIDERS.find((p) => p.value === paymentResult.provider)?.name
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<OnboardingContext.Provider
|
||||
value={{
|
||||
step,
|
||||
setStep,
|
||||
paymentResult,
|
||||
setPaymentResult,
|
||||
mpFeedback,
|
||||
createdGroup,
|
||||
setCreatedGroup,
|
||||
providerName,
|
||||
statusQuery,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { useEffect } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect } from 'react'
|
||||
import { Logo, LogoIcon } from '../../components/brand'
|
||||
import { Button } from '../../components/ui'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { ConfirmationStep } from './ConfirmationStep'
|
||||
import { FirstGroupStep } from './FirstGroupStep'
|
||||
import { useOnboarding } from './OnboardingProvider'
|
||||
import { PaymentStep } from './PaymentStep'
|
||||
import { Stepper } from './Stepper'
|
||||
import { WelcomeStep } from './WelcomeStep'
|
||||
import { PaymentStep } from './PaymentStep'
|
||||
import { FirstGroupStep } from './FirstGroupStep'
|
||||
import { ConfirmationStep } from './ConfirmationStep'
|
||||
|
||||
const STEPS = [
|
||||
{ label: 'Bienvenida' },
|
||||
@@ -21,16 +21,7 @@ const STEPS = [
|
||||
export function OnboardingView() {
|
||||
const { user, isPending: authPending } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
step,
|
||||
setStep,
|
||||
paymentResult,
|
||||
setPaymentResult,
|
||||
createdGroup,
|
||||
setCreatedGroup,
|
||||
providerName,
|
||||
statusQuery,
|
||||
} = useOnboarding()
|
||||
const { step, setStep, mpFeedback, createdGroup, setCreatedGroup, statusQuery } = useOnboarding()
|
||||
|
||||
useEffect(() => {
|
||||
if (statusQuery.data?.completed) {
|
||||
@@ -90,14 +81,7 @@ export function OnboardingView() {
|
||||
<div key={step} className="mt-8 animate-step-enter">
|
||||
{step === 0 ? <WelcomeStep name={firstName} onNext={() => setStep(1)} /> : null}
|
||||
{step === 1 ? (
|
||||
<PaymentStep
|
||||
initialResult={paymentResult}
|
||||
onConnected={(result) => {
|
||||
setPaymentResult(result)
|
||||
setStep(2)
|
||||
}}
|
||||
onBack={() => setStep(0)}
|
||||
/>
|
||||
<PaymentStep feedback={mpFeedback} onNext={() => setStep(2)} onBack={() => setStep(0)} />
|
||||
) : null}
|
||||
{step === 2 ? (
|
||||
<FirstGroupStep
|
||||
@@ -108,9 +92,7 @@ export function OnboardingView() {
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{step === 3 && createdGroup ? (
|
||||
<ConfirmationStep group={createdGroup} providerName={providerName} />
|
||||
) : null}
|
||||
{step === 3 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
|
||||
@@ -1,171 +1,122 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import type { ConnectPaymentResult, PaymentProvider } from '@gruperly/shared'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
BadgeCheck,
|
||||
Check,
|
||||
CheckCircle2,
|
||||
CreditCard,
|
||||
Loader2,
|
||||
ShieldCheck,
|
||||
} from 'lucide-react'
|
||||
import { connectPayment } from '../../lib/api'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { ArrowLeft, ArrowRight, BadgeCheck, CheckCircle2, Loader2 } from 'lucide-react'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import { PAYMENT_PROVIDERS } from './constants'
|
||||
import type { MpCallbackFeedback } from '../mp'
|
||||
import {
|
||||
formatMpConnectionDate,
|
||||
MP_PROVIDER_NAME,
|
||||
mpCallbackErrorMessage,
|
||||
mpStatusBadgeVariant,
|
||||
mpStatusLabel,
|
||||
useMpStatus,
|
||||
useStartMpAuthorization,
|
||||
} from '../mp'
|
||||
|
||||
type PaymentStepProps = {
|
||||
initialResult: ConnectPaymentResult | null
|
||||
onConnected: (result: ConnectPaymentResult) => void
|
||||
/** Resultado de la vinculación, leído de `?mp=` al volver de Mercado Pago. */
|
||||
feedback: MpCallbackFeedback | null
|
||||
onNext: () => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export function PaymentStep({ initialResult, onConnected, onBack }: PaymentStepProps) {
|
||||
const [selected, setSelected] = useState<PaymentProvider>('MERCADO_PAGO')
|
||||
const [connected, setConnected] = useState<ConnectPaymentResult | null>(initialResult)
|
||||
/**
|
||||
* Paso "Cobros" del onboarding.
|
||||
*
|
||||
* Es salteable a propósito: el profesor puede crear su grupo y empezar a usar
|
||||
* Gruperly sin vincular Mercado Pago, y hacerlo después desde Ajustes. Por eso no
|
||||
* es un radiogroup con proveedores sino una sola acción: vincular la cuenta.
|
||||
*/
|
||||
export function PaymentStep({ feedback, onNext, onBack }: PaymentStepProps) {
|
||||
const statusQuery = useMpStatus()
|
||||
const startAuthorization = useStartMpAuthorization()
|
||||
|
||||
const connect = useMutation({
|
||||
mutationFn: () => connectPayment({ provider: selected, sandbox: true }),
|
||||
onSuccess: (result) => {
|
||||
setConnected(result)
|
||||
onConnected(result)
|
||||
},
|
||||
})
|
||||
const status = statusQuery.data?.status ?? 'none'
|
||||
const isConnected = status === 'active'
|
||||
const connectedAt = formatMpConnectionDate(statusQuery.data?.connectedAt ?? null)
|
||||
|
||||
if (connected) {
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<section className="space-y-5">
|
||||
<header className="space-y-1">
|
||||
<h2 className="text-2xl font-bold text-primary">Tu cobro está conectado</h2>
|
||||
<h2 className="text-2xl font-bold text-primary">Conectá tus cobros</h2>
|
||||
<p className="text-sm text-foreground/60">
|
||||
Ya podés dejar listo tu primer grupo para cobrar con{' '}
|
||||
{PAYMENT_PROVIDERS.find((p) => p.value === connected.provider)?.name ?? ''}.
|
||||
Vinculá tu cuenta de {MP_PROVIDER_NAME} y cobrale a tus miembros desde el grupo.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="rounded-xl border border-success/30 bg-success-soft p-5 text-center">
|
||||
<span className="mx-auto flex size-12 items-center justify-center rounded-full bg-surface">
|
||||
<CheckCircle2 className="size-6 text-success" />
|
||||
</span>
|
||||
<p className="mt-3 text-sm font-semibold text-success">Cuenta conectada</p>
|
||||
<div className="mt-1 flex items-center justify-center gap-2">
|
||||
<span className="text-sm font-medium text-primary">
|
||||
{PAYMENT_PROVIDERS.find((p) => p.value === connected.provider)?.name}
|
||||
</span>
|
||||
<Badge variant="success">Modo prueba</Badge>
|
||||
{feedback?.kind === '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" />
|
||||
Tu cuenta de {MP_PROVIDER_NAME} quedó vinculada.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{feedback?.kind === 'error' ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||
{mpCallbackErrorMessage(feedback.reason)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||
<div className="flex items-center justify-between gap-3 px-4 py-3">
|
||||
<p className="text-sm font-medium text-primary">{MP_PROVIDER_NAME}</p>
|
||||
<Badge variant={mpStatusBadgeVariant(status)}>{mpStatusLabel(status)}</Badge>
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-3">
|
||||
{statusQuery.isPending ? (
|
||||
<p className="flex items-center gap-2 text-sm text-foreground/50">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
Consultando tu cuenta…
|
||||
</p>
|
||||
) : isConnected ? (
|
||||
<p className="text-sm text-foreground/60">
|
||||
{connectedAt ? `Vinculada el ${connectedAt}. ` : ''}
|
||||
Los pagos de tus grupos van a entrar a esta cuenta.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm text-foreground/60">
|
||||
Te llevamos a {MP_PROVIDER_NAME} para autorizar los cobros. Los pagos entran
|
||||
directo en tu cuenta, sin intermediarios.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-3">
|
||||
<Button
|
||||
variant="primary"
|
||||
className="w-full"
|
||||
disabled={startAuthorization.isStarting}
|
||||
onClick={() => void startAuthorization.start('onboarding')}
|
||||
>
|
||||
{startAuthorization.isStarting ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<BadgeCheck className="size-4" />
|
||||
)}
|
||||
{startAuthorization.isStarting
|
||||
? 'Abriendo Mercado Pago…'
|
||||
: isConnected
|
||||
? 'Cambiar de cuenta'
|
||||
: 'Vincular cuenta'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{startAuthorization.error ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||
{startAuthorization.error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="outline" onClick={() => setConnected(null)}>
|
||||
<Button variant="outline" onClick={onBack} className="hidden lg:inline-flex">
|
||||
<ArrowLeft className="size-4" />
|
||||
Cambiar
|
||||
Volver
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
onClick={() => onConnected(connected)}
|
||||
>
|
||||
Continuar
|
||||
<Button variant="outline" className="flex-1 lg:flex-none" onClick={onNext}>
|
||||
{isConnected ? 'Continuar' : 'Lo hago después'}
|
||||
<ArrowRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-5">
|
||||
<header className="space-y-1">
|
||||
<h2 className="text-2xl font-bold text-primary">Elegí tu procesador de cobro</h2>
|
||||
<p className="text-sm text-foreground/60">
|
||||
Los pagos de tus miembros van a llegar por esta plataforma.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div role="radiogroup" aria-label="Procesador de pago" className="space-y-3">
|
||||
{PAYMENT_PROVIDERS.map((provider) => {
|
||||
const isSelected = selected === provider.value
|
||||
return (
|
||||
<button
|
||||
key={provider.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={isSelected}
|
||||
onClick={() => setSelected(provider.value)}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-3 rounded-xl border bg-surface p-4 text-left transition-colors',
|
||||
isSelected
|
||||
? 'border-accent ring-2 ring-accent/20'
|
||||
: 'border-border hover:bg-primary-soft',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'rounded-lg p-2',
|
||||
isSelected ? 'bg-accent-soft' : 'bg-primary-soft',
|
||||
)}
|
||||
>
|
||||
<CreditCard
|
||||
className={cn('size-5', isSelected ? 'text-accent' : 'text-primary/40')}
|
||||
/>
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-sm font-semibold text-primary">
|
||||
{provider.name}
|
||||
</span>
|
||||
<span className="block text-xs text-foreground/60">
|
||||
{provider.description}
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-5 shrink-0 items-center justify-center rounded-full border transition-colors',
|
||||
isSelected ? 'border-accent bg-accent text-on-accent' : 'border-border',
|
||||
)}
|
||||
>
|
||||
{isSelected ? <Check className="size-3" strokeWidth={3} /> : null}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex items-start gap-2 rounded-xl bg-warning-soft px-4 py-3">
|
||||
<ShieldCheck className="mt-0.5 size-4 shrink-0 text-warning" />
|
||||
<p className="text-xs text-warning">
|
||||
Por ahora la conexión se hace en modo prueba (sandbox). Más adelante vas a poder
|
||||
vincular tu cuenta real de {selected === 'STRIPE' ? 'Stripe' : 'Mercado Pago'}.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{connect.isError ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||
No pudimos conectar la cuenta. Intentalo de nuevo.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
<ArrowLeft className="size-4" />
|
||||
Volver
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
disabled={connect.isPending}
|
||||
onClick={() => connect.mutate()}
|
||||
>
|
||||
{connect.isPending ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<BadgeCheck className="size-4" />
|
||||
)}
|
||||
{connect.isPending ? 'Conectando…' : 'Conectar cuenta'}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -10,7 +10,7 @@ const STEPS_TO_SETUP = [
|
||||
{
|
||||
icon: Wallet,
|
||||
title: 'Conectá tu cuenta de cobro',
|
||||
description: 'Mercado Pago o Stripe, en modo prueba por ahora.',
|
||||
description: 'Vinculá Mercado Pago y cobrale a tus miembros desde el grupo.',
|
||||
},
|
||||
{
|
||||
icon: Users,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { BillingType, PaymentProvider, WeekDay } from '@gruperly/shared'
|
||||
export { BILLING_LABELS, WEEK_DAY_FULL_LABELS, formatPrice, formatSchedule } from '../../lib/format'
|
||||
import type { BillingType, WeekDay } from '@gruperly/shared'
|
||||
|
||||
export { BILLING_LABELS, formatPrice, formatSchedule, WEEK_DAY_FULL_LABELS } from '../../lib/format'
|
||||
|
||||
export const WEEK_DAYS: readonly WeekDay[] = [
|
||||
'MONDAY',
|
||||
@@ -21,23 +22,6 @@ export const WEEK_DAY_CHIPS: readonly { value: WeekDay; label: string }[] = [
|
||||
{ value: 'SUNDAY', label: 'Dom' },
|
||||
]
|
||||
|
||||
export const PAYMENT_PROVIDERS: readonly {
|
||||
value: PaymentProvider
|
||||
name: string
|
||||
description: string
|
||||
}[] = [
|
||||
{
|
||||
value: 'MERCADO_PAGO',
|
||||
name: 'Mercado Pago',
|
||||
description: 'El procesador más usado en Latinoamérica',
|
||||
},
|
||||
{
|
||||
value: 'STRIPE',
|
||||
name: 'Stripe',
|
||||
description: 'Cobrá con tarjetas e internacionalmente',
|
||||
},
|
||||
]
|
||||
|
||||
export const BILLING_TYPES: readonly { value: BillingType; label: string; hint: string }[] = [
|
||||
{ value: 'MONTHLY', label: 'Mensual', hint: 'Un cobro por mes' },
|
||||
{ value: 'PER_CLASS', label: 'Por clase', hint: 'Cada clase que asista' },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Check } from 'lucide-react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { useTheme } from '../../context/ThemeProvider'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { THEME_ICONS, THEME_OPTIONS } from './constants'
|
||||
|
||||
export function AppearanceCard() {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { Fingerprint } from 'lucide-react'
|
||||
import { signOut } from '../../lib/auth-client'
|
||||
import { Button } from '../../components/ui'
|
||||
import { signOut } from '../../lib/auth-client'
|
||||
import { MpStatusCard } from '../mp'
|
||||
import { AppearanceCard } from './AppearanceCard'
|
||||
|
||||
export function SettingsView() {
|
||||
@@ -31,6 +32,8 @@ export function SettingsView() {
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<MpStatusCard />
|
||||
|
||||
<AppearanceCard />
|
||||
|
||||
<Button variant="outline" onClick={handleSignOut}>
|
||||
|
||||
@@ -10,8 +10,6 @@ import type {
|
||||
BulkCreateAttendees,
|
||||
BulkCreateAttendeesResult,
|
||||
ClassTodayList,
|
||||
ConnectPayment,
|
||||
ConnectPaymentResult,
|
||||
CreateAttendee,
|
||||
CreateAttendeeResult,
|
||||
CreateFirstGroup,
|
||||
@@ -33,6 +31,10 @@ import type {
|
||||
JoinGroupViaInviteResult,
|
||||
MarkAttendance,
|
||||
MarkAttendanceResult,
|
||||
MpAuthorizationUrlDto,
|
||||
MpDisconnectResultDto,
|
||||
MpReturnTo,
|
||||
MpStatusDto,
|
||||
NotifyAbsence,
|
||||
NotifyAbsenceResult,
|
||||
OnboardingStatusDto,
|
||||
@@ -92,12 +94,6 @@ async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
|
||||
export const getOnboardingStatus = () => apiFetch<OnboardingStatusDto>('/api/v1/onboarding/status')
|
||||
|
||||
export const connectPayment = (payload: ConnectPayment) =>
|
||||
apiFetch<ConnectPaymentResult>('/api/v1/onboarding/payment-setup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
export const createFirstGroup = (payload: CreateFirstGroup) =>
|
||||
apiFetch<CreateFirstGroupResult>('/api/v1/onboarding/first-group', {
|
||||
method: 'POST',
|
||||
@@ -110,6 +106,19 @@ export const createGroup = (payload: CreateFirstGroup) =>
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
// — Mercado Pago —
|
||||
|
||||
/* La vinculación es un OAuth: el backend devuelve la URL de autorización y el
|
||||
navegador navega a Mercado Pago. `returnTo` le dice al callback a qué pantalla
|
||||
volver (solo `onboarding` o `settings`: nunca una URL libre). */
|
||||
export const startMpAuthorization = (returnTo: MpReturnTo) =>
|
||||
apiFetch<MpAuthorizationUrlDto>(`/api/v1/mp/connect?returnTo=${returnTo}`)
|
||||
|
||||
export const getMpStatus = () => apiFetch<MpStatusDto>('/api/v1/mp/status')
|
||||
|
||||
export const disconnectMp = () =>
|
||||
apiFetch<MpDisconnectResultDto>('/api/v1/mp/connect', { method: 'DELETE' })
|
||||
|
||||
/* The groups screen has no pagination: we ask for the maximum allowed so no
|
||||
group is left out of the listing, and for the browser time zone so the
|
||||
backend sorts by the next class in the person's local time. */
|
||||
|
||||
@@ -3,6 +3,13 @@ import { OnboardingProvider } from '../features/onboarding/OnboardingProvider'
|
||||
import { OnboardingView } from '../features/onboarding/OnboardingView'
|
||||
|
||||
export const Route = createFileRoute('/onboarding')({
|
||||
/* El callback de Mercado Pago devuelve el control acá con `?mp=success` o
|
||||
`?mp=error&reason=…`. Se valida como search param para que el provider tenga
|
||||
los dos valores ya tipados y no tenga que leer el `location` crudo. */
|
||||
validateSearch: (search: Record<string, unknown>): { mp?: string; reason?: string } => ({
|
||||
mp: typeof search.mp === 'string' ? search.mp : undefined,
|
||||
reason: typeof search.reason === 'string' ? search.reason : undefined,
|
||||
}),
|
||||
component: () => (
|
||||
<OnboardingProvider>
|
||||
<OnboardingView />
|
||||
|
||||
81
apps/web/test/mp-copy.test.ts
Normal file
81
apps/web/test/mp-copy.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import {
|
||||
formatMpConnectionDate,
|
||||
mpCallbackErrorMessage,
|
||||
mpStatusBadgeVariant,
|
||||
mpStatusLabel,
|
||||
readMpCallbackFeedback,
|
||||
shouldShowMpReauthNotice,
|
||||
} from '../src/features/mp/copy'
|
||||
|
||||
/* El copy de Mercado Pago es la única fuente de la verdad de lo que el profesor
|
||||
lee, y el paso del onboarding, Ajustes y el aviso global lo comparten. */
|
||||
|
||||
describe('readMpCallbackFeedback', () => {
|
||||
test('lee el resultado de la vinculación desde la URL', () => {
|
||||
expect(readMpCallbackFeedback('success', undefined)).toEqual({ kind: 'success' })
|
||||
expect(readMpCallbackFeedback('error', 'mp_denied')).toEqual({
|
||||
kind: 'error',
|
||||
reason: 'mp_denied',
|
||||
})
|
||||
})
|
||||
|
||||
test('sin parámetros no hay nada que mostrar', () => {
|
||||
expect(readMpCallbackFeedback(undefined, undefined)).toBeNull()
|
||||
expect(readMpCallbackFeedback(undefined, 'mp_denied')).toBeNull()
|
||||
})
|
||||
|
||||
test('un motivo desconocido se degrada a un fallo genérico', () => {
|
||||
// Nunca se muestra en pantalla lo que venga en la URL: el backend manda el
|
||||
// código y esta función decide el texto.
|
||||
expect(readMpCallbackFeedback('error', 'stack trace')).toEqual({
|
||||
kind: 'error',
|
||||
reason: 'mp_error',
|
||||
})
|
||||
expect(readMpCallbackFeedback('error', undefined)).toEqual({
|
||||
kind: 'error',
|
||||
reason: 'mp_error',
|
||||
})
|
||||
expect(readMpCallbackFeedback('algo-distinto', 'mp_denied')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mpCallbackErrorMessage', () => {
|
||||
test('cada motivo tiene su propio mensaje', () => {
|
||||
const reasons = ['invalid_state', 'mp_denied', 'mp_error', 'mp_account_in_use'] as const
|
||||
const messages = reasons.map(mpCallbackErrorMessage)
|
||||
|
||||
expect(new Set(messages).size).toBe(reasons.length)
|
||||
expect(messages.every((message) => message.length > 0)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('estado de la cuenta', () => {
|
||||
test('cada estado tiene su etiqueta y su color', () => {
|
||||
expect(mpStatusLabel('none')).toBe('Sin vincular')
|
||||
expect(mpStatusLabel('active')).toBe('Vinculada')
|
||||
expect(mpStatusLabel('requires_reauth')).toBe('Necesita vincularse de nuevo')
|
||||
|
||||
expect(mpStatusBadgeVariant('none')).toBe('neutral')
|
||||
expect(mpStatusBadgeVariant('active')).toBe('success')
|
||||
expect(mpStatusBadgeVariant('requires_reauth')).toBe('warning')
|
||||
})
|
||||
|
||||
test('solo requiere_reauth levanta el aviso global', () => {
|
||||
// "Sin vincular" es legítimo: el paso del onboarding es salteable.
|
||||
expect(shouldShowMpReauthNotice('requires_reauth')).toBe(true)
|
||||
expect(shouldShowMpReauthNotice('active')).toBe(false)
|
||||
expect(shouldShowMpReauthNotice('none')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatMpConnectionDate', () => {
|
||||
test('formatea la fecha de vinculación', () => {
|
||||
expect(formatMpConnectionDate('2026-10-05T12:00:00.000Z')).toMatch(/2026/)
|
||||
})
|
||||
|
||||
test('sin fecha o con una inválida no inventa nada', () => {
|
||||
expect(formatMpConnectionDate(null)).toBeNull()
|
||||
expect(formatMpConnectionDate('no-es-fecha')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -22,6 +22,16 @@ x-backend-env: &backend-env
|
||||
EMAIL_SERVER_USER: ${EMAIL_SERVER_USER:-}
|
||||
EMAIL_SERVER_PASSWORD: ${EMAIL_SERVER_PASSWORD:-}
|
||||
EMAIL_FROM: "${EMAIL_FROM:-Gruperly <no-reply@gruperly.com>}"
|
||||
# Mercado Pago OAuth. Opcionales: sin credenciales, GET /mp/connect responde
|
||||
# 503 mp_not_configured y la app sigue funcionando (el paso es salteable).
|
||||
MP_CLIENT_ID: ${MP_CLIENT_ID:-}
|
||||
MP_CLIENT_SECRET: ${MP_CLIENT_SECRET:-}
|
||||
# Tiene que coincidir con la "Redirect URL" del panel de MP, character por
|
||||
# character. En produccion, HTTPS y la URL publica de la API.
|
||||
MP_REDIRECT_URI: ${MP_REDIRECT_URI:-}
|
||||
# Clave de 32 bytes en base64 (openssl rand -base64 32) para cifrar los tokens
|
||||
# en reposo. Sin ella, mp/callback falla al guardar la cuenta.
|
||||
TOKEN_ENCRYPTION_KEY: ${TOKEN_ENCRYPTION_KEY:-}
|
||||
|
||||
services:
|
||||
api:
|
||||
|
||||
@@ -8,6 +8,7 @@ export * from './schemas/enums.js';
|
||||
export * from './schemas/groups.js';
|
||||
export * from './schemas/health-check.js';
|
||||
export * from './schemas/home.js';
|
||||
export * from './schemas/mp.js';
|
||||
export * from './schemas/onboarding.js';
|
||||
export * from './schemas/pagination.js';
|
||||
export * from './schemas/payments.js';
|
||||
|
||||
@@ -12,10 +12,6 @@ export const weekdaySchema = z.enum([
|
||||
]);
|
||||
export type WeekDay = z.output<typeof weekdaySchema>;
|
||||
|
||||
// Supported payment processors.
|
||||
export const paymentProviderSchema = z.enum(['MERCADO_PAGO', 'STRIPE']);
|
||||
export type PaymentProvider = z.output<typeof paymentProviderSchema>;
|
||||
|
||||
// Billing frequency of a group.
|
||||
export const billingTypeSchema = z.enum(['MONTHLY', 'PER_CLASS']);
|
||||
export type BillingType = z.output<typeof billingTypeSchema>;
|
||||
66
packages/shared/src/schemas/mp.ts
Normal file
66
packages/shared/src/schemas/mp.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// State of the teacher's Mercado Pago account, as the app sees it.
|
||||
// A `revoked` row (the teacher unlinked) is reported as 'none': there is
|
||||
// nothing usable left, but the row is kept so the Mercado Pago user stays
|
||||
// reserved for whoever linked it.
|
||||
export const mpAccountStatusSchema = z.enum(['none', 'active', 'requires_reauth']);
|
||||
export type MpAccountStatus = z.output<typeof mpAccountStatusSchema>;
|
||||
|
||||
// Why the OAuth callback failed. These codes are safe to hand to the browser:
|
||||
// they never describe an internal failure, only a reason the teacher can act on.
|
||||
export const mpCallbackReasonSchema = z.enum([
|
||||
// 'state' missing, unknown, expired or already used.
|
||||
'invalid_state',
|
||||
// The teacher rejected the consent screen on Mercado Pago.
|
||||
'mp_denied',
|
||||
// Mercado Pago refused to exchange the code, or was unreachable.
|
||||
'mp_error',
|
||||
// That Mercado Pago account is already linked to another teacher.
|
||||
'mp_account_in_use',
|
||||
]);
|
||||
export type MpCallbackReason = z.output<typeof mpCallbackReasonSchema>;
|
||||
|
||||
// Where the teacher started the flow, so the callback can send them back.
|
||||
export const mpReturnToSchema = z.enum(['onboarding', 'settings']);
|
||||
export type MpReturnTo = z.output<typeof mpReturnToSchema>;
|
||||
|
||||
export const MpConnectQuerySchema = z.strictObject({
|
||||
returnTo: mpReturnToSchema.default('settings'),
|
||||
});
|
||||
export type MpConnectQuery = z.output<typeof MpConnectQuerySchema>;
|
||||
|
||||
// Deliberately not `strictObject`: this query is written by Mercado Pago, not by
|
||||
// us. Alongside `error` it may send `error_description` and other fields we do
|
||||
// not model, and a strict schema would answer those with a 400 problem body in
|
||||
// the teacher's browser instead of the redirect this route exists to perform.
|
||||
// Unknown keys are stripped and ignored.
|
||||
export const MpCallbackQuerySchema = z.object({
|
||||
// Mercado Pago may answer with `error` instead of `code` when the teacher
|
||||
// rejects the consent screen, and omits `state` in some failure paths.
|
||||
code: z.string().min(1).optional(),
|
||||
state: z.string().min(1).optional(),
|
||||
error: z.string().min(1).optional(),
|
||||
});
|
||||
export type MpCallbackQuery = z.output<typeof MpCallbackQuerySchema>;
|
||||
|
||||
export const MpAuthorizationUrlDtoSchema = z.object({
|
||||
authorizationUrl: z.string(),
|
||||
});
|
||||
export type MpAuthorizationUrlDto = z.output<typeof MpAuthorizationUrlDtoSchema>;
|
||||
|
||||
export const MpStatusDtoSchema = z.object({
|
||||
status: mpAccountStatusSchema,
|
||||
liveMode: z.boolean(),
|
||||
expiresAt: z.string().nullable(),
|
||||
connectedAt: z.string().nullable(),
|
||||
// Last digits of the Mercado Pago id, so a teacher can tell whether they
|
||||
// linked the account they meant to. Never the full id.
|
||||
mpUserIdSuffix: z.string().nullable(),
|
||||
});
|
||||
export type MpStatusDto = z.output<typeof MpStatusDtoSchema>;
|
||||
|
||||
export const MpDisconnectResultDtoSchema = z.object({
|
||||
disconnected: z.boolean(),
|
||||
});
|
||||
export type MpDisconnectResultDto = z.output<typeof MpDisconnectResultDtoSchema>;
|
||||
@@ -1,27 +1,12 @@
|
||||
import { z } from 'zod';
|
||||
import { billingTypeSchema, paymentProviderSchema, weekdaySchema } from './enums.js';
|
||||
import { billingTypeSchema, weekdaySchema } from './enums.js';
|
||||
import { GroupDtoSchema } from './groups.js';
|
||||
|
||||
export type { BillingType, PaymentProvider, WeekDay } from './enums.js';
|
||||
export { billingTypeSchema, paymentProviderSchema, weekdaySchema } from './enums.js';
|
||||
export type { BillingType, WeekDay } from './enums.js';
|
||||
export { billingTypeSchema, weekdaySchema } from './enums.js';
|
||||
|
||||
// Step 2: link the teacher's payment account.
|
||||
export const ConnectPaymentSchema = z.strictObject({
|
||||
provider: paymentProviderSchema,
|
||||
// For the MVP it connects in simulation / sandbox mode.
|
||||
sandbox: z.boolean().default(true),
|
||||
accessToken: z.string().optional(),
|
||||
});
|
||||
export type ConnectPayment = z.output<typeof ConnectPaymentSchema>;
|
||||
|
||||
export const ConnectPaymentResultSchema = z.object({
|
||||
provider: paymentProviderSchema,
|
||||
sandbox: z.boolean(),
|
||||
connected: z.boolean(),
|
||||
});
|
||||
export type ConnectPaymentResult = z.output<typeof ConnectPaymentResultSchema>;
|
||||
|
||||
// Step 3: create the teacher's first group.
|
||||
// Step 3: create the teacher's first group. Linking Mercado Pago is step 2 and
|
||||
// is skippable, so nothing here may require a linked account.
|
||||
export const CreateFirstGroupSchema = z.strictObject({
|
||||
name: z
|
||||
.string()
|
||||
|
||||
Reference in New Issue
Block a user