feat: add country selection during onboarding and implement payment management features

- Introduced CountryStep component for selecting the country during onboarding, affecting payment currency.
- Updated FirstGroupStep to include country information.
- Enhanced PaymentsProvider to manage payment states and renewals.
- Created PaymentRow component for displaying individual payment details.
- Implemented PaymentsView for listing and filtering payments by group and status.
- Added API endpoints for fetching and creating payments, including batch processing.
- Defined payment schemas for validation and data handling.
- Updated GroupHeader and GroupDetailView to include charging functionality for group members.
This commit is contained in:
Jose Selesan
2026-10-08 11:42:13 -03:00
parent b11dd47534
commit 8c5caecdda
49 changed files with 2367 additions and 90 deletions

View File

@@ -31,7 +31,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`). - `src/modules/<modulo>/` — por módulo: `index.ts`, `routes.ts` y `features/<accion>/{route,use-case}.ts`. **Patrón**: el route valida (`validate.query/json`) y delega en un use-case que devuelve `Result<T, ProblemDetails>` (`ok`/`err` desde `@gruperly/shared`); el route responde con `resultJson` (o `problemJson`).
- `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`. - `src/lib/` — `prisma.ts` (`getPrismaClient`, proxy `default` y clase `UnitOfWork`), `pagination.ts` (offset/metadata), `email.ts`, `error-message.ts`.
- `src/logger.ts` — pino + pino-pretty. - `src/logger.ts` — pino + pino-pretty.
- Módulos existentes: `mp` (OAuth de Mercado Pago, Authorization Code + PKCE; `apps/backend/src/modules/mp/`), `health-check`, `auth` (**Better Auth 1.7.2 público**, montado en `/api/v1/auth` vía `basePath` del server; cookie de sesión con `path: "/"`), `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. `payments` (links de Checkout Pro por alumno y período): `GET /api/v1/payments` (get-all) y `POST /api/v1/payments/:id/renew` se montan en `modules/payments/routes.ts`; **el batch** (`POST /groups/:gid/payments/batch`) se engancha en `modules/groups/routes.ts` porque nace del grupo. Los jobs de reconciliación por polling (`ReconcilePayments`, `*/15 * * * *`) y overdue (`MarkOverduePayments`, `4 4 * * *` UTC) viven en `modules/payments/jobs/` y los arranca `startPaymentJobs()` desde `server.ts`.
- `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`). - `apps/web` — Frontend React 19 + Vite + Tailwind v4. Entry `src/main.tsx` → `src/router.tsx`. Puerto **6173** (`vite.config.ts`). Auth client con `basePath: '/api/v1/auth'` (`src/lib/auth-client.ts`). Es una **PWA instalable** (`vite-plugin-pwa` + Workbox, config en `vite.config.ts`); el registro del SW y el banner de instalación viven en `src/features/pwa/` (`PwaProvider`, montado en `main.tsx` dentro de `ToastProvider`).
- `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`. - `packages/shared` — Esquemas Zod (v3.24) + tipos + `Result` + Problem Details. **Se consume como TS fuente directo** (`exports` apunta a `src/index.ts`, sin build previo); se resuelve vía el symlink de bun en `node_modules` (`@gruperly/shared` no está en `paths` de los tsconfig). El `paths` de los tsconfig solo mapea `@/*` → `src/*` y `@generated/*` → `generated/*`.
- `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete). - `packages/config` — `tsconfig.base.json`; tsconfigs lo extienden con `"extends": "@gruperly/config/tsconfig.base.json"` (por eso `@gruperly/config` es devDependency de cada paquete).
@@ -41,6 +41,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`. - **Mercado Pago (`modules/mp/`)**: el paso "Cobros" del onboarding es **salteable** y no hay ningún gate `payment_not_setup`: sin cuenta vinculada se puede crear el grupo igual. `GET /mp/connect` devuelve `{ authorizationUrl }` (el navegador navega; no se puede hacer con `fetch`), `GET /mp/callback` **siempre** responde 302 (a `/onboarding` o `/settings` con `?mp=success` / `?mp=error&reason=…`), `GET /mp/status` da `none|active|requires_reauth` (un `REVOKED` se reporta como `none`) y `DELETE /mp/connect` vacía los tokens sin borrar la fila, para que la cuenta de MP quede reservada al mismo profesor. Ojo con cuatro cosas: (1) `MpCallbackQuerySchema` es `z.object` y no `strictObject` a propósito —MP manda `error_description` y otros campos, y un esquema estricto devolvía un 400 JSON en el navegador en vez del redirect—; (2) los tokens se cifran con AES-256-GCM (`sealToken`/`openToken`, payload `v1:iv:tag:ciphertext`) y `TOKEN_ENCRYPTION_KEY` tiene que decodificar a 32 bytes; cambiar la clave deja ilegibles las cuentas existentes; (3) el `state` (10 min, en `mp_oauth_states`) se **quema antes** de hablar con MP: `deleteMany().count === 0` significa replay; (4) el panel de MP exige **HTTPS** en la Redirect URL (rechaza `http://localhost`), así que en local el callback pasa por un túnel (`ngrok http --url=https://TU-DOMINIO.ngrok-free.app 4000`, dominio fijo por cuenta; los quick tunnels de cloudflared cambian de URL en cada arranque) —`MP_REDIRECT_URI` y el panel deben coincidir carácter a carácter—, y las credenciales en dev son las de **producción** de la app (no existe OAuth sandbox; el OAuth solo vincula y no mueve dinero). El cron de renovación (`17 3 * * *` UTC, lotes de 20 con `FOR UPDATE SKIP LOCKED`) solo marca `REQUIRES_REAUTH` con `invalid_grant`, nunca por un 5xx. Nunca loguear tokens, `code`, `code_verifier` ni `client_secret`.
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`. - **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness. - **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
- **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema. - **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema.
- **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación. - **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `<link>` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación.
- **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari). - **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari).

View File

@@ -69,7 +69,7 @@ En DevTools → Application: el manifest sin warnings, el service worker `activa
## Mercado Pago (OAuth) ## 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. 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`). El OAuth vive en `apps/backend/src/modules/mp/`; los links de pago y la reconciliación están en `modules/payments/` (ver [Cobros](#cobros-links-de-pago)).
**Panel de Mercado Pago** (Developer panel → Tu aplicación): **Panel de Mercado Pago** (Developer panel → Tu aplicación):
@@ -88,7 +88,7 @@ Los cobros llegan a la cuenta del profesor a través de una app de Mercado Pago
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**. 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. 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 links de pago también se prueban con la cuenta propia (crear un link no cobra nada; el cobro real le pide credenciales de pago al alumno).
### Cómo funciona ### Cómo funciona
@@ -117,6 +117,35 @@ onboarding/ajustes → GET /mp/connect → { authorizationUrl } (state
curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: <cookie de sesión>' | jq curl -s http://localhost:4000/api/v1/mp/status -H 'Cookie: <cookie de sesión>' | jq
``` ```
## Cobros (links de pago)
Un cobro es un **link de pago de Checkout Pro por alumno y por período**. El profesor lo dispara desde la ficha del grupo (**Cobrar**, habilitado cuando el grupo tiene precio): se crea un `Payment` por cada asistente activo y, para cada uno, una preferencia de Checkout Pro con `external_reference` = id del pago. Crear un link no cobra nada; el cobro real lo paga el alumno desde el link.
La moneda sale del país del profesor (`user.country`, elegido en el onboarding; default `AR` → `ARS`): `AR→ARS, BR→BRL, CL→CLP, CO→COP, MX→MXN, PE→PEN, UY→UYU`.
**Endpoints** (todos requieren sesión; solo grupos propios o donde el profesor es miembro):
| Endpoint | Qué hace |
| --- | --- |
| `POST /api/v1/groups/:groupId/payments/batch` | Crea el lote. Body: `{ dueDate, description?, attendeeIds? }`. Responde `201` con `{ total, linked, failed, items }`; cada item es `LINKED` (trae `checkoutUrl`) o `FAILED` (error del proveedor, la fila queda `PENDING` sin link) |
| `POST /api/v1/payments/:id/renew` | Regenera el link de un pago que lo perdió (item `FAILED`). Idempotente: si ya tiene link, lo devuelve tal cual |
| `GET /api/v1/payments?groupId&status&page&pageSize` | Lista paginada `{ data, pagination }` de los cobros visibles |
**Estados**: `PENDING` (esperando pago) → `PAID` (aprobado en MP) | `OVERDUE` (venció + 24 h de gracia y sigue sin pagar; sigue siendo cobrable) | `CANCELLED` (reservado, hoy no se usa).
**Reconciliación, sin webhook.** El MVP consolida por polling porque un webhook exige una URL pública y verificación de firma, y no aporta nada a esta escala: un cron cada 15 min consulta la API de MP por `external_reference`, y si el pago está `approved` marca el `Payment` como `PAID` (guarda `mpPaymentId` y `paidAt`). Solo toca pagos con link y de más de 5 min de antigüedad, en lotes de 50. Un cron diario (`4 4 * * *` UTC) convierte en `OVERDUE` los `PENDING` cuya fecha venció hace más de 24 h. Los anuncian en el log (`startPaymentJobs()` en `apps/backend/src/server.ts`).
**En la web**: la vista **Cobros** (nav) filtra por grupo y estado y deja copiar el link o regenerarlo con "Generar link" (botón renovar). Del modal **Cobrar** en la ficha del grupo se eligen vencimiento y descripción (default: mes en mayúscula) y se muestra un link por alumno para copiar, con los que fallaron listos para reintentar.
**Errores típicos**: `409 group_without_price` (el grupo no tiene precio definido), `409 no_attendees_to_bill` (sin alumnos activos), `409 mp_not_connected` (el dueño desvinculó MP), `503 mp_not_configured` (faltan las env vars del OAuth).
### Verificar a mano (además del flujo de OAuth)
1. Con un grupo con precio y alumnos, "Cobrar" → elegir vencimiento → los links se generan uno por alumno.
2. En **Cobros** el grupo aparece con `PENDING` por alumno; "Copiar" pega un link `https://www.mercadopago.com.ar/checkout/v1/…`.
3. Abrir el link, pagar (puede fallar si el teste es con la cuenta real: probar el "sandbox de pago" del panel si existe) y esperar la reconciliación (hasta 15 min) o correr el job a mano.
4. Un pago aprobado pasa a `PAID`; uno cuyo vencimiento pasó (con +24 h) pasa a `OVERDUE` y permite regenerar el link.
## Deploy en producción (Docker / Dokploy) ## Deploy en producción (Docker / Dokploy)
Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx). Dos imágenes y un compose: `Dockerfile.backend` (API Bun) y `Dockerfile.web` (Vite + nginx).

View File

@@ -0,0 +1,13 @@
-- Country of the professor (onboarding) + Mercado Pago Checkout Pro payment links.
-- AlterTable (users)
ALTER TABLE "users" ADD COLUMN "country_code" TEXT;
-- AlterTable (payments)
ALTER TABLE "payments" ADD COLUMN "description" TEXT;
ALTER TABLE "payments" ADD COLUMN "checkout_url" TEXT;
ALTER TABLE "payments" ADD COLUMN "mp_preference_id" TEXT;
ALTER TABLE "payments" ADD COLUMN "mp_payment_id" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "payments_mp_preference_id_key" ON "payments"("mp_preference_id");

View File

@@ -7,6 +7,7 @@ model User {
emailVerified Boolean @default(false) @map("email_verified") emailVerified Boolean @default(false) @map("email_verified")
image String? image String?
onboardingCompleted Boolean @default(false) @map("onboarding_completed") onboardingCompleted Boolean @default(false) @map("onboarding_completed")
country String? @map("country_code")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")

View File

@@ -95,9 +95,13 @@ model Payment {
groupId String @map("group_id") groupId String @map("group_id")
attendeeId String @map("attendee_id") attendeeId String @map("attendee_id")
amount Decimal @db.Decimal(10, 2) amount Decimal @db.Decimal(10, 2)
currency String @default("MXN") currency String @default("ARS")
status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED status PaymentStatus @default(PENDING) // PENDING, PAID, OVERDUE, CANCELLED
dueDate DateTime @map("due_date") dueDate DateTime @map("due_date")
description String? @map("description")
checkoutUrl String? @map("checkout_url")
mpPreferenceId String? @unique(map: "payments_mp_preference_id_key") @map("mp_preference_id")
mpPaymentId String? @map("mp_payment_id")
paidAt DateTime? @map("paid_at") paidAt DateTime? @map("paid_at")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")

View File

@@ -142,4 +142,18 @@ export function attendeeHasPaymentsProblem(): ProblemDetails {
detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.', detail: 'Este miembro tiene cobros asociados. Gestiona o cancela sus cobros antes de quitarlo del grupo.',
code: 'attendee_has_payments', code: 'attendee_has_payments',
}); });
}
export function groupWithoutPriceProblem(): ProblemDetails {
return conflictProblem({
detail: 'Definí el precio del grupo antes de generar los cobros.',
code: 'group_without_price',
});
}
export function noAttendeesToBillProblem(): ProblemDetails {
return conflictProblem({
detail: 'No hay miembros activos con un cobro pendiente para este grupo.',
code: 'no_attendees_to_bill',
});
} }

View File

@@ -9,6 +9,7 @@ import removeAttendeeRoute from '../attendees/features/remove/route';
import updateAttendeeRoute from '../attendees/features/update/route'; import updateAttendeeRoute from '../attendees/features/update/route';
import groupPreRegistrationRoutes from '../group-preregistrations/routes'; import groupPreRegistrationRoutes from '../group-preregistrations/routes';
import groupWaitlistRoutes from '../group-waitlist/routes'; import groupWaitlistRoutes from '../group-waitlist/routes';
import createPaymentsBatchRoute from '../payments/features/create-batch/route';
import createGroupRoute from './features/create/route'; import createGroupRoute from './features/create/route';
import getAllRoute from './features/get-all/route'; import getAllRoute from './features/get-all/route';
import getByIdRoute from './features/get-by-id/route'; import getByIdRoute from './features/get-by-id/route';
@@ -24,6 +25,7 @@ routes.route('/', listAttendeesRoute);
routes.route('/', createAttendeeRoute); routes.route('/', createAttendeeRoute);
routes.route('/', bulkCreateAttendeesRoute); routes.route('/', bulkCreateAttendeesRoute);
routes.route('/', getByIdRoute); routes.route('/', getByIdRoute);
routes.route('/', createPaymentsBatchRoute);
routes.route('/', addToGroupWaitlistRoute); routes.route('/', addToGroupWaitlistRoute);
routes.route('/', groupWaitlistRoutes); routes.route('/', groupWaitlistRoutes);
routes.route('/', groupPreRegistrationRoutes); routes.route('/', groupPreRegistrationRoutes);

View File

@@ -6,6 +6,14 @@ export {
openToken, openToken,
sealToken, sealToken,
} from './crypto'; } from './crypto';
export {
createCheckoutPreference,
MP_API_URL,
type MpCreatePreferenceInput,
type MpPreference,
type MpSearchedPayment,
searchMpPaymentByExternalReference,
} from './mp-http';
export { export {
buildAuthorizationUrl, buildAuthorizationUrl,
exchangeAuthorizationCode, exchangeAuthorizationCode,

View File

@@ -0,0 +1,138 @@
import { logger } from '@/logger';
import { MpApiError } from './mp-oauth';
export const MP_API_URL = 'https://api.mercadopago.com';
// Mercado Pago runs the seller's money straight into the professor's own
// account: no platform_id of ours and no fee split.
export type MpCreatePreferenceInput = {
title: string;
unitPrice: number;
currencyId: string;
externalReference: string;
/** Where the buyer lands after paying (pending/success/failure). */
backUrl: string;
};
export type MpPreference = {
id: string;
initPoint: string;
sandboxInitPoint: string | null;
};
/**
* Creates a Checkout Pro preference in the seller's account. This is a payment
* *link*: nothing is charged, and creating it again after a lost connection is
* safe (same external_reference would be a new link for the same payment).
*/
export async function createCheckoutPreference(
accessToken: string,
input: MpCreatePreferenceInput,
): Promise<MpPreference> {
let response: Response;
try {
response = await fetch(`${MP_API_URL}/checkout/preferences`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
items: [
{
title: input.title,
currency_id: input.currencyId,
quantity: 1,
unit_price: input.unitPrice,
},
],
external_reference: input.externalReference,
auto_return: 'approved',
back_urls: {
success: input.backUrl,
pending: input.backUrl,
failure: input.backUrl,
},
}),
});
} catch (error) {
logger.error({ err: error }, 'Mercado Pago preferences endpoint unreachable');
throw new MpApiError(0, null);
}
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null;
const reason = typeof payload?.error === 'string' ? payload.error : null;
logger.error(
{ status: response.status, reason },
'Mercado Pago preferences request failed',
);
throw new MpApiError(response.status, reason);
}
const payload = (await response.json()) as Record<string, unknown>;
return {
id: String(payload.id),
initPoint: String(payload.init_point),
sandboxInitPoint: payload.sandbox_init_point == null ? null : String(payload.sandbox_init_point),
};
}
export type MpSearchedPayment = {
id: string;
status: string;
externalReference: string;
liveMode: boolean;
dateApproved: string | null;
};
/**
* Finds a payment created for one of our payment rows.
*
* This is the reconciliation path: instead of trusting a webhook, the job asks
* the seller's account for payments whose `external_reference` is our payment
* id. Only an approved payment whose reference matches ours is a PAID row.
*/
export async function searchMpPaymentByExternalReference(
accessToken: string,
externalReference: string,
): Promise<MpSearchedPayment | null> {
const url = new URL(`${MP_API_URL}/v1/payments/search`);
url.searchParams.set('external_reference', externalReference);
let response: Response;
try {
response = await fetch(url, {
headers: { Accept: 'application/json', Authorization: `Bearer ${accessToken}` },
});
} catch (error) {
logger.error({ err: error }, 'Mercado Pago payments search unreachable');
throw new MpApiError(0, null);
}
if (!response.ok) {
logger.error({ status: response.status }, 'Mercado Pago payments search failed');
throw new MpApiError(response.status, null);
}
const payload = (await response.json()) as { results?: Record<string, unknown>[] } | null;
const results = payload?.results ?? [];
const match = results.find(
(payment) => payment.external_reference === externalReference,
);
if (!match) {
return null;
}
return {
id: String(match.id),
status: String(match.status),
externalReference: String(match.external_reference),
liveMode: Boolean(match.live_mode),
dateApproved:
typeof match.date_approved === 'string' ? match.date_approved : null,
};
}

View File

@@ -60,7 +60,7 @@ export class CreateFirstGroup {
await tx.user.update({ await tx.user.update({
where: { id: userId }, where: { id: userId },
data: { onboardingCompleted: true }, data: { onboardingCompleted: true, country: data.country },
}); });
return ok(created); return ok(created);

View File

@@ -0,0 +1,27 @@
import type { CreatePaymentsBatch } from '@gruperly/shared';
import { CreatePaymentsBatchSchema } from '@gruperly/shared';
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate';
import { CreatePaymentBatch } from './use-case';
const route = new Hono();
route.post(
'/:groupId/payments/batch',
validate.json(CreatePaymentsBatchSchema),
async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const groupId = c.req.param('groupId');
const body = c.req.valid('json') as CreatePaymentsBatch;
const result = await new CreatePaymentBatch().execute(groupId, user.id, body);
return resultJson(c, result, { status: 201 });
},
);
export default route;

View File

@@ -0,0 +1,159 @@
import type { PrismaClient } from '@generated/prisma/client';
import type {
CountryCode,
CreatePaymentsBatch,
CreatePaymentsBatchResult,
PaymentBatchItem,
ProblemDetails,
Result,
} from '@gruperly/shared';
import { currencyForCountry, err, ok } from '@gruperly/shared';
import {
groupWithoutPriceProblem,
noAttendeesToBillProblem,
noGroupAccessProblem,
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin, MpApiError } from '@/modules/mp/lib';
type BatchDeps = {
db?: Pick<PrismaClient, 'group' | 'attendee' | 'payment' | 'user'>;
createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken;
webOrigin?: string;
};
/**
* Creates one Checkout Pro payment link per active attendee of a group.
*
* The rows are created first (they are the single source of truth); a preference
* that fails leaves its row PENDING without a link, and the professor retries
* that one with `POST /payments/:id/renew` from the Cobros screen. A duplicate
* batch call for the same period is up to the professor: each run creates new
* links and creating a link never charges anyone.
*/
export class CreatePaymentBatch {
constructor(private readonly deps: BatchDeps = {}) {}
async execute(
groupId: string,
userId: string,
input: CreatePaymentsBatch,
): Promise<Result<CreatePaymentsBatchResult, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const group = await db.group.findUnique({
where: { id: groupId },
include: { members: { where: { userId } } },
});
if (!group) {
return err(notFoundResourceProblem('Group', groupId));
}
const isOwner = group.createdById === userId;
const isMember = group.members.length > 0;
if (!isOwner && !isMember) {
return err(noGroupAccessProblem());
}
if (group.price == null) {
return err(groupWithoutPriceProblem());
}
const attendees = await db.attendee.findMany({
where: {
groupId,
status: 'ACTIVE',
...(input.attendeeIds ? { id: { in: input.attendeeIds } } : {}),
},
});
if (attendees.length === 0) {
return err(noAttendeesToBillProblem());
}
const owner = await db.user.findUnique({ where: { id: group.createdById } });
const currency = currencyForCountry((owner?.country as CountryCode | null) ?? null);
const unitPrice = Number(group.price.toString());
const getToken = this.deps.getToken ?? getMpAccessToken;
const token = await getToken(group.createdById);
if (!token.ok) {
return token;
}
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
const dueDate = new Date(input.dueDate);
const title = input.description?.trim() || group.name;
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
const items: PaymentBatchItem[] = [];
let failed = 0;
for (const attendee of attendees) {
const payment = await db.payment.create({
data: {
groupId,
attendeeId: attendee.id,
amount: group.price,
currency,
dueDate,
description: input.description?.trim() || null,
status: 'PENDING',
},
});
let link: { initPoint: string; id: string } | null = null;
let reason: string | null = null;
try {
const preference = await createPreference(token.value.accessToken, {
title,
unitPrice,
currencyId: currency,
externalReference: payment.id,
backUrl,
});
link = preference;
} catch (error) {
failed += 1;
if (error instanceof MpApiError) {
reason = 'mp_provider_error';
} else {
// Never swallow a real bug: log it, but keep the rest of the batch going.
reason = 'unknown_error';
logger.error({ err: error }, 'Unexpected Mercado Pago preference failure');
}
}
if (link) {
await db.payment.update({
where: { id: payment.id },
data: { checkoutUrl: link.initPoint, mpPreferenceId: link.id },
});
}
items.push({
paymentId: payment.id,
attendeeId: attendee.id,
attendeeName: attendee.fullName,
amount: unitPrice,
currency,
checkoutUrl: link?.initPoint ?? null,
outcome: link ? 'LINKED' : 'FAILED',
reason,
});
}
return ok({
groupId,
total: attendees.length,
linked: attendees.length - failed,
failed,
items,
});
}
}

View File

@@ -1,16 +1,20 @@
import type { PaymentQuery } from '@gruperly/shared'; import type { PaymentQuery } from '@gruperly/shared';
import { PaymentQuerySchema } from '@gruperly/shared'; import { PaymentQuerySchema } from '@gruperly/shared';
import { Hono } from 'hono'; import { Hono } from 'hono';
import { resultJson } from '@/http/problem-details'; import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { validate } from '@/http/validate'; import { validate } from '@/http/validate';
import { ListPayments } from './use-case'; import { ListPayments } from './use-case';
const route = new Hono(); const route = new Hono();
route.get('/', validate.query(PaymentQuerySchema), async (c) => { route.get('/', validate.query(PaymentQuerySchema), async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const query = c.req.valid('query') as PaymentQuery; const query = c.req.valid('query') as PaymentQuery;
const useCase = new ListPayments(); const result = await new ListPayments().execute(query, user.id);
const result = await useCase.execute(query);
return resultJson(c, result); return resultJson(c, result);
}); });

View File

@@ -1,57 +1,52 @@
import type { PrismaClient } from '@generated/prisma/client'; import type { PrismaClient } from '@generated/prisma/client';
import type { PaymentDto, PaymentList, PaymentQuery, ProblemDetails, Result } from '@gruperly/shared'; import type { PaymentList, PaymentQuery, ProblemDetails, Result } from '@gruperly/shared';
import { ok } from '@gruperly/shared'; import { ok } from '@gruperly/shared';
import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination'; import { getPaginationMetadata, getPaginationOffset } from '@/lib/pagination';
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { buildGroupWhereForUser } from '@/modules/groups/lib';
import { type PaymentRecord, toPaymentDto } from '../../lib';
type ListPaymentsDeps = { type ListPaymentsDeps = {
db?: Pick<PrismaClient, 'payment'>; db?: Pick<PrismaClient, 'payment' | 'group'>;
}; };
type PaymentRecord = {
id: string;
groupId: string;
attendeeId: string;
amount: { toString(): string };
currency: string;
status: PaymentDto['status'];
dueDate: Date;
paidAt: Date | null;
createdAt: Date;
updatedAt: Date;
};
function toPaymentDto(record: PaymentRecord): PaymentDto {
return {
id: record.id,
groupId: record.groupId,
attendeeId: record.attendeeId,
amount: Number(record.amount.toString()),
currency: record.currency,
status: record.status,
dueDate: record.dueDate.toISOString(),
paidAt: record.paidAt ? record.paidAt.toISOString() : null,
createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(),
};
}
export class ListPayments { export class ListPayments {
constructor(private readonly deps: ListPaymentsDeps = {}) {} constructor(private readonly deps: ListPaymentsDeps = {}) {}
async execute(query: PaymentQuery): Promise<Result<PaymentList, ProblemDetails>> { async execute(
query: PaymentQuery,
userId: string,
): Promise<Result<PaymentList, ProblemDetails>> {
const db = this.deps.db ?? prisma; const db = this.deps.db ?? prisma;
// Only the professor's own groups (owner or member) are visible.
const accessibleGroups = await db.group.findMany({
where: buildGroupWhereForUser(userId),
select: { id: true },
});
const groupIds = accessibleGroups.map((group) => group.id);
const where = {
groupId: { in: groupIds },
...(query.groupId ? { groupId: query.groupId } : {}),
...(query.status ? { status: query.status } : {}),
};
const [records, total] = await Promise.all([ const [records, total] = await Promise.all([
db.payment.findMany({ db.payment.findMany({
where,
include: {
group: { select: { name: true, price: true } },
attendee: { select: { fullName: true } },
},
skip: getPaginationOffset(query), skip: getPaginationOffset(query),
take: query.pageSize, take: query.pageSize,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
}), }),
db.payment.count(), db.payment.count({ where }),
]); ]);
return ok({ return ok({
data: records.map(toPaymentDto), data: records.map((record) => toPaymentDto(record as unknown as PaymentRecord)),
pagination: getPaginationMetadata(query, total), pagination: getPaginationMetadata(query, total),
}); });
} }

View File

@@ -0,0 +1,19 @@
import { Hono } from 'hono';
import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
import { RenewPaymentLink } from './use-case';
const route = new Hono();
route.post('/:id/renew', async (c) => {
const user = c.get('user');
if (!user) {
return problemJson(c, unauthorizedProblem(c.req.path));
}
const paymentId = c.req.param('id');
const result = await new RenewPaymentLink().execute(paymentId, user.id);
return resultJson(c, result);
});
export default route;

View File

@@ -0,0 +1,106 @@
import type { PrismaClient } from '@generated/prisma/client';
import type { CountryCode, PaymentDto, ProblemDetails, Result } from '@gruperly/shared';
import { currencyForCountry, err, ok } from '@gruperly/shared';
import {
groupWithoutPriceProblem,
mpProviderErrorProblem,
noGroupAccessProblem,
notFoundResourceProblem,
} from '@/http/problem-builders';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getMpAccessToken } from '@/modules/mp';
import { createCheckoutPreference, getWebOrigin } from '@/modules/mp/lib';
import { type PaymentRecord, toPaymentDto } from '../../lib';
type RenewDeps = {
db?: Pick<PrismaClient, 'payment' | 'user'>;
createPreference?: typeof createCheckoutPreference;
getToken?: typeof getMpAccessToken;
webOrigin?: string;
};
/**
* Re-creates the Checkout Pro link of a payment that lost it (a failed batch
* item). Idempotent: a payment that already has a link keeps it.
*/
export class RenewPaymentLink {
constructor(private readonly deps: RenewDeps = {}) {}
async execute(paymentId: string, userId: string): Promise<Result<PaymentDto, ProblemDetails>> {
const db = this.deps.db ?? prisma;
const payment = await db.payment.findUnique({
where: { id: paymentId },
include: {
attendee: { select: { fullName: true } },
group: {
select: {
name: true,
price: true,
createdById: true,
members: { where: { userId } },
},
},
},
});
if (!payment) {
return err(notFoundResourceProblem('Payment', paymentId));
}
const isOwner = payment.group.createdById === userId;
const isMember = payment.group.members.length > 0;
if (!isOwner && !isMember) {
return err(noGroupAccessProblem());
}
if (payment.checkoutUrl) {
return ok(toPaymentDto(payment as unknown as PaymentRecord));
}
if (payment.group.price == null) {
return err(groupWithoutPriceProblem());
}
const owner = await db.user.findUnique({ where: { id: payment.group.createdById } });
const currency = currencyForCountry((owner?.country as CountryCode | null) ?? null);
const unitPrice = Number(payment.amount.toString());
const getToken = this.deps.getToken ?? getMpAccessToken;
const token = await getToken(payment.group.createdById);
if (!token.ok) {
return token;
}
const backUrl = `${this.deps.webOrigin ?? getWebOrigin()}/payments`;
const createPreference = this.deps.createPreference ?? createCheckoutPreference;
let preference: { initPoint: string; id: string };
try {
preference = await createPreference(token.value.accessToken, {
title: payment.description ?? payment.group.name,
unitPrice,
currencyId: currency,
externalReference: payment.id,
backUrl,
});
} catch (error) {
if (error instanceof Error) {
logger.error({ err: error }, 'Mercado Pago preference renew failed');
}
return err(mpProviderErrorProblem());
}
const updated = await db.payment.update({
where: { id: payment.id },
data: { checkoutUrl: preference.initPoint, mpPreferenceId: preference.id },
include: {
attendee: { select: { fullName: true } },
group: { select: { name: true, price: true } },
},
});
return ok(toPaymentDto(updated as unknown as PaymentRecord));
}
}

View File

@@ -1 +1,2 @@
export { startPaymentJobs } from './jobs';
export { default as paymentsRoutes } from './routes'; export { default as paymentsRoutes } from './routes';

View File

@@ -0,0 +1,9 @@
export {
MarkOverduePayments,
type MarkOverduePaymentsResult,
} from './mark-overdue-payments';
export {
ReconcilePayments,
type ReconcilePaymentsResult,
} from './reconcile-payments';
export { startPaymentJobs } from './schedule';

View File

@@ -0,0 +1,35 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
/**
* Marks overdue rows. A payment whose due date (plus a day of grace) passed and
* is still PENDING becomes OVERDUE; it stays billable, so the professor can
* renew its link from Cobros.
*/
const GRACE_MS = 24 * 60 * 60 * 1000;
export type MarkOverduePaymentsResult = {
marked: number;
};
type MarkOverduePaymentsDeps = {
db?: PrismaClient;
now?: Date;
};
export class MarkOverduePayments {
constructor(private readonly deps: MarkOverduePaymentsDeps = {}) {}
async execute(): Promise<MarkOverduePaymentsResult> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const horizon = new Date(now.getTime() - GRACE_MS);
const updated = await db.payment.updateMany({
where: { status: 'PENDING', dueDate: { lt: horizon } },
data: { status: 'OVERDUE' },
});
return { marked: updated.count };
}
}

View File

@@ -0,0 +1,87 @@
import type { PrismaClient } from '@generated/prisma/client';
import prisma from '@/lib/prisma';
import { logger } from '@/logger';
import { getMpAccessToken } from '@/modules/mp';
import { MpApiError, searchMpPaymentByExternalReference } from '@/modules/mp/lib';
/**
* Pulls payments from Mercado Pago instead of trusting a webhook. A payment
* link is just a preference until someone pays it; this job asks the seller's
* account for our `external_reference` and marks approved payments as PAID.
*
* This is the stopgap and the source of truth: if a webhook is ever added it
* gives you the confirmation, but this job is what keeps the Cobros screen
* correct even when a notification is lost.
*/
const RECONCILE_AFTER_MS = 5 * 60 * 1000;
const BATCH_LIMIT = 50;
export type ReconcilePaymentsResult = {
paid: number;
skipped: number;
failed: number;
};
type ReconcilePaymentsDeps = {
db?: PrismaClient;
getToken?: typeof getMpAccessToken;
search?: typeof searchMpPaymentByExternalReference;
now?: Date;
};
export class ReconcilePayments {
constructor(private readonly deps: ReconcilePaymentsDeps = {}) {}
async execute(): Promise<ReconcilePaymentsResult> {
const db = this.deps.db ?? prisma;
const now = this.deps.now ?? new Date();
const getToken = this.deps.getToken ?? getMpAccessToken;
const search = this.deps.search ?? searchMpPaymentByExternalReference;
const awaiting = await db.payment.findMany({
where: {
status: 'PENDING',
checkoutUrl: { not: null },
createdAt: { lt: new Date(now.getTime() - RECONCILE_AFTER_MS) },
},
include: { group: { select: { createdById: true } } },
take: BATCH_LIMIT,
});
const totals: ReconcilePaymentsResult = { paid: 0, skipped: 0, failed: 0 };
for (const payment of awaiting) {
const token = await getToken(payment.group.createdById);
if (!token.ok) {
// No usable token (not linked, or needs re-auth). Not a payment problem:
// the row stays PENDING and the account notice tells the professor what to do.
totals.skipped += 1;
continue;
}
try {
const found = await search(token.value.accessToken, payment.id);
if (found && found.status === 'approved' && found.externalReference === payment.id) {
await db.payment.update({
where: { id: payment.id },
data: {
status: 'PAID',
mpPaymentId: found.id,
paidAt: found.dateApproved ? new Date(found.dateApproved) : new Date(),
},
});
totals.paid += 1;
}
} catch (error) {
if (error instanceof MpApiError) {
totals.failed += 1;
} else {
logger.error({ err: error }, 'Unexpected payment reconciliation failure');
totals.failed += 1;
}
}
}
return totals;
}
}

View File

@@ -0,0 +1,40 @@
import { logger } from '@/logger';
import { MarkOverduePayments } from './mark-overdue-payments';
import { ReconcilePayments } from './reconcile-payments';
const RECONCILE_CRON = '*/15 * * * *';
const OVERDUE_CRON = '4 4 * * *';
/**
* Registers the payment background jobs. Called once from `server.ts`, following
* the same guards as `startMpJobs`: Bun's in-process cron treats a rejected
* promise as an unhandledRejection (which would crash the process), and `unref`
* keeps the jobs from holding the process alive on their own.
*/
export function startPaymentJobs(): void {
Bun.cron(
RECONCILE_CRON,
async () => {
try {
const totals = await new ReconcilePayments().execute();
logger.info(totals, 'Mercado Pago payments reconciliation finished');
} catch (error) {
logger.error({ err: error }, 'Mercado Pago payments reconciliation failed');
}
},
{ tz: 'UTC' },
).unref();
Bun.cron(
OVERDUE_CRON,
async () => {
try {
const totals = await new MarkOverduePayments().execute();
logger.info(totals, 'Overdue payments marked');
} catch (error) {
logger.error({ err: error }, 'Marking overdue payments failed');
}
},
{ tz: 'UTC' },
).unref();
}

View File

@@ -0,0 +1,37 @@
import type { PaymentDto } from '@gruperly/shared';
export type PaymentRecord = {
id: string;
groupId: string;
attendeeId: string;
amount: { toString(): string } | number;
currency: string;
status: PaymentDto['status'];
description: string | null;
checkoutUrl: string | null;
dueDate: Date;
paidAt: Date | null;
createdAt: Date;
updatedAt: Date;
group: { name: string; price: unknown };
attendee: { fullName: string };
};
export function toPaymentDto(record: PaymentRecord): PaymentDto {
return {
id: record.id,
groupId: record.groupId,
groupName: record.group.name,
attendeeId: record.attendeeId,
attendeeName: record.attendee.fullName,
amount: Number(record.amount.toString()),
currency: record.currency,
status: record.status,
description: record.description,
checkoutUrl: record.checkoutUrl,
dueDate: record.dueDate.toISOString(),
paidAt: record.paidAt ? record.paidAt.toISOString() : null,
createdAt: record.createdAt.toISOString(),
updatedAt: record.updatedAt.toISOString(),
};
}

View File

@@ -0,0 +1 @@
export { type PaymentRecord, toPaymentDto } from './helpers';

View File

@@ -1,8 +1,10 @@
import { Hono } from 'hono'; import { Hono } from 'hono';
import getAllRoute from './features/get-all/route'; import getAllRoute from './features/get-all/route';
import renewRoute from './features/renew/route';
const routes = new Hono(); const routes = new Hono();
routes.route('/', getAllRoute); routes.route('/', getAllRoute);
routes.route('/', renewRoute);
export default routes; export default routes;

View File

@@ -2,6 +2,7 @@ import app from '@/app';
import { getPrismaClient } from '@/lib/prisma'; import { getPrismaClient } from '@/lib/prisma';
import { logger } from '@/logger'; import { logger } from '@/logger';
import { startMpJobs } from '@/modules/mp'; import { startMpJobs } from '@/modules/mp';
import { startPaymentJobs } from '@/modules/payments';
const port = Number(process.env.PORT ?? 4000); const port = Number(process.env.PORT ?? 4000);
@@ -13,6 +14,7 @@ const server = Bun.serve({
}); });
startMpJobs(); startMpJobs();
startPaymentJobs();
async function shutdown(): Promise<void> { async function shutdown(): Promise<void> {
server.stop(true); server.stop(true);

View File

@@ -64,6 +64,7 @@ const firstGroupPayload = {
price: group.price, price: group.price,
billingType: group.billingType, billingType: group.billingType,
dueDay: group.dueDay, dueDay: group.dueDay,
country: 'AR',
}; };
describe('onboarding routes', () => { describe('onboarding routes', () => {
@@ -185,7 +186,7 @@ describe('onboarding routes', () => {
}); });
expect(prisma.user.update).toHaveBeenCalledWith({ expect(prisma.user.update).toHaveBeenCalledWith({
where: { id: userId }, where: { id: userId },
data: { onboardingCompleted: true }, data: { onboardingCompleted: true, country: 'AR' },
}); });
}); });

View File

@@ -0,0 +1,247 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
mpAccount: {
findUnique: mock(),
},
group: {
findUnique: mock(),
},
attendee: {
findMany: mock(),
},
payment: {
create: mock(),
update: mock(),
},
user: {
findUnique: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}));
import prisma from '@/lib/prisma';
import { groupsRoutes } from '@/modules/groups';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
import { CreatePaymentBatch } from '@/modules/payments/features/create-batch/use-case';
const userId = 'user-1';
const webOrigin = 'http://localhost:6173';
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/groups', groupsRoutes);
return app;
}
function okAccount() {
return {
ok: true,
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
};
}
const groupOwner = {
id: 'group-1',
name: 'Vinyasa',
createdById: userId,
price: { toString: () => '120.00' } as { toString(): string },
members: [],
};
let getToken: ReturnType<typeof mock>;
let createPreference: ReturnType<typeof mock>;
function batchUseCase() {
getToken = mock(async () => okAccount());
createPreference = mock(async () => ({
id: 'pref-1',
initPoint: 'https://mp.link/pay-1',
sandboxInitPoint: null,
}));
return new CreatePaymentBatch({ getToken, createPreference, webOrigin });
}
describe('create payments batch', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('creates one link per active attendee; keeps going when one preference fails', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([
{ id: 'att-1', fullName: 'Juana' },
{ id: 'att-2', fullName: 'Pedro' },
]);
prisma.payment.create
.mockResolvedValueOnce({ id: 'pay-1' })
.mockResolvedValueOnce({ id: 'pay-2' });
const useCase = batchUseCase();
createPreference.mockResolvedValueOnce({
id: 'pref-1',
initPoint: 'https://mp.link/pay-1',
sandboxInitPoint: null,
});
createPreference.mockRejectedValue(new MpApiError(502, 'bad_gateway'));
const result = await useCase.execute('group-1', userId, {
dueDate: '2026-10-05T12:00:00.000Z',
description: 'Octubre',
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error('expected ok');
expect(result.value).toEqual({
groupId: 'group-1',
total: 2,
linked: 1,
failed: 1,
items: [
{
paymentId: 'pay-1',
attendeeId: 'att-1',
attendeeName: 'Juana',
amount: 120,
currency: 'ARS',
checkoutUrl: 'https://mp.link/pay-1',
outcome: 'LINKED',
reason: null,
},
{
paymentId: 'pay-2',
attendeeId: 'att-2',
attendeeName: 'Pedro',
amount: 120,
currency: 'ARS',
checkoutUrl: null,
outcome: 'FAILED',
reason: 'mp_provider_error',
},
],
});
expect(prisma.payment.create).toHaveBeenCalledTimes(2);
expect(prisma.payment.update).toHaveBeenCalledTimes(1);
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-1' },
});
expect(createPreference).toHaveBeenNthCalledWith(1, 'token-1', {
title: 'Octubre',
unitPrice: 120,
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/payments`,
});
});
it('derives the currency from the owner country and defaults when there is none', async () => {
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: { toString: () => '80.00' } });
prisma.user.findUnique.mockResolvedValue({ id: userId, country: null });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-2', fullName: 'Pedro' }]);
prisma.payment.create.mockResolvedValueOnce({ id: 'pay-2' });
const useCase = batchUseCase();
createPreference.mockResolvedValueOnce({
id: 'pref-2',
initPoint: 'https://mp.link/pay-2',
sandboxInitPoint: null,
});
const result = await useCase.execute('group-1', userId, {
dueDate: '2026-10-05T12:00:00.000Z',
attendeeIds: ['att-2'],
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error('expected ok');
expect(result.value.items).toHaveLength(1);
expect(result.value.items[0]).toMatchObject({ attendeeId: 'att-2', currency: 'ARS' });
expect(prisma.attendee.findMany).toHaveBeenCalledWith({
where: { groupId: 'group-1', status: 'ACTIVE', id: { in: ['att-2'] } },
});
});
it('propagates the not-connected problem and creates no rows', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
getToken = mock(async () => ({
ok: false,
error: {
type: 'https://gruperly.app/problems/conflict',
title: 'Conflict',
status: 409,
detail: 'No tenés una cuenta de Mercado Pago vinculada.',
code: 'mp_not_connected',
},
}));
const createPreference = mock(async () => {
throw new Error('should not be called');
});
const result = await new CreatePaymentBatch({ getToken, createPreference, webOrigin }).execute(
'group-1',
userId,
{ dueDate: '2026-10-05T12:00:00.000Z' },
);
expect(result.ok).toBe(false);
expect(prisma.payment.create).not.toHaveBeenCalled();
});
it('answers 409 over HTTP when the owner has no linked account', async () => {
prisma.group.findUnique.mockResolvedValue(groupOwner);
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.attendee.findMany.mockResolvedValue([{ id: 'att-1', fullName: 'Juana' }]);
prisma.mpAccount.findUnique.mockResolvedValue(null);
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
});
expect(res.status).toBe(409);
expect(prisma.payment.create).not.toHaveBeenCalled();
});
it('rejects a group without price', async () => {
prisma.group.findUnique.mockResolvedValue({ ...groupOwner, price: null });
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
});
expect(res.status).toBe(409);
expect(prisma.attendee.findMany).not.toHaveBeenCalled();
});
it('rejects a group the user has no access to', async () => {
prisma.group.findUnique.mockResolvedValue({
...groupOwner,
createdById: 'someone-else',
members: [],
});
const res = await makeApp({ id: userId }).request('/groups/group-1/payments/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dueDate: '2026-10-05T12:00:00.000Z' }),
});
expect(res.status).toBe(403);
});
});

View File

@@ -0,0 +1,43 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
const db = {
payment: {
updateMany: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}));
import prisma from '@/lib/prisma';
import { MarkOverduePayments } from '@/modules/payments/jobs';
describe('mark overdue payments', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('marks PENDING payments whose due date passed more than a day ago', async () => {
prisma.payment.updateMany.mockResolvedValue({ count: 3 });
const now = new Date('2026-10-08T12:00:00.000Z');
const result = await new MarkOverduePayments({ now }).execute();
expect(result).toEqual({ marked: 3 });
expect(prisma.payment.updateMany).toHaveBeenCalledWith({
where: { status: 'PENDING', dueDate: { lt: new Date('2026-10-07T12:00:00.000Z') } },
data: { status: 'OVERDUE' },
});
});
it('leaves payments inside the grace period alone', async () => {
prisma.payment.updateMany.mockResolvedValue({ count: 0 });
const result = await new MarkOverduePayments({ now: new Date() }).execute();
expect(result).toEqual({ marked: 0 });
});
});

View File

@@ -0,0 +1,129 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
const db = {
payment: {
findMany: mock(),
update: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}));
import prisma from '@/lib/prisma';
import { MpApiError } from '@/modules/mp/lib/mp-oauth';
import { ReconcilePayments } from '@/modules/payments/jobs';
const ownerId = 'user-1';
const pendingPayment = (id: string, overrides: Record<string, unknown> = {}) => ({
id,
groupId: 'group-1',
status: 'PENDING',
checkoutUrl: 'https://mp.link/pay',
createdAt: new Date(Date.now() - 10 * 60 * 1000),
group: { createdById: ownerId },
...overrides,
});
function okAccount() {
return {
ok: true,
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
};
}
describe('reconcile payments', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('marks an approved Mercado Pago payment as PAID', async () => {
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
const getToken = mock(async () => okAccount());
const search = mock(async () => ({
id: '999999999',
status: 'approved',
externalReference: 'pay-1',
liveMode: true,
dateApproved: '2026-10-01T12:30:00.000Z',
}));
const result = await new ReconcilePayments({ getToken, search }).execute();
expect(result).toEqual({ paid: 1, skipped: 0, failed: 0 });
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: {
status: 'PAID',
mpPaymentId: '999999999',
paidAt: new Date('2026-10-01T12:30:00.000Z'),
},
});
});
it('skips a payment that is still pending in Mercado Pago', async () => {
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
const getToken = mock(async () => okAccount());
const search = mock(async () => ({
id: '999999999',
status: 'pending',
externalReference: 'pay-1',
liveMode: true,
dateApproved: null,
}));
const result = await new ReconcilePayments({ getToken, search }).execute();
expect(result).toEqual({ paid: 0, skipped: 0, failed: 0 });
expect(prisma.payment.update).not.toHaveBeenCalled();
});
it('skips rows when the owner has no usable token', async () => {
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
const getToken = mock(async () => ({
ok: false,
error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' },
}));
const search = mock(async () => {
throw new Error('should not be called');
});
const result = await new ReconcilePayments({ getToken, search }).execute();
expect(result).toEqual({ paid: 0, skipped: 1, failed: 0 });
expect(search).not.toHaveBeenCalled();
});
it('counts an unreachable Mercado Pago as failed and leaves the row pending', async () => {
prisma.payment.findMany.mockResolvedValue([pendingPayment('pay-1')]);
const getToken = mock(async () => okAccount());
const search = mock(async () => {
throw new MpApiError(0, null);
});
const result = await new ReconcilePayments({ getToken, search }).execute();
expect(result).toEqual({ paid: 0, skipped: 0, failed: 1 });
expect(prisma.payment.update).not.toHaveBeenCalled();
});
it('only reconciles payments linked for at least five minutes', async () => {
prisma.payment.findMany.mockResolvedValue([]);
const now = new Date('2026-10-01T12:00:00.000Z');
await new ReconcilePayments({ now }).execute();
expect(prisma.payment.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
status: 'PENDING',
checkoutUrl: { not: null },
createdAt: { lt: new Date('2026-10-01T11:55:00.000Z') },
},
}),
);
});
});

View File

@@ -0,0 +1,158 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono';
const db = {
payment: {
findUnique: mock(),
update: mock(),
},
user: {
findUnique: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(),
UnitOfWork: class {},
}));
import prisma from '@/lib/prisma';
import { paymentsRoutes } from '@/modules/payments';
import { RenewPaymentLink } from '@/modules/payments/features/renew/use-case';
const userId = 'user-1';
const webOrigin = 'http://localhost:6173';
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/payments', paymentsRoutes);
return app;
}
function paymentWithoutLink(overrides: Record<string, unknown> = {}) {
return {
id: 'pay-1',
groupId: 'group-1',
attendeeId: 'att-1',
amount: { toString: () => '120.00' } as { toString(): string },
currency: 'ARS',
status: 'PENDING',
description: null,
checkoutUrl: null,
mpPreferenceId: null,
dueDate: new Date('2026-10-05T12:00:00.000Z'),
paidAt: null,
createdAt: new Date('2026-10-01T10:00:00.000Z'),
updatedAt: new Date('2026-10-01T10:00:00.000Z'),
attendee: { fullName: 'Juana Pérez' },
group: {
name: 'Vinyasa',
price: { toString: () => '120.00' },
createdById: userId,
members: [],
},
...overrides,
};
}
describe('renew payment link', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('creates a new link for a payment that lost it and returns the payment', async () => {
prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink());
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
prisma.payment.update.mockResolvedValue({
...paymentWithoutLink(),
checkoutUrl: 'https://mp.link/pay-1',
group: { name: 'Vinyasa', price: { toString: () => '120.00' } },
});
const getToken = mock(async () => ({
ok: true,
value: { accountId: 'acc-1', accessToken: 'token-1', expiresAt: new Date() },
}));
const createPreference = mock(async () => ({
id: 'pref-new',
initPoint: 'https://mp.link/pay-1',
sandboxInitPoint: null,
}));
const result = await new RenewPaymentLink({ getToken, createPreference, webOrigin }).execute(
'pay-1',
userId,
);
expect(result.ok).toBe(true);
if (!result.ok) throw new Error('expected ok');
expect(result.value).toMatchObject({
id: 'pay-1',
groupName: 'Vinyasa',
attendeeName: 'Juana Pérez',
checkoutUrl: 'https://mp.link/pay-1',
});
expect(createPreference).toHaveBeenCalledWith('token-1', {
title: 'Vinyasa',
unitPrice: 120,
currencyId: 'ARS',
externalReference: 'pay-1',
backUrl: `${webOrigin}/payments`,
});
expect(prisma.payment.update).toHaveBeenCalledWith({
where: { id: 'pay-1' },
data: { checkoutUrl: 'https://mp.link/pay-1', mpPreferenceId: 'pref-new' },
include: {
attendee: { select: { fullName: true } },
group: { select: { name: true, price: true } },
},
});
});
it('keeps an existing link: idempotent, no Mercado Pago call', async () => {
prisma.payment.findUnique.mockResolvedValue(
paymentWithoutLink({ checkoutUrl: 'https://mp.link/pay-1' }),
);
const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' });
expect(res.status).toBe(200);
expect(prisma.payment.update).not.toHaveBeenCalled();
});
it('answers 409 when the owner has no linked account', async () => {
prisma.payment.findUnique.mockResolvedValue(paymentWithoutLink());
prisma.user.findUnique.mockResolvedValue({ id: userId, country: 'AR' });
const getToken = mock(async () => ({
ok: false,
error: { type: 'x', title: 'Conflict', status: 409, detail: 'x', code: 'mp_not_connected' },
}));
const result = await new RenewPaymentLink({ getToken }).execute('pay-1', userId);
expect(result.ok).toBe(false);
expect(prisma.payment.update).not.toHaveBeenCalled();
});
it('rejects a payment of a group the user has no access to', async () => {
prisma.payment.findUnique.mockResolvedValue(
paymentWithoutLink({
group: {
name: 'Vinyasa',
price: { toString: () => '120.00' },
createdById: 'someone-else',
members: [],
},
}),
);
const res = await makeApp({ id: userId }).request('/payments/pay-1/renew', { method: 'POST' });
expect(res.status).toBe(403);
expect(prisma.payment.update).not.toHaveBeenCalled();
});
});

View File

@@ -1,13 +1,18 @@
import { beforeEach, describe, expect, it, mock, vi } from 'bun:test'; import { beforeEach, describe, expect, it, mock, vi } from 'bun:test';
import { Hono } from 'hono'; import { Hono } from 'hono';
mock.module('@/lib/prisma', () => ({ const db = {
default: { group: {
payment: { findMany: mock(),
findMany: mock(),
count: mock(),
},
}, },
payment: {
findMany: mock(),
count: mock(),
},
};
mock.module('@/lib/prisma', () => ({
default: db,
getPrismaClient: mock(), getPrismaClient: mock(),
UnitOfWork: class {}, UnitOfWork: class {},
})); }));
@@ -15,43 +20,61 @@ mock.module('@/lib/prisma', () => ({
import prisma from '@/lib/prisma'; import prisma from '@/lib/prisma';
import { paymentsRoutes } from '@/modules/payments'; import { paymentsRoutes } from '@/modules/payments';
const app = new Hono(); const userId = 'user-1';
app.route('/payments', paymentsRoutes);
const payment = { const payment = {
id: 'payment-1', id: 'payment-1',
groupId: 'group-1', groupId: 'group-1',
attendeeId: 'attendee-1', attendeeId: 'attendee-1',
amount: { toString: () => '150.50' } as { toString(): string }, amount: { toString: () => '150.50' } as { toString(): string },
currency: 'MXN', currency: 'ARS',
status: 'pending', status: 'PENDING',
description: 'Mensualidad de Septiembre',
checkoutUrl: 'https://mercadopago.com/checkout/payment-1',
dueDate: new Date('2026-09-01T10:00:00.000Z'), dueDate: new Date('2026-09-01T10:00:00.000Z'),
paidAt: null, paidAt: null,
createdAt: new Date('2026-08-01T10:00:00.000Z'), createdAt: new Date('2026-08-01T10:00:00.000Z'),
updatedAt: new Date('2026-08-01T10:00:00.000Z'), updatedAt: new Date('2026-08-01T10:00:00.000Z'),
group: { name: 'Cuadrilla Alfa', price: 150.5 },
attendee: { fullName: 'Juana Pérez' },
}; };
function makeApp(userValue: unknown) {
const app = new Hono();
app.use('*', async (c, next) => {
c.set('user', userValue as never);
await next();
});
app.route('/payments', paymentsRoutes);
return app;
}
describe('payments routes', () => { describe('payments routes', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
it('lists payments with pagination and converts Decimal amounts', async () => { it('lists payments scoped to the user, with attendee and group names', async () => {
prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]);
prisma.payment.findMany.mockResolvedValue([payment]); prisma.payment.findMany.mockResolvedValue([payment]);
prisma.payment.count.mockResolvedValue(1); prisma.payment.count.mockResolvedValue(1);
const res = await app.request('/payments'); const res = await makeApp({ id: userId }).request('/payments');
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(await res.json()).toEqual({ expect(await res.json()).toEqual({
data: [ data: [
{ {
id: 'payment-1', id: 'payment-1',
groupId: 'group-1', groupId: 'group-1',
attendeeId: 'attendee-1', groupName: 'Cuadrilla Alfa',
attendeeId: 'attendee-1',
attendeeName: 'Juana Pérez',
amount: 150.5, amount: 150.5,
currency: 'MXN', currency: 'ARS',
status: 'pending', status: 'PENDING',
description: 'Mensualidad de Septiembre',
checkoutUrl: payment.checkoutUrl,
dueDate: payment.dueDate.toISOString(), dueDate: payment.dueDate.toISOString(),
paidAt: null, paidAt: null,
createdAt: payment.createdAt.toISOString(), createdAt: payment.createdAt.toISOString(),
@@ -60,15 +83,49 @@ groupId: 'group-1',
], ],
pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 }, pagination: { page: 1, pageSize: 10, total: 1, totalPages: 1 },
}); });
expect(prisma.group.findMany).toHaveBeenCalledWith({
where: {
OR: [{ createdById: userId }, { members: { some: { userId } } }],
},
select: { id: true },
});
expect(prisma.payment.findMany).toHaveBeenCalledWith({ expect(prisma.payment.findMany).toHaveBeenCalledWith({
where: { groupId: { in: ['group-1'] } },
include: {
group: { select: { name: true, price: true } },
attendee: { select: { fullName: true } },
},
skip: 0, skip: 0,
take: 10, take: 10,
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
}); });
}); });
it('filters payments by group and status', async () => {
prisma.group.findMany.mockResolvedValue([{ id: 'group-1' }]);
prisma.payment.findMany.mockResolvedValue([]);
prisma.payment.count.mockResolvedValue(0);
const res = await makeApp({ id: userId }).request(
'/payments?groupId=group-1&status=OVERDUE',
);
expect(res.status).toBe(200);
expect(prisma.payment.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { groupId: 'group-1', status: 'OVERDUE' },
}),
);
});
it('rejects requests without a session user', async () => {
const res = await makeApp(null).request('/payments');
expect(res.status).toBe(401);
});
it('rejects invalid pagination query parameters', async () => { it('rejects invalid pagination query parameters', async () => {
const res = await app.request('/payments?pageSize=101'); const res = await makeApp({ id: userId }).request('/payments?pageSize=101');
expect(res.status).toBe(400); expect(res.status).toBe(400);
}); });

View File

@@ -1,28 +1,20 @@
import { useForm } from 'react-hook-form' import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from '@hookform/resolvers/zod'
import type { BillingType, CreateFirstGroup, WeekDay } from '@gruperly/shared' import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
import { CreateFirstGroupSchema } from '@gruperly/shared' import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
import { ArrowLeft, Check, Loader2 } from 'lucide-react' import { ArrowLeft, Check, Loader2 } from 'lucide-react'
import { cn } from '../../lib/utils' import { cn } from '../../lib/utils'
import { Button, Input, Label } from '../../components/ui' import { Button, Input, Label } from '../../components/ui'
import { BILLING_TYPES, WEEK_DAY_CHIPS } from '../onboarding/constants' import { BILLING_TYPES, WEEK_DAY_CHIPS } from '../onboarding/constants'
const defaultValues: CreateFirstGroup = {
name: '',
days: [],
time: '09:00',
capacity: 1,
price: 0,
billingType: 'MONTHLY',
dueDay: 1,
}
type GroupFormProps = { type GroupFormProps = {
heading: string heading: string
description: string description: string
submitLabel: string submitLabel: string
isSubmitting: boolean isSubmitting: boolean
errorMessage?: string | null errorMessage?: string | null
/** Solo lo usa el onboarding: ahí el país ya se eligió en el paso anterior. */
country?: CountryCode
onSubmit: (values: CreateFirstGroup) => void onSubmit: (values: CreateFirstGroup) => void
onBack?: () => void onBack?: () => void
} }
@@ -33,9 +25,21 @@ export function GroupForm({
submitLabel, submitLabel,
isSubmitting, isSubmitting,
errorMessage, errorMessage,
country = DEFAULT_COUNTRY,
onSubmit, onSubmit,
onBack, onBack,
}: GroupFormProps) { }: GroupFormProps) {
const defaultValues: CreateFirstGroup = {
name: '',
days: [],
time: '09:00',
capacity: 1,
price: 0,
billingType: 'MONTHLY',
dueDay: 1,
country,
}
const { const {
register, register,
handleSubmit, handleSubmit,

View File

@@ -0,0 +1,264 @@
import type { CreatePaymentsBatchResult, PaymentBatchItem } from '@gruperly/shared'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Check, Copy, Loader2, TriangleAlert, Wallet } from 'lucide-react'
import { useEffect, useState } from 'react'
import { Badge, Button, Input, Label, Modal } from '../../../components/ui'
import { ApiError, createPaymentsBatch } from '../../../lib/api'
import { formatPrice } from '../../../lib/format'
import { mpStatusBadgeVariant, mpStatusLabel, useMpStatus } from '../../mp'
import { useGroupDetail } from './GroupDetailProvider'
type ChargeMembersModalProps = {
isOpen: boolean
onClose: () => void
}
/** El payload viaja en el día local del profesor, no en la UTC del servidor. */
function localDateValue(date: Date): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
function monthLabel(date: Date): string {
return date.toLocaleDateString('es-MX', { month: 'long', year: 'numeric' })
}
function defaultDueDate(): Date {
const now = new Date()
return new Date(now.getFullYear(), now.getMonth() + 1, 1)
}
type LinkRowProps = {
item: PaymentBatchItem
copiedId: string | null
onCopy: (id: string) => void
}
function LinkRow({ item, copiedId, onCopy }: LinkRowProps) {
if (item.outcome !== 'LINKED' || !item.checkoutUrl) {
return (
<li className="flex items-center justify-between gap-3 rounded-lg bg-primary-soft px-3 py-2.5">
<span className="min-w-0 truncate text-sm text-primary">{item.attendeeName}</span>
<Badge variant="danger">No se generó</Badge>
</li>
)
}
const copied = copiedId === item.paymentId
return (
<li className="flex items-center justify-between gap-3 rounded-lg bg-primary-soft px-3 py-2.5">
<span className="min-w-0 truncate text-sm text-primary">{item.attendeeName}</span>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onCopy(item.paymentId!)}
className="shrink-0 gap-1.5"
>
{copied ? (
<Check className="size-3.5 text-success" />
) : (
<Copy className="size-3.5 text-accent" />
)}
{copied ? 'Copiado' : 'Copiar link'}
</Button>
</li>
)
}
/**
* "Cobrar" de una ficha de grupo: crea un link de pago por miembro activo para
* un período (Checkout Pro). Crear links no cobra a nadie: el profesor los
* reenvía y los pagos entran directo a su cuenta de Mercado Pago.
*/
export function ChargeMembersModal({ isOpen, onClose }: ChargeMembersModalProps) {
const { group } = useGroupDetail()
const navigate = useNavigate()
const queryClient = useQueryClient()
const statusQuery = useMpStatus()
const [dueDate, setDueDate] = useState(() => localDateValue(defaultDueDate()))
const [description, setDescription] = useState(() =>
monthLabel(defaultDueDate()).replace(/^./, (ch) => ch.toUpperCase()),
)
const [submissionError, setSubmissionError] = useState<string | null>(null)
const [result, setResult] = useState<CreatePaymentsBatchResult | null>(null)
const [copiedId, setCopiedId] = useState<string | null>(null)
useEffect(() => {
if (isOpen) {
setSubmissionError(null)
setResult(null)
setCopiedId(null)
}
}, [isOpen])
const create = useMutation({
mutationFn: () =>
createPaymentsBatch(group!.id, {
dueDate: new Date(`${dueDate}T12:00:00.000Z`).toISOString(),
description: description.trim() || undefined,
}),
onSuccess: (payload) => {
setResult(payload)
void queryClient.invalidateQueries({ queryKey: ['payments'] })
},
onError: (error: unknown) => {
if (error instanceof ApiError) {
setSubmissionError(
error.problem?.code === 'mp_not_connected'
? 'Tu cuenta de Mercado Pago no está vinculada.'
: error.problem?.code === 'group_without_price'
? 'Este grupo todavía no tiene precio.'
: error.problem?.code === 'no_attendees_to_bill'
? 'No hay miembros activos para cobrar.'
: (error.problem?.detail ?? error.problem?.title ?? 'No pudimos crear los cobros.'),
)
} else {
setSubmissionError('No pudimos crear los cobros.')
}
},
})
if (!isOpen) return null
const status = statusQuery.data?.status ?? 'none'
const isConnected = status === 'active'
const price = group?.price ?? null
const copyItemLink = (paymentId: string) => {
const item = result?.items.find((candidate) => candidate.paymentId === paymentId)
if (!item?.checkoutUrl) return
void navigator.clipboard.writeText(item.checkoutUrl).then(() => {
setCopiedId(paymentId)
window.setTimeout(() => setCopiedId(null), 1500)
})
}
return (
<Modal
isOpen={isOpen}
onClose={onClose}
title="Cobrar período"
description={group?.name ? `Links de pago para ${group.name}` : undefined}
maxWidth="md"
>
{!isConnected ? (
<div className="space-y-4">
<Badge variant={mpStatusBadgeVariant(status)}>{mpStatusLabel(status)}</Badge>
<p className="flex items-start gap-2 rounded-xl bg-warning-soft px-4 py-3 text-sm text-warning">
<TriangleAlert className="mt-0.5 size-4 shrink-0" />
Para crear links de pago primero vinculá tu cuenta de Mercado Pago.
</p>
<Button
variant="primary"
className="w-full"
onClick={() => void navigate({ to: '/settings' })}
>
Conectar Mercado Pago
</Button>
</div>
) : result ? (
<div className="space-y-5">
<p className="flex items-center gap-2 text-sm text-primary">
<Wallet className="size-4 text-accent" />
{result.linked} de {result.total} links creados
</p>
<ul className="space-y-2">
{result.items.map((item) => (
<LinkRow key={item.paymentId} item={item} copiedId={copiedId} onCopy={copyItemLink} />
))}
</ul>
{result.failed > 0 ? (
<p className="rounded-xl bg-primary-soft px-4 py-3 text-xs leading-relaxed text-foreground/70">
Los que no se generaron quedaron guardados: vas a poder crearles el link desde
Cobros sin cargarle nada al alumno.
</p>
) : null}
<div className="flex justify-end">
<Button variant="primary" onClick={onClose}>
Listo
</Button>
</div>
</div>
) : (
<form
className="space-y-5"
onSubmit={(event) => {
event.preventDefault()
setSubmissionError(null)
create.mutate()
}}
>
<div className="flex items-center justify-between rounded-xl bg-primary-soft px-4 py-3">
<span className="text-sm text-foreground/70">Cuota del grupo</span>
<span className="text-sm font-semibold text-primary">{formatPrice(price)}</span>
</div>
<div className="space-y-4">
<div>
<Label htmlFor="charge-due-date" className="mb-1.5 block">
Vencimiento
</Label>
<Input
id="charge-due-date"
type="date"
required
autoFocus
value={dueDate}
onChange={(event) => {
setDueDate(event.target.value)
const picked = new Date(`${event.target.value}T12:00:00`)
if (!Number.isNaN(picked.getTime())) {
setDescription(monthLabel(picked).replace(/^./, (ch) => ch.toUpperCase()))
}
}}
className="[&::-webkit-calendar-picker-indicator]:opacity-60"
/>
</div>
<div>
<Label htmlFor="charge-description" className="mb-1.5 block">
Período o concepto
</Label>
<Input
id="charge-description"
type="text"
maxLength={120}
value={description}
onChange={(event) => setDescription(event.target.value)}
placeholder="Ej.: Octubre 2026"
/>
</div>
</div>
{submissionError ? (
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
{submissionError}
</p>
) : null}
<div className="flex items-center justify-end gap-3">
<Button type="button" variant="ghost" onClick={onClose}>
Cancelar
</Button>
<Button type="submit" variant="primary" disabled={create.isPending}>
{create.isPending ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Wallet className="size-4" />
)}
Crear links de pago
</Button>
</div>
</form>
)}
</Modal>
)
}

View File

@@ -1,6 +1,8 @@
import { useNavigate } from '@tanstack/react-router' import { useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react' import { Loader2 } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../../components/ui' import { Button } from '../../../components/ui'
import { ChargeMembersModal } from './ChargeMembersModal'
import { GroupHeader } from './GroupHeader' import { GroupHeader } from './GroupHeader'
import { GroupInfoCard } from './GroupInfoCard' import { GroupInfoCard } from './GroupInfoCard'
import { InviteLinkModal } from './InviteLinkModal' import { InviteLinkModal } from './InviteLinkModal'
@@ -22,13 +24,14 @@ export function GroupDetailView() {
isSubmittingRemoval, isSubmittingRemoval,
} = useGroupDetail() } = useGroupDetail()
const navigate = useNavigate() const navigate = useNavigate()
const [isChargeModalOpen, setIsChargeModalOpen] = useState(false)
return ( return (
<section className="animate-fade-in space-y-5 sm:space-y-6"> <section className="animate-fade-in space-y-5 sm:space-y-6">
{/* The large title always renders, even while loading: it is what gives {/* The large title always renders, even while loading: it is what gives
the immersive bar its height and stops the layout from jumping when the immersive bar its height and stops the layout from jumping when
the data arrives. */} the data arrives. */}
<GroupHeader /> <GroupHeader onCharge={() => setIsChargeModalOpen(true)} />
{groupQueryPending ? ( {groupQueryPending ? (
<div className="flex items-center justify-center py-20"> <div className="flex items-center justify-center py-20">
@@ -66,6 +69,10 @@ export function GroupDetailView() {
/> />
<WaitlistEntryDetailModal /> <WaitlistEntryDetailModal />
<PreRegistrationDetailModal /> <PreRegistrationDetailModal />
<ChargeMembersModal
isOpen={isChargeModalOpen}
onClose={() => setIsChargeModalOpen(false)}
/>
</section> </section>
) )
} }

View File

@@ -1,12 +1,12 @@
import { Link, useNavigate } from '@tanstack/react-router' import { Link, useNavigate } from '@tanstack/react-router'
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react' import { ArrowLeft, BarChart3, Share2, UserPlus, Wallet } from 'lucide-react'
import { Badge, Button, Tooltip } from '../../../components/ui' import { Badge, Button, Tooltip } from '../../../components/ui'
import { LargeTitle } from '../../../components/layout/LargeTitle' import { LargeTitle } from '../../../components/layout/LargeTitle'
import { cn } from '../../../lib/utils' import { cn } from '../../../lib/utils'
import { RISK_HINT, RISK_LABELS } from '../constants' import { RISK_HINT, RISK_LABELS } from '../constants'
import { useGroupDetail } from './GroupDetailProvider' import { useGroupDetail } from './GroupDetailProvider'
export function GroupHeader() { export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
const { const {
group, group,
groupTitle, groupTitle,
@@ -122,6 +122,20 @@ export function GroupHeader() {
<BarChart3 className="size-4 text-accent" /> <BarChart3 className="size-4 text-accent" />
<span className="hidden sm:inline">Estadísticas</span> <span className="hidden sm:inline">Estadísticas</span>
</Button> </Button>
<Button
variant="outline"
onClick={onCharge}
disabled={group?.price == null}
aria-label="Cobrar período"
title={group?.price == null ? 'Definí el precio del grupo para poder cobrar' : undefined}
className={cn(
'h-11 shrink-0 justify-center border-border',
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
)}
>
<Wallet className="size-4 text-accent" />
<span className="hidden sm:inline">Cobrar</span>
</Button>
{!isEmptyGroup ? ( {!isEmptyGroup ? (
<Button <Button
variant="outline" variant="outline"

View File

@@ -0,0 +1,82 @@
import type { CountryCode } from '@gruperly/shared'
import { COUNTRY_CURRENCY, COUNTRY_LABELS, DEFAULT_COUNTRY } from '@gruperly/shared'
import { ArrowLeft, ArrowRight } from 'lucide-react'
import { useState } from 'react'
import { Button } from '../../components/ui'
import { cn } from '../../lib/utils'
export const COUNTRY_OPTIONS: readonly CountryCode[] = [
'AR',
'BR',
'CL',
'CO',
'MX',
'PE',
'UY',
]
type CountryStepProps = {
onNext: () => void
onBack: () => void
}
/**
* Paso "País" del onboarding.
*
* El país del profesor define la moneda con la que se generan los links de
* cobro, así que se pregunta al empezar. Por default Argentina (la moneda por
* default es ARS); se cambia después desde Ajustes.
*/
export function CountryStep({ onNext, onBack }: CountryStepProps) {
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
return (
<section className="space-y-5">
<header className="space-y-1">
<h2 className="text-2xl font-bold text-primary">¿En qué país vas a cobrar?</h2>
<p className="text-sm text-foreground/60">
Tus links se generan en la moneda de ese país.
</p>
</header>
<div role="radiogroup" aria-label="País" className="space-y-2">
{COUNTRY_OPTIONS.map((code) => {
const isSelected = code === country
return (
<label
key={code}
className={cn(
'flex cursor-pointer items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3 transition-colors',
isSelected && 'border-accent bg-accent-soft ring-2 ring-accent/20',
)}
>
<input
type="radio"
name="country"
value={code}
checked={isSelected}
onChange={() => setCountry(code)}
className="size-4 accent-accent"
/>
<span className="flex-1 text-sm font-medium text-primary">
{COUNTRY_LABELS[code]}
</span>
<span className="text-sm text-foreground/50">{COUNTRY_CURRENCY[code]}</span>
</label>
)
})}
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={onBack} className="hidden lg:inline-flex">
<ArrowLeft className="size-4" />
Volver
</Button>
<Button variant="primary" className="flex-1 lg:flex-none" onClick={() => onNext()}>
Continuar
<ArrowRight className="size-4" />
</Button>
</div>
</section>
)
}

View File

@@ -2,6 +2,7 @@ import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared'
import { useMutation } from '@tanstack/react-query' import { useMutation } from '@tanstack/react-query'
import { createFirstGroup } from '../../lib/api' import { createFirstGroup } from '../../lib/api'
import { GroupForm } from '../groups/GroupForm' import { GroupForm } from '../groups/GroupForm'
import { useOnboarding } from './OnboardingProvider'
type FirstGroupStepProps = { type FirstGroupStepProps = {
onBack: () => void onBack: () => void
@@ -9,6 +10,7 @@ type FirstGroupStepProps = {
} }
export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) { export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) {
const { country } = useOnboarding()
const create = useMutation({ const create = useMutation({
mutationFn: (values: CreateFirstGroup) => createFirstGroup(values), mutationFn: (values: CreateFirstGroup) => createFirstGroup(values),
onSuccess: (result) => onCompleted(result.group), onSuccess: (result) => onCompleted(result.group),
@@ -19,6 +21,7 @@ export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) {
heading="Tu primer grupo" heading="Tu primer grupo"
description="Definí los datos de la clase que vas a cobrar. Después siempre podés editarlos." description="Definí los datos de la clase que vas a cobrar. Después siempre podés editarlos."
submitLabel="Crear grupo" submitLabel="Crear grupo"
country={country}
isSubmitting={create.isPending} isSubmitting={create.isPending}
errorMessage={ errorMessage={
create.isError ? 'No pudimos crear el grupo. Revisá los datos e intentá de nuevo.' : null create.isError ? 'No pudimos crear el grupo. Revisá los datos e intentá de nuevo.' : null

View File

@@ -1,4 +1,5 @@
import type { OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared' import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared'
import { DEFAULT_COUNTRY } from '@gruperly/shared'
import type { UseQueryResult } from '@tanstack/react-query' import type { UseQueryResult } from '@tanstack/react-query'
import { useQuery, useQueryClient } from '@tanstack/react-query' import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate, useSearch } from '@tanstack/react-router' import { useNavigate, useSearch } from '@tanstack/react-router'
@@ -10,12 +11,15 @@ import type { MpCallbackFeedback } from '../mp'
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp' import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
const WELCOME_STEP = 0 const WELCOME_STEP = 0
const PAYMENT_STEP = 1 const PAYMENT_STEP = 2
const FIRST_GROUP_STEP = 2 const FIRST_GROUP_STEP = 3
type OnboardingContextValue = { type OnboardingContextValue = {
step: number step: number
setStep: (step: number) => void setStep: (step: number) => void
/** El país del profesor; define la moneda de los links de cobro. */
country: CountryCode
setCountry: (country: CountryCode) => void
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */ /** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
mpFeedback: MpCallbackFeedback | null mpFeedback: MpCallbackFeedback | null
createdGroup: OnboardingGroupDto | null createdGroup: OnboardingGroupDto | null
@@ -31,6 +35,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
const search = useSearch({ from: '/onboarding' }) const search = useSearch({ from: '/onboarding' })
const [step, setStep] = useState(WELCOME_STEP) const [step, setStep] = useState(WELCOME_STEP)
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null) const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null) const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
@@ -79,6 +84,8 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
value={{ value={{
step, step,
setStep, setStep,
country,
setCountry,
mpFeedback, mpFeedback,
createdGroup, createdGroup,
setCreatedGroup, setCreatedGroup,

View File

@@ -5,6 +5,7 @@ import { Logo, LogoIcon } from '../../components/brand'
import { Button } from '../../components/ui' import { Button } from '../../components/ui'
import { useAuth } from '../../context/AuthProvider' import { useAuth } from '../../context/AuthProvider'
import { ConfirmationStep } from './ConfirmationStep' import { ConfirmationStep } from './ConfirmationStep'
import { CountryStep } from './CountryStep'
import { FirstGroupStep } from './FirstGroupStep' import { FirstGroupStep } from './FirstGroupStep'
import { useOnboarding } from './OnboardingProvider' import { useOnboarding } from './OnboardingProvider'
import { PaymentStep } from './PaymentStep' import { PaymentStep } from './PaymentStep'
@@ -13,6 +14,7 @@ import { WelcomeStep } from './WelcomeStep'
const STEPS = [ const STEPS = [
{ label: 'Bienvenida' }, { label: 'Bienvenida' },
{ label: 'País' },
{ label: 'Cobros' }, { label: 'Cobros' },
{ label: 'Tu grupo' }, { label: 'Tu grupo' },
{ label: 'Listo' }, { label: 'Listo' },
@@ -81,18 +83,21 @@ export function OnboardingView() {
<div key={step} className="mt-8 animate-step-enter"> <div key={step} className="mt-8 animate-step-enter">
{step === 0 ? <WelcomeStep name={firstName} onNext={() => setStep(1)} /> : null} {step === 0 ? <WelcomeStep name={firstName} onNext={() => setStep(1)} /> : null}
{step === 1 ? ( {step === 1 ? (
<PaymentStep feedback={mpFeedback} onNext={() => setStep(2)} onBack={() => setStep(0)} /> <CountryStep onNext={() => setStep(2)} onBack={() => setStep(0)} />
) : null} ) : null}
{step === 2 ? ( {step === 2 ? (
<PaymentStep feedback={mpFeedback} onNext={() => setStep(3)} onBack={() => setStep(1)} />
) : null}
{step === 3 ? (
<FirstGroupStep <FirstGroupStep
onBack={() => setStep(1)} onBack={() => setStep(2)}
onCompleted={(group) => { onCompleted={(group) => {
setCreatedGroup(group) setCreatedGroup(group)
setStep(3) setStep(4)
}} }}
/> />
) : null} ) : null}
{step === 3 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null} {step === 4 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
</div> </div>
</main> </main>
) )

View File

@@ -0,0 +1,93 @@
import type { PaymentDto } from '@gruperly/shared'
import { Check, Copy, Link2, Loader2, RefreshCw } from 'lucide-react'
import { useState } from 'react'
import { Badge, Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import { formatPrice, PAYMENT_STATUS_LABELS } from '../../lib/format'
import { paymentDateLabel, paymentPeriodLabel, PAYMENT_STATUS_BADGE } from './copy'
type PaymentRowProps = {
payment: PaymentDto
isRenewing: boolean
onRenew: (paymentId: string) => void
}
export function PaymentRow({ payment, isRenewing, onRenew }: PaymentRowProps) {
const [copied, setCopied] = useState(false)
const canCopy = Boolean(payment.checkoutUrl)
const canRenew = !payment.checkoutUrl || payment.status === 'CANCELLED'
const copyLink = async () => {
if (!payment.checkoutUrl) return
try {
await navigator.clipboard.writeText(payment.checkoutUrl)
setCopied(true)
window.setTimeout(() => setCopied(false), 1500)
} catch {
// No clipboard: the link is lost in silence, renew opens a new one later.
}
}
return (
<li className="rounded-xl border border-border bg-surface p-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold text-primary">
{payment.attendeeName}
<span className="ml-2 font-normal text-foreground/60">{payment.groupName}</span>
</p>
<p className="mt-1 flex flex-wrap items-center gap-x-2 text-sm">
<span className="font-medium text-primary">
{formatPrice(payment.amount, payment.currency)}
</span>
<span className="text-xs text-foreground/50">{paymentPeriodLabel(payment)}</span>
</p>
<p className="mt-1 text-xs text-foreground/50">{paymentDateLabel(payment)}</p>
</div>
<Badge variant={PAYMENT_STATUS_BADGE[payment.status]}>
{PAYMENT_STATUS_LABELS[payment.status]}
</Badge>
</div>
<div className="mt-3 flex items-center gap-2">
{canCopy ? (
<Button variant="outline" size="sm" onClick={() => void copyLink()}>
{copied ? (
<Check className="size-3.5 text-success" />
) : (
<Copy className="size-3.5 text-accent" />
)}
{copied ? 'Copiado' : 'Copiar link'}
</Button>
) : (
<span
className={cn(
'flex items-center gap-1.5 text-xs text-foreground/40',
payment.status === 'CANCELLED' && 'line-through',
)}
>
<Link2 className="size-3.5" />
Sin link
</span>
)}
{canRenew ? (
<Button
variant="outline"
size="sm"
className="ml-auto"
disabled={isRenewing}
onClick={() => onRenew(payment.id)}
>
{isRenewing ? (
<Loader2 className="size-3.5 animate-spin" />
) : (
<RefreshCw className="size-3.5 text-accent" />
)}
Generar link
</Button>
) : null}
</div>
</li>
)
}

View File

@@ -0,0 +1,132 @@
import type { PaymentDto, PaymentQuery, PaymentStatus } from '@gruperly/shared'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { ReactNode } from 'react'
import { createContext, useContext, useMemo, useState } from 'react'
import { ApiError, getGroups, getPayments, renewPaymentLink } from '../../lib/api'
export type PaymentFilterStatus = PaymentStatus | 'ALL'
const PAGE_SIZE = 20
function filterLabel(status: PaymentFilterStatus): string {
return status === 'ALL' ? '' : status
}
type PaymentsContextValue = {
payments: PaymentDto[]
total: number
page: number
totalPages: number
isPending: boolean
isFetching: boolean
isError: boolean
errorMessage: string | null
groupId: string | null
setGroupId: (groupId: string | null) => void
status: PaymentFilterStatus
setStatus: (status: PaymentFilterStatus) => void
setPage: (page: number) => void
retry: () => void
renew: (paymentId: string) => void
isRenewing: (paymentId: string) => boolean
groups: { id: string; name: string }[]
}
const PaymentsContext = createContext<PaymentsContextValue | null>(null)
export function PaymentsProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient()
const [page, setPage] = useState(1)
const [groupId, setGroupId] = useState<string | null>(null)
const [status, setStatus] = useState<PaymentFilterStatus>('ALL')
const params = useMemo<PaymentQuery>(
() => ({
page,
pageSize: PAGE_SIZE,
...(groupId ? { groupId } : {}),
...(status !== 'ALL' ? { status: filterLabel(status) as PaymentStatus } : {}),
}),
[page, groupId, status],
)
const paymentsQuery = useQuery({
queryKey: ['payments', params],
queryFn: () => getPayments(params),
placeholderData: (previous) => previous,
})
// El filtro por grupo reutiliza el query de la pestaña Grupos (misma clave).
const groupsQuery = useQuery({ queryKey: ['groups'], queryFn: getGroups })
const renewMutation = useMutation({
mutationFn: renewPaymentLink,
onSuccess: (updated) => {
queryClient.setQueriesData<{ data: PaymentDto[] }>(
{ queryKey: ['payments'] },
(current) =>
current
? {
...current,
data: current.data.map((payment) =>
payment.id === updated.id ? updated : payment,
),
}
: current,
)
void queryClient.invalidateQueries({ queryKey: ['payments'] })
},
})
const renew = (paymentId: string) => renewMutation.mutate(paymentId)
const isRenewing = (paymentId: string) => renewMutation.isPending && renewMutation.variables === paymentId
const data = paymentsQuery.data
const pagination = data?.pagination
const errorMessage = paymentsQuery.isError
? paymentsQuery.error instanceof ApiError
? paymentsQuery.error.problem?.detail ?? 'No pudimos cargar tus cobros.'
: 'No pudimos cargar tus cobros.'
: null
return (
<PaymentsContext.Provider
value={{
payments: data?.data ?? [],
total: pagination?.total ?? 0,
page,
totalPages: pagination?.totalPages ?? 1,
isPending: paymentsQuery.isPending,
isFetching: paymentsQuery.isFetching,
isError: paymentsQuery.isError,
errorMessage,
groupId,
setGroupId: (value) => {
setGroupId(value)
setPage(1)
},
status,
setStatus: (value) => {
setStatus(value)
setPage(1)
},
setPage,
retry: () => void paymentsQuery.refetch(),
renew,
isRenewing,
groups: groupsQuery.data?.data ?? [],
}}
>
{children}
</PaymentsContext.Provider>
)
}
export function usePayments() {
const context = useContext(PaymentsContext)
if (!context) {
throw new Error('usePayments debe usarse dentro de <PaymentsProvider>')
}
return context
}

View File

@@ -1,8 +1,163 @@
import type { PaymentStatus } from '@gruperly/shared'
import { ChevronLeft, ChevronRight, Loader2, Wallet } from 'lucide-react'
import { Button } from '../../components/ui'
import { cn } from '../../lib/utils'
import { PaymentRow } from './PaymentRow'
import { usePayments } from './PaymentsProvider'
const STATUS_FILTERS: readonly { value: 'ALL' | PaymentStatus; label: string }[] = [
{ value: 'ALL', label: 'Todos' },
{ value: 'PENDING', label: 'Pendientes' },
{ value: 'PAID', label: 'Pagados' },
{ value: 'OVERDUE', label: 'Vencidos' },
{ value: 'CANCELLED', label: 'Anulados' },
]
export function PaymentsView() { export function PaymentsView() {
const {
payments,
total,
page,
totalPages,
isPending,
isFetching,
isError,
errorMessage,
groupId,
setGroupId,
status,
setStatus,
setPage,
retry,
renew,
isRenewing,
groups,
} = usePayments()
return ( return (
<section> <section>
<h1 className="text-2xl font-bold text-primary">Cobros</h1> <div className="flex items-center justify-between gap-3">
<p className="mt-2 text-sm text-foreground/60">Sigue los pagos de tus grupos.</p> <div>
<h1 className="text-2xl font-bold text-primary">Cobros</h1>
<p className="mt-1 text-sm text-foreground/60">Seguí los pagos de tus grupos.</p>
</div>
</div>
{/* Filtros: el grupo primera (cada cobro cuelga de un grupo) y el estado. */}
<div className="mt-5 space-y-3">
<label className="block">
<span className="mb-1.5 block text-sm font-medium text-primary">Grupo</span>
<select
value={groupId ?? ''}
onChange={(event) => setGroupId(event.target.value || null)}
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
>
<option value="">Todos los grupos</option>
{groups.map((group) => (
<option key={group.id} value={group.id}>
{group.name}
</option>
))}
</select>
</label>
<div role="tablist" aria-label="Filtrar por estado" className="flex gap-2 overflow-x-auto">
{STATUS_FILTERS.map((filter) => {
const isActive = status === filter.value
return (
<button
key={filter.value}
type="button"
role="tab"
aria-selected={isActive}
onClick={() => setStatus(filter.value)}
className={cn(
'shrink-0 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors',
isActive
? 'border-accent bg-accent text-on-accent'
: 'border-border bg-surface text-foreground/70 hover:text-primary',
)}
>
{filter.label}
</button>
)
})}
</div>
</div>
{isPending ? (
<div className="mt-8 flex items-center justify-center py-16" role="status">
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
<span className="sr-only">Cargando cobros</span>
</div>
) : null}
{isError ? (
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
<p>{errorMessage}</p>
<Button variant="outline" size="sm" onClick={retry}>
Reintentar
</Button>
</div>
) : null}
{!isPending && !isError && payments.length === 0 ? (
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
<Wallet className="size-7" aria-hidden="true" />
</span>
<p className="mt-4 text-base font-semibold text-primary">Todavía no hay cobros</p>
<p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary">
Entrá a un grupo, abrí la ficha y creá los links de cobro del período.
</p>
</div>
) : null}
{!isPending && !isError && payments.length > 0 ? (
<>
<ul className="mt-5 space-y-3">
{payments.map((payment) => (
<PaymentRow
key={payment.id}
payment={payment}
isRenewing={isRenewing(payment.id)}
onRenew={renew}
/>
))}
</ul>
<div className="mt-6 flex items-center justify-between gap-3">
<Button
variant="outline"
size="sm"
disabled={page <= 1}
onClick={() => setPage(page - 1)}
>
<ChevronLeft className="size-4" />
Anteriores
</Button>
<p className="text-xs text-foreground/50">
Página {page} de {totalPages} · {total} cobros
</p>
<Button
variant="outline"
size="sm"
disabled={page >= totalPages}
onClick={() => setPage(page + 1)}
>
Siguientes
<ChevronRight className="size-4" />
</Button>
</div>
{isFetching && page > 1 ? (
<p className="flex items-center justify-center gap-2 py-4 text-sm text-foreground/50">
<Loader2 className="size-4 animate-spin" />
Actualizando…
</p>
) : null}
</>
) : null}
</section> </section>
) )
} }

View File

@@ -0,0 +1,32 @@
import type { PaymentDto } from '@gruperly/shared'
import type { BadgeVariant } from '../../components/ui'
export const PAYMENT_STATUS_BADGE: Record<PaymentDto['status'], BadgeVariant> = {
PENDING: 'neutral',
PAID: 'success',
OVERDUE: 'danger',
CANCELLED: 'warning',
}
export function paymentPeriodLabel(payment: PaymentDto): string {
return payment.description ?? payment.groupName
}
export function paymentDateLabel(payment: PaymentDto): string {
if (payment.status === 'PAID' && payment.paidAt) {
return `Cobrada el ${formatDay(payment.paidAt)}`
}
return `Vence el ${formatDay(payment.dueDate)}`
}
/* Fechas sin hora: el vencimiento es un día, no un instante. */
function formatDay(iso: string): string {
const date = new Date(iso)
const today = new Date()
const sameYear = date.getFullYear() === today.getFullYear()
return date.toLocaleDateString('es-MX', {
day: 'numeric',
month: 'short',
...(sameYear ? {} : { year: 'numeric' }),
})
}

View File

@@ -16,6 +16,8 @@ import type {
CreateFirstGroupResult, CreateFirstGroupResult,
CreateGroupResult, CreateGroupResult,
CreateGroupWaitlistEntry, CreateGroupWaitlistEntry,
CreatePaymentsBatch,
CreatePaymentsBatchResult,
GroupAnalytics, GroupAnalytics,
GroupDto, GroupDto,
GroupInviteInfoDto, GroupInviteInfoDto,
@@ -38,6 +40,9 @@ import type {
NotifyAbsence, NotifyAbsence,
NotifyAbsenceResult, NotifyAbsenceResult,
OnboardingStatusDto, OnboardingStatusDto,
PaymentDto,
PaymentList,
PaymentQuery,
ProblemDetails, ProblemDetails,
PromoteGroupWaitlistEntryResult, PromoteGroupWaitlistEntryResult,
PublicNotifyAbsence, PublicNotifyAbsence,
@@ -119,6 +124,27 @@ export const getMpStatus = () => apiFetch<MpStatusDto>('/api/v1/mp/status')
export const disconnectMp = () => export const disconnectMp = () =>
apiFetch<MpDisconnectResultDto>('/api/v1/mp/connect', { method: 'DELETE' }) apiFetch<MpDisconnectResultDto>('/api/v1/mp/connect', { method: 'DELETE' })
// — Cobros —
export const getPayments = (params: PaymentQuery) => {
const query = new URLSearchParams({
page: String(params.page ?? 1),
pageSize: String(params.pageSize ?? 20),
})
if (params.groupId) query.set('groupId', params.groupId)
if (params.status) query.set('status', params.status)
return apiFetch<PaymentList>(`/api/v1/payments?${query.toString()}`)
}
export const createPaymentsBatch = (groupId: string, payload: CreatePaymentsBatch) =>
apiFetch<CreatePaymentsBatchResult>(`/api/v1/groups/${groupId}/payments/batch`, {
method: 'POST',
body: JSON.stringify(payload),
})
export const renewPaymentLink = (paymentId: string) =>
apiFetch<PaymentDto>(`/api/v1/payments/${paymentId}/renew`, { method: 'POST' })
/* The groups screen has no pagination: we ask for the maximum allowed so no /* 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 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. */ backend sorts by the next class in the person's local time. */

View File

@@ -1,6 +1,11 @@
import { createFileRoute } from '@tanstack/react-router' import { createFileRoute } from '@tanstack/react-router'
import { PaymentsProvider } from '../../features/payments/PaymentsProvider'
import { PaymentsView } from '../../features/payments/PaymentsView' import { PaymentsView } from '../../features/payments/PaymentsView'
export const Route = createFileRoute('/_authenticated/payments')({ export const Route = createFileRoute('/_authenticated/payments')({
component: PaymentsView, component: () => (
}) <PaymentsProvider>
<PaymentsView />
</PaymentsProvider>
),
})

View File

@@ -4,6 +4,7 @@ export * from './lib/result.js';
export * from './schemas/analytics.js'; export * from './schemas/analytics.js';
export * from './schemas/attendance.js'; export * from './schemas/attendance.js';
export * from './schemas/attendees.js'; export * from './schemas/attendees.js';
export * from './schemas/country.js';
export * from './schemas/enums.js'; export * from './schemas/enums.js';
export * from './schemas/groups.js'; export * from './schemas/groups.js';
export * from './schemas/health-check.js'; export * from './schemas/health-check.js';

View File

@@ -0,0 +1,33 @@
import { z } from 'zod';
// Countries where Mercado Pago operates and Gruperly collects. The professor
// picks one during onboarding; it drives the currency of the payment links.
export const countryCodeSchema = z.enum(['AR', 'BR', 'CL', 'CO', 'MX', 'PE', 'UY']);
export type CountryCode = z.output<typeof countryCodeSchema>;
export const COUNTRY_CURRENCY: Record<CountryCode, string> = {
AR: 'ARS',
BR: 'BRL',
CL: 'CLP',
CO: 'COP',
MX: 'MXN',
PE: 'PEN',
UY: 'UYU',
};
export const COUNTRY_LABELS: Record<CountryCode, string> = {
AR: 'Argentina',
BR: 'Brasil',
CL: 'Chile',
CO: 'Colombia',
MX: 'México',
PE: 'Perú',
UY: 'Uruguay',
};
export const DEFAULT_COUNTRY: CountryCode = 'AR';
export const DEFAULT_CURRENCY = COUNTRY_CURRENCY[DEFAULT_COUNTRY];
export function currencyForCountry(country: CountryCode | null | undefined): string {
return country ? COUNTRY_CURRENCY[country] : DEFAULT_CURRENCY;
}

View File

@@ -1,12 +1,17 @@
import { z } from 'zod'; import { z } from 'zod';
import { countryCodeSchema, DEFAULT_COUNTRY } from './country.js';
import { billingTypeSchema, weekdaySchema } from './enums.js'; import { billingTypeSchema, weekdaySchema } from './enums.js';
import { GroupDtoSchema } from './groups.js'; import { GroupDtoSchema } from './groups.js';
export { countryCodeSchema } from './country.js';
export type { BillingType, WeekDay } from './enums.js'; export type { BillingType, WeekDay } from './enums.js';
export { billingTypeSchema, weekdaySchema } from './enums.js'; export { billingTypeSchema, weekdaySchema } from './enums.js';
// Step 3: create the teacher's first group. Linking Mercado Pago is step 2 and // Step 4: create the teacher's first group. Linking Mercado Pago is step 2 and
// is skippable, so nothing here may require a linked account. // is skippable, so nothing here may require a linked account. The country is
// stored on the user and drives the currency of the payment links later. It
// defaults to Argentina because the group form (also used outside onboarding)
// has no country field: the country lives on the user, not on the group.
export const CreateFirstGroupSchema = z.strictObject({ export const CreateFirstGroupSchema = z.strictObject({
name: z name: z
.string() .string()
@@ -30,6 +35,7 @@ export const CreateFirstGroupSchema = z.strictObject({
.int({ message: 'El día debe ser un número entero' }) .int({ message: 'El día debe ser un número entero' })
.min(1, 'El día de vencimiento debe estar entre 1 y 28') .min(1, 'El día de vencimiento debe estar entre 1 y 28')
.max(28, 'El día de vencimiento debe estar entre 1 y 28'), .max(28, 'El día de vencimiento debe estar entre 1 y 28'),
country: countryCodeSchema.default(DEFAULT_COUNTRY),
}); });
export type CreateFirstGroup = z.output<typeof CreateFirstGroupSchema>; export type CreateFirstGroup = z.output<typeof CreateFirstGroupSchema>;

View File

@@ -7,14 +7,19 @@ const pageSizeSchema = createPageSizeSchema(10);
const paginationSchema = createPaginationSchema(); const paginationSchema = createPaginationSchema();
export const paymentStatusSchema = z.enum(['PENDING', 'PAID', 'OVERDUE', 'CANCELLED']); export const paymentStatusSchema = z.enum(['PENDING', 'PAID', 'OVERDUE', 'CANCELLED']);
export type PaymentStatus = z.output<typeof paymentStatusSchema>;
export const PaymentDtoSchema = z.object({ export const PaymentDtoSchema = z.object({
id: z.string(), id: z.string(),
groupId: z.string(), groupId: z.string(),
groupName: z.string(),
attendeeId: z.string(), attendeeId: z.string(),
attendeeName: z.string(),
amount: z.coerce.number().positive(), amount: z.coerce.number().positive(),
currency: z.string(), currency: z.string(),
status: paymentStatusSchema, status: paymentStatusSchema,
description: z.string().nullable(),
checkoutUrl: z.string().nullable(),
dueDate: isoDateTimeSchema, dueDate: isoDateTimeSchema,
paidAt: isoDateTimeSchema.nullable(), paidAt: isoDateTimeSchema.nullable(),
createdAt: isoDateTimeSchema, createdAt: isoDateTimeSchema,
@@ -25,6 +30,8 @@ export type PaymentDto = z.output<typeof PaymentDtoSchema>;
export const PaymentQuerySchema = z.object({ export const PaymentQuerySchema = z.object({
page: pageSchema, page: pageSchema,
pageSize: pageSizeSchema, pageSize: pageSizeSchema,
groupId: z.string().min(1).optional(),
status: paymentStatusSchema.optional(),
}); });
export type PaymentQuery = z.output<typeof PaymentQuerySchema>; export type PaymentQuery = z.output<typeof PaymentQuerySchema>;
@@ -32,4 +39,36 @@ export const PaymentListSchema = z.object({
data: z.array(PaymentDtoSchema), data: z.array(PaymentDtoSchema),
pagination: paginationSchema, pagination: paginationSchema,
}); });
export type PaymentList = z.output<typeof PaymentListSchema>; export type PaymentList = z.output<typeof PaymentListSchema>;
// Creates one payment link per active attendee of a group. The professor
// triggers it from the group page for a period (e.g. June's monthly fee).
export const CreatePaymentsBatchSchema = z.strictObject({
dueDate: isoDateTimeSchema,
description: z.string().trim().max(120, 'La descripción es demasiado larga').optional(),
attendeeIds: z.array(z.string().min(1)).min(1).optional(),
});
export type CreatePaymentsBatch = z.output<typeof CreatePaymentsBatchSchema>;
export const paymentBatchOutcomeSchema = z.enum(['CREATED', 'LINKED', 'FAILED']);
export const PaymentBatchItemSchema = z.object({
paymentId: z.string(),
attendeeId: z.string(),
attendeeName: z.string(),
amount: z.number().positive(),
currency: z.string(),
checkoutUrl: z.string().nullable(),
outcome: paymentBatchOutcomeSchema,
reason: z.string().nullable(),
});
export type PaymentBatchItem = z.output<typeof PaymentBatchItemSchema>;
export const CreatePaymentsBatchResultSchema = z.object({
groupId: z.string(),
total: z.number().int().min(0),
linked: z.number().int().min(0),
failed: z.number().int().min(0),
items: z.array(PaymentBatchItemSchema),
});
export type CreatePaymentsBatchResult = z.output<typeof CreatePaymentsBatchResultSchema>;